This repository has been archived by the owner on Jul 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
dtls.c
2504 lines (2035 loc) · 70.6 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
/* dtls -- a very basic DTLS implementation
*
* Copyright (C) 2011--2012 Olaf Bergmann <[email protected]>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_ASSERT_H
#include <assert.h>
#endif
#ifdef HAVE_TIME_H
#include <time.h>
#define clock_time() (time(NULL))
#ifndef CLOCK_SECOND
# define CLOCK_SECOND 1024
#endif
#endif
#ifndef WITH_CONTIKI
#include <stdlib.h>
#include "uthash.h"
#else /* WITH_CONTIKI */
# ifndef NDEBUG
# define DEBUG DEBUG_PRINT
# include "net/uip-debug.h"
# endif /* NDEBUG */
#endif /* WITH_CONTIKI */
#include "debug.h"
#include "numeric.h"
#include "netq.h"
#include "dtls.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)
#ifndef WITH_CONTIKI
#define HASH_FIND_PEER(head,sess,out) \
HASH_FIND(hh,head,sess,sizeof(session_t),out)
#define HASH_ADD_PEER(head,sess,add) \
HASH_ADD(hh,head,sess,sizeof(session_t),add)
#define HASH_DEL_PEER(head,delptr) \
HASH_DELETE(hh,head,delptr)
#endif /* WITH_CONTIKI */
#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_HV_LENGTH sizeof(dtls_hello_verify_t)
#define DTLS_SH_LENGTH (2 + 32 + 1 + 2 + 1)
#define DTLS_CKX_LENGTH 1
#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))
#define IS_HELLOVERIFY(M,L) \
((L) >= DTLS_HS_LENGTH + DTLS_HV_LENGTH && (M)[0] == DTLS_HT_HELLO_VERIFY_REQUEST)
#define IS_SERVERHELLO(M,L) \
((L) >= DTLS_HS_LENGTH + 6 && (M)[0] == DTLS_HT_SERVER_HELLO)
#define IS_SERVERHELLODONE(M,L) \
((L) >= DTLS_HS_LENGTH && (M)[0] == DTLS_HT_SERVER_HELLO_DONE)
#define IS_FINISHED(M,L) \
((L) >= DTLS_HS_LENGTH + DTLS_FIN_LENGTH && (M)[0] == DTLS_HT_FINISHED)
/* 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); \
}
#define CURRENT_CONFIG(Peer) (&(Peer)->security_params[(Peer)->config])
#define OTHER_CONFIG(Peer) (&(Peer)->security_params[!((Peer)->config & 0x01)])
#define SWITCH_CONFIG(Peer) ((Peer)->config = !((Peer)->config & 0x01))
uint8 _clear[DTLS_MAX_BUF]; /* target buffer message decryption */
uint8 _buf[DTLS_MAX_BUF]; /* target buffer for several crypto operations */
#ifndef NDEBUG
void hexdump(const unsigned char *packet, int length);
void dump(unsigned char *buf, size_t len);
#endif
/* 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";
extern void netq_init();
extern void crypto_init();
dtls_context_t the_dtls_context;
#ifndef WITH_CONTIKI
static inline dtls_peer_t *
dtls_malloc_peer() {
return (dtls_peer_t *)malloc(sizeof(dtls_peer_t));
}
static inline void
dtls_free_peer(dtls_peer_t *peer) {
free(peer);
}
#else /* WITH_CONTIKI */
PROCESS(dtls_retransmit_process, "DTLS retransmit process");
#include "memb.h"
MEMB(peer_storage, dtls_peer_t, DTLS_PEER_MAX);
static inline dtls_peer_t *
dtls_malloc_peer() {
return memb_alloc(&peer_storage);
}
static inline void
dtls_free_peer(dtls_peer_t *peer) {
memb_free(&peer_storage, peer);
}
#endif /* WITH_CONTIKI */
void
dtls_init() {
netq_init();
crypto_init();
#ifdef WITH_CONTIKI
memb_init(&peer_storage);
#endif /* WITH_CONTIKI */
}
/* 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)
/**
* 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.
*/
int dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
uint8 *buf, size_t buflen);
/**
* Stops ongoing retransmissions of handshake messages for @p peer.
*/
void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
dtls_peer_t *
dtls_get_peer(struct dtls_context_t *ctx, const session_t *session) {
dtls_peer_t *p = NULL;
#ifndef WITH_CONTIKI
HASH_FIND_PEER(ctx->peers, session, p);
#else /* WITH_CONTIKI */
for (p = list_head(ctx->peers); p; p = list_item_next(p))
if (dtls_session_equals(&p->session, session))
return p;
#endif /* WITH_CONTIKI */
return p;
}
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);
if (peer && peer->state == DTLS_STATE_CONNECTED)
return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
else
return peer ? 0 : -1;
}
int
dtls_get_cookie(uint8 *msg, int 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)
|| dtls_uint16_to_int(msg + DTLS_HS_LENGTH) != DTLS_VERSION)
return -1;
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 -1;
*cookie = msg + sizeof(uint8);
return dtls_uint8_to_int(msg);
error:
return -1;
}
int
dtls_create_cookie(dtls_context_t *ctx,
session_t *session,
uint8 *msg, int 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);
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);
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 1;
}
#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, int 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 peer.
* \return pointer to the next byte after the written header
*/
static inline uint8 *
dtls_set_record_header(uint8 type, dtls_peer_t *peer, uint8 *buf) {
dtls_int_to_uint8(buf, type);
buf += sizeof(uint8);
dtls_int_to_uint16(buf, DTLS_VERSION);
buf += sizeof(uint16);
if (peer) {
memcpy(buf, &peer->epoch, sizeof(uint16) + sizeof(uint48));
/* increment record sequence counter by 1 */
inc_uint(uint48, peer->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) {
/* increment handshake message sequence counter by 1 */
inc_uint(uint16, peer->hs_state.mseq);
/* and copy the result to buf */
memcpy(buf, &peer->hs_state.mseq, sizeof(uint16));
} 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;
}
/**
* Checks a received Client Hello message for a valid cookie. When the
* Client Hello contains no cookie, the function fails and a Hello
* Verify Request is sent to the peer (using the write callback function
* registered with \p ctx). The return value is \c -1 on error, \c 0 when
* undecided, and \c 1 if the Client Hello was good.
*
* \param ctx The DTLS context.
* \param peer The remote party we are talking to, if any.
* \param session Transport address of the remote peer.
* \param msg The received datagram.
* \param msglen Length of \p msg.
* \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
* \c -1 otherwise.
*/
int
dtls_verify_peer(dtls_context_t *ctx,
dtls_peer_t *peer,
session_t *session,
uint8 *record,
uint8 *data, size_t data_length) {
int len = DTLS_COOKIE_LENGTH;
uint8 *cookie, *p;
#undef mycookie
#define mycookie (ctx->sendbuf + HV_HDR_LENGTH)
/* check if we can access at least all fields from the handshake header */
if (record[0] == DTLS_CT_HANDSHAKE
&& data_length >= DTLS_HS_LENGTH
&& data[0] == DTLS_HT_CLIENT_HELLO) {
/* Store cookie where we can reuse it for the HelloVerify request. */
if (dtls_create_cookie(ctx, session, data, data_length,
mycookie, &len) < 0)
return -1;
#ifndef NDEBUG
debug("create cookie: ");
dump(mycookie, len);
printf("\n");
#endif
assert(len == DTLS_COOKIE_LENGTH);
/* Perform cookie check. */
len = dtls_get_cookie(data, data_length, &cookie);
#ifndef NDEBUG
debug("compare with cookie: ");
dump(cookie, len);
printf("\n");
#endif
/* check if cookies match */
if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
debug("found matching cookie\n");
return 1;
}
#ifndef NDEBUG
if (len > 0) {
debug("invalid cookie:");
dump(cookie, len);
printf("\n");
} else {
debug("cookie len is 0!\n");
}
#endif
/* ClientHello did not contain any valid cookie, hence we send a
* HelloVerify request. */
p = dtls_set_handshake_header(DTLS_HT_HELLO_VERIFY_REQUEST,
peer, DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH,
0, DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH,
ctx->sendbuf + DTLS_RH_LENGTH);
dtls_int_to_uint16(p, DTLS_VERSION);
p += sizeof(uint16);
dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
p += sizeof(uint8);
assert(p == mycookie);
p += DTLS_COOKIE_LENGTH;
if (!peer) {
/* It's an initial ClientHello, so we set the record header
* manually and send the HelloVerify request using the
* registered write callback. */
dtls_set_record_header(DTLS_CT_HANDSHAKE, NULL, ctx->sendbuf);
/* set packet length */
dtls_int_to_uint16(ctx->sendbuf + 11,
p - (ctx->sendbuf + DTLS_RH_LENGTH));
(void)CALL(ctx, write, session, ctx->sendbuf, p - ctx->sendbuf);
} else {
if (peer->epoch) {
debug("renegotiation, therefore we accept it anyway:");
return 1;
}
if (dtls_send(ctx, peer, DTLS_CT_HANDSHAKE,
ctx->sendbuf + DTLS_RH_LENGTH,
p - (ctx->sendbuf + DTLS_RH_LENGTH)) < 0) {
warn("cannot send HelloVerify request\n");
return -1;
}
}
return 0; /* HelloVerify is sent, now we cannot do anything but wait */
}
return -1; /* not a ClientHello, signal error */
#undef mycookie
}
/** only one compression method is currently defined */
uint8 compression_methods[] = {
TLS_COMP_NULL
};
/**
* Returns @c 1 if @p code is a cipher suite other than @c
* TLS_NULL_WITH_NULL_NULL that we recognize.
*
* @param code The cipher suite identifier to check
* @return @c 1 iff @p code is recognized,
*/
static inline int
known_cipher(dtls_cipher_t code) {
return code == TLS_PSK_WITH_AES_128_CCM_8;
}
int
calculate_key_block(dtls_context_t *ctx,
dtls_security_parameters_t *config,
const dtls_key_t *key,
unsigned char client_random[32],
unsigned char server_random[32]) {
unsigned char *pre_master_secret;
size_t pre_master_len = 0;
pre_master_secret = config->key_block;
assert(key);
switch (key->type) {
case DTLS_KEY_PSK: {
/* Temporarily use the key_block storage space for the pre master secret. */
pre_master_len = dtls_pre_master_secret(key->key.psk.key, key->key.psk.key_length,
pre_master_secret);
break;
}
default:
debug("calculate_key_block: unknown key type\n");
return 0;
}
#ifndef NDEBUG
{
int i;
printf("client_random:");
for (i = 0; i < 32; ++i)
printf(" %02x", client_random[i]);
printf("\n");
printf("server_random:");
for (i = 0; i < 32; ++i)
printf(" %02x", server_random[i]);
printf("\n");
printf("psk: (%lu bytes):", key->key.psk.key_length);
hexdump(key->key.psk.key, key->key.psk.key_length);
printf("\n");
printf("pre_master_secret: (%lu bytes):", pre_master_len);
for (i = 0; i < pre_master_len; ++i)
printf(" %02x", pre_master_secret[i]);
printf("\n");
}
#endif /* NDEBUG */
dtls_prf(pre_master_secret, pre_master_len,
PRF_LABEL(master), PRF_LABEL_SIZE(master),
client_random, 32,
server_random, 32,
config->master_secret,
DTLS_MASTER_SECRET_LENGTH);
#ifndef NDEBUG
{
int i;
printf("master_secret (%d bytes):", DTLS_MASTER_SECRET_LENGTH);
for (i = 0; i < DTLS_MASTER_SECRET_LENGTH; ++i)
printf(" %02x", config->master_secret[i]);
printf("\n");
}
#endif /* NDEBUG */
/* create key_block from master_secret
* key_block = PRF(master_secret,
"key expansion" + server_random + client_random) */
dtls_prf(config->master_secret,
DTLS_MASTER_SECRET_LENGTH,
PRF_LABEL(key), PRF_LABEL_SIZE(key),
server_random, 32,
client_random, 32,
config->key_block,
dtls_kb_size(config));
#ifndef NDEBUG
{
printf("key_block (%d bytes):\n", dtls_kb_size(config));
printf(" client_MAC_secret:\t");
dump(dtls_kb_client_mac_secret(config),
dtls_kb_mac_secret_size(config));
printf("\n");
printf(" server_MAC_secret:\t");
dump(dtls_kb_server_mac_secret(config),
dtls_kb_mac_secret_size(config));
printf("\n");
printf(" client_write_key:\t");
dump(dtls_kb_client_write_key(config),
dtls_kb_key_size(config));
printf("\n");
printf(" server_write_key:\t");
dump(dtls_kb_server_write_key(config),
dtls_kb_key_size(config));
printf("\n");
printf(" client_IV:\t\t");
dump(dtls_kb_client_iv(config),
dtls_kb_iv_size(config));
printf("\n");
printf(" server_IV:\t\t");
dump(dtls_kb_server_iv(config),
dtls_kb_iv_size(config));
printf("\n");
}
#endif
return 1;
}
/**
* Updates the security parameters of given \p peer. As this must be
* done before the new configuration is activated, it changes the
* OTHER_CONFIG only. When the ClientHello handshake message in \p
* data does not contain a cipher suite or compression method, it is
* copied from the CURRENT_CONFIG.
*
* \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 0 if an error occurred, \c 1 otherwise.
*/
int
dtls_update_parameters(dtls_context_t *ctx,
dtls_peer_t *peer,
uint8 *data, size_t data_length) {
int i, j;
int ok;
dtls_security_parameters_t *config = OTHER_CONFIG(peer);
assert(config);
assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
/* debug("dtls_update_parameters: msglen is %d\n", data_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
* FIXME: if we send the ServerHello here, we do not need to store
* the client's random bytes */
memcpy(config->client_random, data, sizeof(config->client_random));
data += sizeof(config->client_random);
data_length -= sizeof(config->client_random);
/* 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 (CURRENT_CONFIG(peer)->cipher == TLS_NULL_WITH_NULL_NULL)
goto error;
config->cipher = CURRENT_CONFIG(peer)->cipher;
config->compression = CURRENT_CONFIG(peer)->compression;
return 1;
}
data += sizeof(uint16);
data_length -= sizeof(uint16) + i;
ok = 0;
while (i && !ok) {
config->cipher = dtls_uint16_to_int(data);
ok = known_cipher(config->cipher);
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;
return 0;
}
if (data_length < sizeof(uint8)) {
/* no compression specified, take the current compression method */
config->compression = CURRENT_CONFIG(peer)->compression;
return 1;
}
i = dtls_uint8_to_int(data);
if (data_length < i + sizeof(uint8))
goto error;
data += sizeof(uint8);
data_length -= sizeof(uint8) + i;
ok = 0;
while (i && !ok) {
for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
if (dtls_uint8_to_int(data) == compression_methods[j]) {
config->compression = compression_methods[j];
ok = 1;
}
i -= sizeof(uint8);
data += sizeof(uint8);
}
return ok;
error:
warn("ClientHello too short (%d bytes)\n", data_length);
return 0;
}
static inline int
check_client_keyexchange(dtls_context_t *ctx,
dtls_peer_t *peer,
uint8 *data, size_t length) {
return length >= DTLS_CKX_LENGTH && data[0] == DTLS_HT_CLIENT_KEY_EXCHANGE;
}
static int
check_ccs(dtls_context_t *ctx,
dtls_peer_t *peer,
uint8 *record, uint8 *data, size_t data_length) {
if (DTLS_RECORD_HEADER(record)->content_type != DTLS_CT_CHANGE_CIPHER_SPEC
|| data_length < 1 || data[0] != 1)
return 0;
/* set crypto context for TLS_PSK_WITH_AES_128_CCM_8 */
/* client */
dtls_cipher_free(OTHER_CONFIG(peer)->read_cipher);
assert(OTHER_CONFIG(peer)->cipher != TLS_NULL_WITH_NULL_NULL);
OTHER_CONFIG(peer)->read_cipher =
dtls_cipher_new(OTHER_CONFIG(peer)->cipher,
dtls_kb_client_write_key(OTHER_CONFIG(peer)),
dtls_kb_key_size(OTHER_CONFIG(peer)));
if (!OTHER_CONFIG(peer)->read_cipher) {
warn("cannot create read cipher\n");
return 0;
}
dtls_cipher_set_iv(OTHER_CONFIG(peer)->read_cipher,
dtls_kb_client_iv(OTHER_CONFIG(peer)),
dtls_kb_iv_size(OTHER_CONFIG(peer)));
/* server */
dtls_cipher_free(OTHER_CONFIG(peer)->write_cipher);
OTHER_CONFIG(peer)->write_cipher =
dtls_cipher_new(OTHER_CONFIG(peer)->cipher,
dtls_kb_server_write_key(OTHER_CONFIG(peer)),
dtls_kb_key_size(OTHER_CONFIG(peer)));
if (!OTHER_CONFIG(peer)->write_cipher) {
warn("cannot create write cipher\n");
return 0;
}
dtls_cipher_set_iv(OTHER_CONFIG(peer)->write_cipher,
dtls_kb_server_iv(OTHER_CONFIG(peer)),
dtls_kb_iv_size(OTHER_CONFIG(peer)));
return 1;
}
#ifndef NDEBUG
extern size_t dsrv_print_addr(const session_t *, unsigned char *, size_t);
#endif
dtls_peer_t *
dtls_new_peer(dtls_context_t *ctx,
const session_t *session) {
dtls_peer_t *peer;
peer = dtls_malloc_peer();
if (peer) {
memset(peer, 0, sizeof(dtls_peer_t));
memcpy(&peer->session, session, sizeof(session_t));
#ifndef NDEBUG
{
unsigned char addrbuf[72];
dsrv_print_addr(session, addrbuf, sizeof(addrbuf));
printf("dtls_new_peer: %s\n", addrbuf);
dump((unsigned char *)session, sizeof(session_t));
printf("\n");
}
#endif
/* initially allow the NULL cipher */
CURRENT_CONFIG(peer)->cipher = TLS_NULL_WITH_NULL_NULL;
/* initialize the handshake hash wrt. the hard-coded DTLS version */
debug("DTLSv12: initialize HASH_SHA256\n");
/* TLS 1.2: PRF(secret, label, seed) = P_<hash>(secret, label + seed) */
/* FIXME: we use the default SHA256 here, might need to support other
hash functions as well */
dtls_hash_init(&peer->hs_state.hs_hash);
}
return peer;
}
static inline void
update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
#ifndef NDEBUG
printf("add MAC data: ");
dump(data, length);
printf("\n");
#endif
dtls_hash_update(&peer->hs_state.hs_hash, data, length);
}
static inline size_t
finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
return dtls_hash_finalize(buf, &peer->hs_state.hs_hash);
}
static inline void
clear_hs_hash(dtls_peer_t *peer) {
assert(peer);
dtls_hash_init(&peer->hs_state.hs_hash);
}
/**
*Checks if \p record + \p data contain a Finished message with valid
* verify_data.
*
* \param ctx The current DTLS context.
* \param peer The remote peer of the security association.
* \param record The message record header.
* \param rlen The actual length of \p record.
* \param data The cleartext payload of the message.
* \param data_length Actual length of \p data.
* \return \c 1 if the Finished message is valid, \c 0 otherwise.
*/
static int
check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
uint8 *record, uint8 *data, size_t data_length) {
size_t digest_length, label_size;
const unsigned char *label;
unsigned char buf[DTLS_HMAC_MAX];
/* Use a union here to ensure that sufficient stack space is
* reserved. As statebuf and verify_data are not used at the same
* time, we can re-use the storage safely.
*/
union {
unsigned char statebuf[DTLS_HASH_CTX_SIZE];
unsigned char verify_data[DTLS_FIN_LENGTH];
} b;
debug("check Finish message\n");
if (record[0] != DTLS_CT_HANDSHAKE || !IS_FINISHED(data, data_length)) {
debug("failed\n");
return 0;
}
/* temporarily store hash status for roll-back after finalize */
memcpy(b.statebuf, &peer->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
digest_length = finalize_hs_hash(peer, buf);
/* clear_hash(); */
/* restore hash status */
memcpy(&peer->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
if (CURRENT_CONFIG(peer)->role == DTLS_SERVER) {
label = PRF_LABEL(server);
label_size = PRF_LABEL_SIZE(server);
} else { /* client */
label = PRF_LABEL(client);
label_size = PRF_LABEL_SIZE(client);
}
dtls_prf(CURRENT_CONFIG(peer)->master_secret,
DTLS_MASTER_SECRET_LENGTH,
label, label_size,
PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
buf, digest_length,
b.verify_data, sizeof(b.verify_data));
#ifndef NDEBUG
printf("d:\t"); dump(data + DTLS_HS_LENGTH, sizeof(b.verify_data)); printf("\n");
printf("v:\t"); dump(b.verify_data, sizeof(b.verify_data)); printf("\n");
#endif
return
memcmp(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data)) == 0;
}
/**
* Prepares the payload given in \p data for sending with
* dtls_send(). The \p data is encrypted and compressed according to
* the current security parameters of \p peer. The result of this
* operation is put into \p sendbuf with a prepended record header of
* type \p type ready for sending. As some cipher suites add a MAC
* before encryption, \p data must be large enough to hold this data
* as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
*
* \param peer The remote peer the packet will be sent to.
* \param type The content type of this record.
* \param data The payload to send.
* \param data_length The size of \p data.
* \param sendbuf The output buffer where the encrypted record
* will be placed.
* \param rlen This parameter must be initialized with the
* maximum size of \p sendbuf and will be updated
* to hold the actual size of the stored packet
* on success. On error, the value of \p rlen is
* undefined.
* \return Less than zero on error, or greater than zero success.
*/
int
dtls_prepare_record(dtls_peer_t *peer,
unsigned char type,
uint8 *data, size_t data_length,
uint8 *sendbuf, size_t *rlen) {
uint8 *p;
int res;
/* check the minimum that we need for packets that are not encrypted */
if (*rlen < DTLS_RH_LENGTH + data_length) {
debug("dtls_prepare_record: send buffer too small\n");
return -1;
}
p = dtls_set_record_header(type, peer, sendbuf);
if (CURRENT_CONFIG(peer)->cipher == TLS_NULL_WITH_NULL_NULL) {
/* no cipher suite */
memcpy(p, data, data_length);
res = data_length;
} else { /* TLS_PSK_WITH_AES_128_CCM_8 */