tinydtls  0.8.6
dtls.c
Go to the documentation of this file.
1 /*******************************************************************************
2  *
3  * Copyright (c) 2011, 2012, 2013, 2014, 2015 Olaf Bergmann (TZI) and others.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
7  *
8  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
9  * and the Eclipse Distribution License is available at
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  *
12  * Contributors:
13  * Olaf Bergmann - initial API and implementation
14  * Hauke Mehrtens - memory optimization, ECC integration
15  * Achim Kraus - session recovery
16  * Sachin Agrawal - rehandshake support
17  *
18  *******************************************************************************/
19 
20 #include "tinydtls.h"
21 #include "dtls_time.h"
22 
23 #include <stdio.h>
24 #include <stdlib.h>
25 #ifdef HAVE_ASSERT_H
26 #include <assert.h>
27 #endif
28 #ifndef WITH_CONTIKI
29 #include <stdlib.h>
30 #include "global.h"
31 #endif /* WITH_CONTIKI */
32 #ifdef HAVE_INTTYPES_H
33 #define __STDC_FORMAT_MACROS
34 #include <inttypes.h>
35 #else
36 # ifndef PRIu64
37 # define PRIu64 "llu"
38 # endif
39 # ifndef PRIx64
40 # define PRIx64 "llx"
41 # endif
42 #endif /* HAVE_INTTYPES_H */
43 
44 #include "utlist.h"
45 #ifndef DTLS_PEERS_NOHASH
46 #include "uthash.h"
47 #endif /* DTLS_PEERS_NOHASH */
48 
49 #include "dtls_debug.h"
50 #include "numeric.h"
51 #include "netq.h"
52 #include "dtls.h"
53 
54 #include "alert.h"
55 #include "session.h"
56 #include "prng.h"
57 
58 #ifdef WITH_SHA256
59 # include "sha2/sha2.h"
60 #endif
61 
62 #define dtls_set_version(H,V) dtls_int_to_uint16((H)->version, (V))
63 #define dtls_set_content_type(H,V) ((H)->content_type = (V) & 0xff)
64 #define dtls_set_length(H,V) ((H)->length = (V))
65 
66 #define dtls_get_content_type(H) ((H)->content_type & 0xff)
67 #define dtls_get_version(H) dtls_uint16_to_int((H)->version)
68 #define dtls_get_epoch(H) dtls_uint16_to_int((H)->epoch)
69 #define dtls_get_sequence_number(H) dtls_uint48_to_ulong((H)->sequence_number)
70 #define dtls_get_fragment_length(H) dtls_uint24_to_int((H)->fragment_length)
71 
72 #ifdef DTLS_PEERS_NOHASH
73 #define FIND_PEER(head,sess,out) \
74  do { \
75  dtls_peer_t * tmp; \
76  (out) = NULL; \
77  LL_FOREACH((head), tmp) { \
78  if (dtls_session_equals(&tmp->session, (sess))) { \
79  (out) = tmp; \
80  break; \
81  } \
82  } \
83  } while (0)
84 #define DEL_PEER(head,delptr) \
85  if ((head) != NULL && (delptr) != NULL) { \
86  LL_DELETE(head,delptr); \
87  }
88 #define ADD_PEER(head,sess,add) \
89  LL_PREPEND(ctx->peers, peer);
90 #else /* DTLS_PEERS_NOHASH */
91 #define FIND_PEER(head,sess,out) \
92  HASH_FIND(hh,head,sess,sizeof(session_t),out)
93 #define ADD_PEER(head,sess,add) \
94  HASH_ADD(hh,head,sess,sizeof(session_t),add)
95 #define DEL_PEER(head,delptr) \
96  if ((head) != NULL && (delptr) != NULL) { \
97  HASH_DELETE(hh,head,delptr); \
98  }
99 #endif /* DTLS_PEERS_NOHASH */
100 
101 #define DTLS_RH_LENGTH sizeof(dtls_record_header_t)
102 #define DTLS_HS_LENGTH sizeof(dtls_handshake_header_t)
103 #define DTLS_CH_LENGTH sizeof(dtls_client_hello_t) /* no variable length fields! */
104 #define DTLS_COOKIE_LENGTH_MAX 32
105 #define DTLS_CH_LENGTH_MAX sizeof(dtls_client_hello_t) + DTLS_COOKIE_LENGTH_MAX + 12 + 26
106 #define DTLS_HV_LENGTH sizeof(dtls_hello_verify_t)
107 #define DTLS_SH_LENGTH (2 + DTLS_RANDOM_LENGTH + 1 + 2 + 1)
108 #define DTLS_CE_LENGTH (3 + 3 + 27 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
109 #define DTLS_SKEXEC_LENGTH (1 + 2 + 1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE + 1 + 1 + 2 + 70)
110 #define DTLS_SKEXECPSK_LENGTH_MIN 2
111 #define DTLS_SKEXECPSK_LENGTH_MAX 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
112 #define DTLS_CKXPSK_LENGTH_MIN 2
113 #define DTLS_CKXEC_LENGTH (1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
114 #define DTLS_CV_LENGTH (1 + 1 + 2 + 1 + 1 + 1 + 1 + DTLS_EC_KEY_SIZE + 1 + 1 + DTLS_EC_KEY_SIZE)
115 #define DTLS_FIN_LENGTH 12
116 
117 #define HS_HDR_LENGTH DTLS_RH_LENGTH + DTLS_HS_LENGTH
118 #define HV_HDR_LENGTH HS_HDR_LENGTH + DTLS_HV_LENGTH
119 
120 #define HIGH(V) (((V) >> 8) & 0xff)
121 #define LOW(V) ((V) & 0xff)
122 
123 #define DTLS_RECORD_HEADER(M) ((dtls_record_header_t *)(M))
124 #define DTLS_HANDSHAKE_HEADER(M) ((dtls_handshake_header_t *)(M))
125 
126 #define HANDSHAKE(M) ((dtls_handshake_header_t *)((M) + DTLS_RH_LENGTH))
127 #define CLIENTHELLO(M) ((dtls_client_hello_t *)((M) + HS_HDR_LENGTH))
128 
129 /* The length check here should work because dtls_*_to_int() works on
130  * unsigned char. Otherwise, broken messages could cause severe
131  * trouble. Note that this macro jumps out of the current program flow
132  * when the message is too short. Beware!
133  */
134 #define SKIP_VAR_FIELD(P,L,T) { \
135  if (L < dtls_ ## T ## _to_int(P) + sizeof(T)) \
136  goto error; \
137  L -= dtls_ ## T ## _to_int(P) + sizeof(T); \
138  P += dtls_ ## T ## _to_int(P) + sizeof(T); \
139  }
140 
141 /* some constants for the PRF */
142 #define PRF_LABEL(Label) prf_label_##Label
143 #define PRF_LABEL_SIZE(Label) (sizeof(PRF_LABEL(Label)) - 1)
144 
145 static const unsigned char prf_label_master[] = "master secret";
146 static const unsigned char prf_label_key[] = "key expansion";
147 static const unsigned char prf_label_client[] = "client";
148 static const unsigned char prf_label_server[] = "server";
149 static const unsigned char prf_label_finished[] = " finished";
150 
151 #ifdef DTLS_ECC
152 /* first part of Raw public key, the is the start of the Subject Public Key */
153 static const unsigned char cert_asn1_header[] = {
154  0x30, 0x59, /* SEQUENCE, length 89 bytes */
155  0x30, 0x13, /* SEQUENCE, length 19 bytes */
156  0x06, 0x07, /* OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1) */
157  0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01,
158  0x06, 0x08, /* OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7) */
159  0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07,
160  0x03, 0x42, 0x00, /* BIT STRING, length 66 bytes, 0 bits unused */
161  0x04 /* uncompressed, followed by the r und s values of the public key */
162 };
163 #endif /* DTLS_ECC */
164 
165 #ifdef WITH_CONTIKI
166 PROCESS(dtls_retransmit_process, "DTLS retransmit process");
167 
168 static dtls_context_t the_dtls_context;
169 
170 static inline dtls_context_t *
171 malloc_context(void) {
172  return &the_dtls_context;
173 }
174 
175 static inline void
176 free_context(dtls_context_t *context) {
177 }
178 
179 #else /* WITH_CONTIKI */
180 
181 static inline dtls_context_t *
183  return (dtls_context_t *)malloc(sizeof(dtls_context_t));
184 }
185 
186 static inline void
188  free(context);
189 }
190 #endif
191 
192 void
193 dtls_init(void) {
194  dtls_clock_init();
195  crypto_init();
197  netq_init();
198  peer_init();
199 }
200 
201 /* Calls cb_alert() with given arguments if defined, otherwise an
202  * error message is logged and the result is -1. This is just an
203  * internal helper.
204  */
205 #define CALL(Context, which, ...) \
206  ((Context)->h && (Context)->h->which \
207  ? (Context)->h->which((Context), ##__VA_ARGS__) \
208  : -1)
209 
210 static int
212  dtls_security_parameters_t *security , session_t *session,
213  unsigned char type, uint8 *buf_array[],
214  size_t buf_len_array[], size_t buf_array_len);
215 
230 static int
231 dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
232  uint8 *buf, size_t buflen) {
233  return dtls_send_multi(ctx, peer, dtls_security_params(peer), &peer->session,
234  type, &buf, &buflen, 1);
235 }
236 
240 static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
241 
242 dtls_peer_t *
243 dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
244  dtls_peer_t *p;
245  FIND_PEER(ctx->peers, session, p);
246  return p;
247 }
248 
254 static int
256  ADD_PEER(ctx->peers, session, peer);
257  return 0;
258 }
259 
260 int
262  session_t *dst, uint8 *buf, size_t len) {
263 
264  dtls_peer_t *peer = dtls_get_peer(ctx, dst);
265 
266  /* Check if peer connection already exists */
267  if (!peer) { /* no ==> create one */
268  int res;
269 
270  /* dtls_connect() returns a value greater than zero if a new
271  * connection attempt is made, 0 for session reuse. */
272  res = dtls_connect(ctx, dst);
273 
274  return (res >= 0) ? 0 : res;
275  } else { /* a session exists, check if it is in state connected */
276 
277  if (peer->state != DTLS_STATE_CONNECTED) {
278  return 0;
279  } else {
280  return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
281  }
282  }
283 }
284 
285 static int
286 dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie) {
287  /* To access the cookie, we have to determine the session id's
288  * length and skip the whole thing. */
289  if (msglen < DTLS_HS_LENGTH + DTLS_CH_LENGTH + sizeof(uint8))
291 
294 
295  msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
297 
298  SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
299 
300  if (msglen < (*msg & 0xff) + sizeof(uint8))
302 
303  *cookie = msg + sizeof(uint8);
304  return dtls_uint8_to_int(msg);
305 
306  error:
308 }
309 
310 static int
312  session_t *session,
313  uint8 *msg, size_t msglen,
314  uint8 *cookie, int *clen) {
315  unsigned char buf[DTLS_HMAC_MAX];
316  size_t e;
317  int len;
318 
319  /* create cookie with HMAC-SHA256 over:
320  * - SECRET
321  * - session parameters (only IP address?)
322  * - client version
323  * - random gmt and bytes
324  * - session id
325  * - cipher_suites
326  * - compression method
327  */
328 
329  /* We use our own buffer as hmac_context instead of a dynamic buffer
330  * created by dtls_hmac_new() to separate storage space for cookie
331  * creation from storage that is used in real sessions. Note that
332  * the buffer size must fit with the default hash algorithm (see
333  * implementation of dtls_hmac_context_new()). */
334 
335  dtls_hmac_context_t hmac_context;
337 
338  dtls_hmac_update(&hmac_context,
339  (unsigned char *)&session->addr, session->size);
340 
341  /* feed in the beginning of the Client Hello up to and including the
342  session id */
343  e = sizeof(dtls_client_hello_t);
344  e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
345  if (e + DTLS_HS_LENGTH > msglen)
347 
348  dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
349 
350  /* skip cookie bytes and length byte */
351  e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
352  e += sizeof(uint8);
353  if (e + DTLS_HS_LENGTH > msglen)
355 
356  dtls_hmac_update(&hmac_context,
357  msg + DTLS_HS_LENGTH + e,
359 
360  len = dtls_hmac_finalize(&hmac_context, buf);
361 
362  if (len < *clen) {
363  memset(cookie + len, 0, *clen - len);
364  *clen = len;
365  }
366 
367  memcpy(cookie, buf, *clen);
368  return 0;
369 }
370 
371 #ifdef DTLS_CHECK_CONTENTTYPE
372 /* used to check if a received datagram contains a DTLS message */
373 static char const content_types[] = {
378  0 /* end marker */
379 };
380 #endif
381 
386 static unsigned int
387 is_record(uint8 *msg, size_t msglen) {
388  unsigned int rlen = 0;
389 
390  if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
391 #ifdef DTLS_CHECK_CONTENTTYPE
392  && strchr(content_types, msg[0])
393 #endif
394  && msg[1] == HIGH(DTLS_VERSION)
395  && msg[2] == LOW(DTLS_VERSION))
396  {
397  rlen = DTLS_RH_LENGTH +
399 
400  /* we do not accept wrong length field in record header */
401  if (rlen > msglen)
402  rlen = 0;
403  }
404 
405  return rlen;
406 }
407 
415 static inline uint8 *
417  uint8 *buf) {
418 
419  dtls_int_to_uint8(buf, type);
420  buf += sizeof(uint8);
421 
423  buf += sizeof(uint16);
424 
425  if (security) {
426  dtls_int_to_uint16(buf, security->epoch);
427  buf += sizeof(uint16);
428 
429  dtls_int_to_uint48(buf, security->rseq);
430  buf += sizeof(uint48);
431 
432  /* increment record sequence counter by 1 */
433  security->rseq++;
434  } else {
435  memset(buf, 0, sizeof(uint16) + sizeof(uint48));
436  buf += sizeof(uint16) + sizeof(uint48);
437  }
438 
439  memset(buf, 0, sizeof(uint16));
440  return buf + sizeof(uint16);
441 }
442 
449 static inline uint8 *
451  int length,
452  int frag_offset, int frag_length,
453  uint8 *buf) {
454 
455  dtls_int_to_uint8(buf, type);
456  buf += sizeof(uint8);
457 
458  dtls_int_to_uint24(buf, length);
459  buf += sizeof(uint24);
460 
461  if (peer && peer->handshake_params) {
462  /* and copy the result to buf */
464 
465  /* increment handshake message sequence counter by 1 */
467  } else {
468  memset(buf, 0, sizeof(uint16));
469  }
470  buf += sizeof(uint16);
471 
472  dtls_int_to_uint24(buf, frag_offset);
473  buf += sizeof(uint24);
474 
475  dtls_int_to_uint24(buf, frag_length);
476  buf += sizeof(uint24);
477 
478  return buf;
479 }
480 
484 };
485 
488 {
489 #ifdef DTLS_ECC
490  return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
491 #else
492  (void)cipher;
493  return 0;
494 #endif /* DTLS_ECC */
495 }
496 
499 {
500 #ifdef DTLS_PSK
501  return cipher == TLS_PSK_WITH_AES_128_CCM_8;
502 #else
503  return 0;
504 #endif /* DTLS_PSK */
505 }
506 
508 static inline int is_psk_supported(dtls_context_t *ctx)
509 {
510 #ifdef DTLS_PSK
511  return ctx && ctx->h && ctx->h->get_psk_info;
512 #else
513  return 0;
514 #endif /* DTLS_PSK */
515 }
516 
518 static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
519 {
520 #ifdef DTLS_ECC
521  return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
522  (is_client && ctx->h->verify_ecdsa_key));
523 #else
524  (void)ctx;
525  (void)is_client;
526  return 0;
527 #endif /* DTLS_ECC */
528 }
529 
533 {
534 #ifdef DTLS_ECC
535  return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
536 #else
537  (void)ctx;
538  return 0;
539 #endif /* DTLS_ECC */
540 }
541 
551 static int
552 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
553  int psk;
554  int ecdsa;
555 
556  psk = is_psk_supported(ctx);
557  ecdsa = is_ecdsa_supported(ctx, is_client);
558  return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
559  (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
560 }
561 
574 static int
576  dtls_peer_t *peer)
577 {
578  (void)msglen;
579  if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
580  if (msg[0] == DTLS_CT_HANDSHAKE) {
581  uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
582  if (msg_epoch == 0) {
584  if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
585  hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
586  return 1;
587  }
588  }
589  }
590  }
591  return 0;
592 }
595 {
596  dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
597  dtls_debug_dump(" client_MAC_secret",
598  dtls_kb_client_mac_secret(config, peer->role),
599  dtls_kb_mac_secret_size(config, peer->role));
600 
601  dtls_debug_dump(" server_MAC_secret",
602  dtls_kb_server_mac_secret(config, peer->role),
603  dtls_kb_mac_secret_size(config, peer->role));
604 
605  dtls_debug_dump(" client_write_key",
606  dtls_kb_client_write_key(config, peer->role),
607  dtls_kb_key_size(config, peer->role));
608 
609  dtls_debug_dump(" server_write_key",
610  dtls_kb_server_write_key(config, peer->role),
611  dtls_kb_key_size(config, peer->role));
612 
613  dtls_debug_dump(" client_IV",
614  dtls_kb_client_iv(config, peer->role),
615  dtls_kb_iv_size(config, peer->role));
616 
617  dtls_debug_dump(" server_IV",
618  dtls_kb_server_iv(config, peer->role),
619  dtls_kb_iv_size(config, peer->role));
620 }
621 
626 static char *dtls_handshake_type_to_name(int type)
627 {
628  switch (type) {
630  return "hello_request";
632  return "client_hello";
634  return "server_hello";
636  return "hello_verify_request";
637  case DTLS_HT_CERTIFICATE:
638  return "certificate";
640  return "server_key_exchange";
642  return "certificate_request";
644  return "server_hello_done";
646  return "certificate_verify";
648  return "client_key_exchange";
649  case DTLS_HT_FINISHED:
650  return "finished";
651  default:
652  return "unknown";
653  }
654 }
655 
659 static int
661  dtls_handshake_parameters_t *handshake,
662  dtls_peer_t *peer,
663  session_t *session,
664  dtls_peer_type role) {
665  unsigned char *pre_master_secret;
666  int pre_master_len = 0;
668  uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
669  (void)role; /* The macro dtls_kb_size() does not use role. */
670 
671  if (!security) {
673  }
674 
675  pre_master_secret = security->key_block;
676 
677  switch (handshake->cipher) {
678 #ifdef DTLS_PSK
680  unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
681  int len;
682 
683  len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
684  handshake->keyx.psk.identity,
685  handshake->keyx.psk.id_length,
686  psk, DTLS_PSK_MAX_KEY_LEN);
687  if (len < 0) {
688  dtls_crit("no psk key for session available\n");
689  return len;
690  }
691  /* Temporarily use the key_block storage space for the pre master secret. */
692  pre_master_len = dtls_psk_pre_master_secret(psk, len,
693  pre_master_secret,
695 
696  dtls_debug_hexdump("psk", psk, len);
697 
698  memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
699  if (pre_master_len < 0) {
700  dtls_crit("the psk was too long, for the pre master secret\n");
702  }
703 
704  break;
705  }
706 #endif /* DTLS_PSK */
707 #ifdef DTLS_ECC
709  pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecdsa.own_eph_priv,
710  handshake->keyx.ecdsa.other_eph_pub_x,
711  handshake->keyx.ecdsa.other_eph_pub_y,
712  sizeof(handshake->keyx.ecdsa.own_eph_priv),
713  pre_master_secret,
715  if (pre_master_len < 0) {
716  dtls_crit("the curve was too long, for the pre master secret\n");
718  }
719  break;
720  }
721 #endif /* DTLS_ECC */
723  assert(!"calculate_key_block: tried to use NULL cipher\n");
725 
726  /* The following cases cover the enum symbols that are not
727  * included in this build. These must be kept just above the
728  * default case as they do nothing but fall through.
729  */
730 #ifndef DTLS_PSK
732  /* fall through to default */
733 #endif /* !DTLS_PSK */
734 
735 #ifndef DTLS_ECC
737  /* fall through to default */
738 #endif /* !DTLS_ECC */
739 
740  default:
741  dtls_crit("calculate_key_block: unknown cipher %x04 \n", handshake->cipher);
743  }
744 
745  dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
746  dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
747  dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
748 
749  dtls_prf(pre_master_secret, pre_master_len,
750  PRF_LABEL(master), PRF_LABEL_SIZE(master),
751  handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
752  handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
753  master_secret,
755 
756  dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
757 
758  /* create key_block from master_secret
759  * key_block = PRF(master_secret,
760  "key expansion" + tmp.random.server + tmp.random.client) */
761 
762  dtls_prf(master_secret,
764  PRF_LABEL(key), PRF_LABEL_SIZE(key),
765  handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
766  handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
767  security->key_block,
768  dtls_kb_size(security, role));
769 
770  memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
771  dtls_debug_keyblock(security);
772 
773  security->cipher = handshake->cipher;
774  security->compression = handshake->compression;
775  security->rseq = 0;
776 
777  return 0;
778 }
779 
780 /* TODO: add a generic method which iterates over a list and searches for a specific key */
781 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
782  int i, curve_name;
783 
784  /* length of curve list */
785  i = dtls_uint16_to_int(data);
786  data += sizeof(uint16);
787  if (i + sizeof(uint16) != data_length) {
788  dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
790  }
791 
792  for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
793  /* check if this curve is supported */
794  curve_name = dtls_uint16_to_int(data);
795  data += sizeof(uint16);
796 
797  if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
798  return 0;
799  }
800 
801  dtls_warn("no supported elliptic curve found\n");
803 }
804 
805 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
806  int i, cert_type;
807 
808  /* length of cert type list */
809  i = dtls_uint8_to_int(data);
810  data += sizeof(uint8);
811  if (i + sizeof(uint8) != data_length) {
812  dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
814  }
815 
816  for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
817  /* check if this cert type is supported */
818  cert_type = dtls_uint8_to_int(data);
819  data += sizeof(uint8);
820 
821  if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
822  return 0;
823  }
824 
825  dtls_warn("no supported certificate type found\n");
827 }
828 
829 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
830  int i, cert_type;
831 
832  /* length of ec_point_formats list */
833  i = dtls_uint8_to_int(data);
834  data += sizeof(uint8);
835  if (i + sizeof(uint8) != data_length) {
836  dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
838  }
839 
840  for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
841  /* check if this ec_point_format is supported */
842  cert_type = dtls_uint8_to_int(data);
843  data += sizeof(uint8);
844 
845  if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
846  return 0;
847  }
848 
849  dtls_warn("no supported ec_point_format found\n");
851 }
852 
853 /*
854  * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
855  */
856 static int
858  uint8 *data, size_t data_length, int client_hello)
859 {
860  uint16_t i, j;
861  int ext_elliptic_curve = 0;
862  int ext_client_cert_type = 0;
863  int ext_server_cert_type = 0;
864  int ext_ec_point_formats = 0;
866 
867  if (data_length < sizeof(uint16)) {
868  /* no tls extensions specified */
870  goto error;
871  }
872  return 0;
873  }
874 
875  /* get the length of the tls extension list */
876  j = dtls_uint16_to_int(data);
877  data += sizeof(uint16);
878  data_length -= sizeof(uint16);
879 
880  if (data_length < j)
881  goto error;
882 
883  /* check for TLS extensions needed for this cipher */
884  while (data_length) {
885  if (data_length < sizeof(uint16) * 2)
886  goto error;
887 
888  /* get the tls extension type */
889  i = dtls_uint16_to_int(data);
890  data += sizeof(uint16);
891  data_length -= sizeof(uint16);
892 
893  /* get the length of the tls extension */
894  j = dtls_uint16_to_int(data);
895  data += sizeof(uint16);
896  data_length -= sizeof(uint16);
897 
898  if (data_length < j)
899  goto error;
900 
901  switch (i) {
903  ext_elliptic_curve = 1;
904  if (verify_ext_eliptic_curves(data, j))
905  goto error;
906  break;
908  ext_client_cert_type = 1;
909  if (client_hello) {
910  if (verify_ext_cert_type(data, j))
911  goto error;
912  } else {
914  goto error;
915  }
916  break;
918  ext_server_cert_type = 1;
919  if (client_hello) {
920  if (verify_ext_cert_type(data, j))
921  goto error;
922  } else {
924  goto error;
925  }
926  break;
928  ext_ec_point_formats = 1;
929  if (verify_ext_ec_point_formats(data, j))
930  goto error;
931  break;
933  /* As only AEAD cipher suites are currently available, this
934  * extension can be skipped.
935  */
936  dtls_info("skipped encrypt-then-mac extension\n");
937  break;
938  default:
939  dtls_warn("unsupported tls extension: %i\n", i);
940  break;
941  }
942  data += j;
943  data_length -= j;
944  }
945  if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
946  if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
947  || !ext_ec_point_formats) {
948  dtls_warn("not all required tls extensions found in client hello\n");
949  goto error;
950  }
951  } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
952  if (!ext_client_cert_type || !ext_server_cert_type) {
953  dtls_warn("not all required tls extensions found in server hello\n");
954  goto error;
955  }
956  }
957  return 0;
958 
959 error:
960  if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
962  } else {
964  }
965 }
966 
979 static int
981  dtls_peer_t *peer,
982  uint8 *data, size_t data_length) {
983  int i;
984  unsigned int j;
985  int ok;
988 
989  assert(config);
990  assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
991 
992  /* skip the handshake header and client version information */
993  data += DTLS_HS_LENGTH + sizeof(uint16);
994  data_length -= DTLS_HS_LENGTH + sizeof(uint16);
995 
996  /* store client random in config */
997  memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
998  data += DTLS_RANDOM_LENGTH;
999  data_length -= DTLS_RANDOM_LENGTH;
1000 
1001  /* Caution: SKIP_VAR_FIELD may jump to error: */
1002  SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
1003  SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
1004 
1005  i = dtls_uint16_to_int(data);
1006  if (data_length < i + sizeof(uint16)) {
1007  /* Looks like we do not have a cipher nor compression. This is ok
1008  * for renegotiation, but not for the initial handshake. */
1009 
1010  if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
1011  goto error;
1012 
1013  config->cipher = security->cipher;
1014  config->compression = security->compression;
1015 
1016  return 0;
1017  }
1018 
1019  data += sizeof(uint16);
1020  data_length -= sizeof(uint16) + i;
1021 
1022  ok = 0;
1023  while (i && !ok) {
1024  config->cipher = dtls_uint16_to_int(data);
1025  ok = known_cipher(ctx, config->cipher, 0);
1026  i -= sizeof(uint16);
1027  data += sizeof(uint16);
1028  }
1029 
1030  /* skip remaining ciphers */
1031  data += i;
1032 
1033  if (!ok) {
1034  /* reset config cipher to a well-defined value */
1035  config->cipher = TLS_NULL_WITH_NULL_NULL;
1036  dtls_warn("No matching cipher found\n");
1037  goto error;
1038  }
1039 
1040  if (data_length < sizeof(uint8)) {
1041  /* no compression specified, take the current compression method */
1042  if (security)
1043  config->compression = security->compression;
1044  else
1046  return 0;
1047  }
1048 
1049  i = dtls_uint8_to_int(data);
1050  if (data_length < i + sizeof(uint8))
1051  goto error;
1052 
1053  data += sizeof(uint8);
1054  data_length -= sizeof(uint8) + i;
1055 
1056  ok = 0;
1057  while (i && !ok) {
1058  for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
1059  if (dtls_uint8_to_int(data) == compression_methods[j]) {
1060  config->compression = compression_methods[j];
1061  ok = 1;
1062  }
1063  i -= sizeof(uint8);
1064  data += sizeof(uint8);
1065  }
1066 
1067  if (!ok) {
1068  /* reset config cipher to a well-defined value */
1069  goto error;
1070  }
1071 
1072  return dtls_check_tls_extension(peer, data, data_length, 1);
1073 error:
1074  if (peer->state == DTLS_STATE_CONNECTED) {
1076  } else {
1078  }
1079 }
1080 
1085 static inline int
1087  dtls_handshake_parameters_t *handshake,
1088  uint8 *data, size_t length) {
1089  (void)ctx;
1090 #ifdef DTLS_ECC
1092 
1093  if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1094  dtls_debug("The client key exchange is too short\n");
1096  }
1097  data += DTLS_HS_LENGTH;
1098 
1099  if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1100  dtls_alert("expected 65 bytes long public point\n");
1102  }
1103  data += sizeof(uint8);
1104 
1105  if (dtls_uint8_to_int(data) != 4) {
1106  dtls_alert("expected uncompressed public point\n");
1108  }
1109  data += sizeof(uint8);
1110 
1111  memcpy(handshake->keyx.ecdsa.other_eph_pub_x, data,
1112  sizeof(handshake->keyx.ecdsa.other_eph_pub_x));
1113  data += sizeof(handshake->keyx.ecdsa.other_eph_pub_x);
1114 
1115  memcpy(handshake->keyx.ecdsa.other_eph_pub_y, data,
1116  sizeof(handshake->keyx.ecdsa.other_eph_pub_y));
1117  data += sizeof(handshake->keyx.ecdsa.other_eph_pub_y);
1118  }
1119 #endif /* DTLS_ECC */
1120 #ifdef DTLS_PSK
1121  if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1122  int id_length;
1123 
1124  if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1125  dtls_debug("The client key exchange is too short\n");
1127  }
1128  data += DTLS_HS_LENGTH;
1129 
1130  id_length = dtls_uint16_to_int(data);
1131  data += sizeof(uint16);
1132 
1133  if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1134  dtls_debug("The identity has a wrong length\n");
1136  }
1137 
1138  if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1139  dtls_warn("please use a smaller client identity\n");
1141  }
1142 
1143  handshake->keyx.psk.id_length = id_length;
1144  memcpy(handshake->keyx.psk.identity, data, id_length);
1145  }
1146 #endif /* DTLS_PSK */
1147  return 0;
1148 }
1149 
1150 static inline void
1151 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1152  dtls_debug_dump("add MAC data", data, length);
1153  dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1154 }
1155 
1156 static void
1158  memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1159  sizeof(peer->handshake_params->hs_state.hs_hash));
1160 }
1161 
1162 static inline size_t
1164  return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1165 }
1166 
1167 static inline void
1169  assert(peer);
1170  dtls_debug("clear MAC\n");
1172 }
1173 
1184 static int
1186  uint8 *data, size_t data_length) {
1187  size_t digest_length, label_size;
1188  const unsigned char *label;
1189  unsigned char buf[DTLS_HMAC_MAX];
1190  (void)ctx;
1191 
1192  if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1194 
1195  /* Use a union here to ensure that sufficient stack space is
1196  * reserved. As statebuf and verify_data are not used at the same
1197  * time, we can re-use the storage safely.
1198  */
1199  union {
1200  unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1201  unsigned char verify_data[DTLS_FIN_LENGTH];
1202  } b;
1203 
1204  /* temporarily store hash status for roll-back after finalize */
1205  memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1206 
1207  digest_length = finalize_hs_hash(peer, buf);
1208  /* clear_hash(); */
1209 
1210  /* restore hash status */
1211  memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1212 
1213  if (peer->role == DTLS_CLIENT) {
1214  label = PRF_LABEL(server);
1215  label_size = PRF_LABEL_SIZE(server);
1216  } else { /* server */
1217  label = PRF_LABEL(client);
1218  label_size = PRF_LABEL_SIZE(client);
1219  }
1220 
1223  label, label_size,
1224  PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1225  buf, digest_length,
1226  b.verify_data, sizeof(b.verify_data));
1227 
1228  dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1229  dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1230 
1231  /* compare verify data and create DTLS alert code when they differ */
1232  return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1233  ? 0
1235 }
1236 
1261 static int
1263  unsigned char type,
1264  uint8 *data_array[], size_t data_len_array[],
1265  size_t data_array_len,
1266  uint8 *sendbuf, size_t *rlen) {
1267  uint8 *p, *start;
1268  int res;
1269  unsigned int i;
1270 
1271  if (*rlen < DTLS_RH_LENGTH) {
1272  dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1274  }
1275 
1276  p = dtls_set_record_header(type, security, sendbuf);
1277  start = p;
1278 
1279  if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1280  /* no cipher suite */
1281 
1282  res = 0;
1283  for (i = 0; i < data_array_len; i++) {
1284  /* check the minimum that we need for packets that are not encrypted */
1285  if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1286  dtls_debug("dtls_prepare_record: send buffer too small\n");
1288  }
1289 
1290  memcpy(p, data_array[i], data_len_array[i]);
1291  p += data_len_array[i];
1292  res += data_len_array[i];
1293  }
1294  } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1299 #define A_DATA_LEN 13
1300  unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1301  unsigned char A_DATA[A_DATA_LEN];
1302 
1303  if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1304  dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1305  } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1306  dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1307  } else {
1308  dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1309  }
1310 
1311  /* set nonce
1312  from RFC 6655:
1313  The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1314  the "nonce" SHALL be 12 bytes long and is constructed as follows:
1315  (this is an example of a "partially explicit" nonce; see Section
1316  3.2.1 in [RFC5116]).
1317 
1318  struct {
1319  opaque salt[4];
1320  opaque nonce_explicit[8];
1321  } CCMNonce;
1322 
1323  [...]
1324 
1325  In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1326  48-bit seq_num.
1327 
1328  When the nonce_explicit is equal to the sequence number, the CCMNonce
1329  will have the structure of the CCMNonceExample given below.
1330 
1331  struct {
1332  uint32 client_write_IV; // low order 32-bits
1333  uint64 seq_num; // TLS sequence number
1334  } CCMClientNonce.
1335 
1336 
1337  struct {
1338  uint32 server_write_IV; // low order 32-bits
1339  uint64 seq_num; // TLS sequence number
1340  } CCMServerNonce.
1341 
1342 
1343  struct {
1344  case client:
1345  CCMClientNonce;
1346  case server:
1347  CCMServerNonce:
1348  } CCMNonceExample;
1349  */
1350 
1351  memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1352  p += 8;
1353  res = 8;
1354 
1355  for (i = 0; i < data_array_len; i++) {
1356  /* check the minimum that we need for packets that are not encrypted */
1357  if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1358  dtls_debug("dtls_prepare_record: send buffer too small\n");
1360  }
1361 
1362  memcpy(p, data_array[i], data_len_array[i]);
1363  p += data_len_array[i];
1364  res += data_len_array[i];
1365  }
1366 
1367  memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1368  memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1369  dtls_kb_iv_size(security, peer->role));
1370  memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
1371 
1372  dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1373  dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1374  dtls_kb_key_size(security, peer->role));
1375 
1376  /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1377  *
1378  * additional_data = seq_num + TLSCompressed.type +
1379  * TLSCompressed.version + TLSCompressed.length;
1380  */
1381  memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1382  memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1383  dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1384 
1385  res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1386  dtls_kb_local_write_key(security, peer->role),
1387  dtls_kb_key_size(security, peer->role),
1388  A_DATA, A_DATA_LEN);
1389 
1390  if (res < 0)
1391  return res;
1392 
1393  res += 8; /* increment res by size of nonce_explicit */
1394  dtls_debug_dump("message:", start, res);
1395  }
1396 
1397  /* fix length of fragment in sendbuf */
1398  dtls_int_to_uint16(sendbuf + 11, res);
1399 
1400  *rlen = DTLS_RH_LENGTH + res;
1401  return 0;
1402 }
1403 
1404 static int
1406  dtls_peer_t *peer,
1407  session_t *session,
1408  uint8 header_type,
1409  uint8 *data, size_t data_length,
1410  int add_hash)
1411 {
1412  uint8 buf[DTLS_HS_LENGTH];
1413  uint8 *data_array[2];
1414  size_t data_len_array[2];
1415  int i = 0;
1416  dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1417 
1418  dtls_set_handshake_header(header_type, peer, data_length, 0,
1419  data_length, buf);
1420 
1421  if (add_hash) {
1422  update_hs_hash(peer, buf, sizeof(buf));
1423  }
1424  data_array[i] = buf;
1425  data_len_array[i] = sizeof(buf);
1426  i++;
1427 
1428  if (data != NULL) {
1429  if (add_hash) {
1430  update_hs_hash(peer, data, data_length);
1431  }
1432  data_array[i] = data;
1433  data_len_array[i] = data_length;
1434  i++;
1435  }
1436  dtls_debug("send handshake packet of type: %s (%i)\n",
1437  dtls_handshake_type_to_name(header_type), header_type);
1438  return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1439  data_array, data_len_array, i);
1440 }
1441 
1442 static int
1444  dtls_peer_t *peer,
1445  uint8 header_type,
1446  uint8 *data, size_t data_length)
1447 {
1448  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1449  header_type, data, data_length, 1);
1450 }
1451 
1466 #define MUST_HASH(Type, Data, Length) \
1467  ((Type) == DTLS_CT_HANDSHAKE && \
1468  ((Data) != NULL) && ((Length) > 0) && \
1469  ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) && \
1470  ((Data)[0] != DTLS_HT_CLIENT_HELLO || \
1471  ((Length) >= HS_HDR_LENGTH && \
1472  (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) || \
1473  (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1474 
1488 static int
1490  dtls_security_parameters_t *security , session_t *session,
1491  unsigned char type, uint8 *buf_array[],
1492  size_t buf_len_array[], size_t buf_array_len)
1493 {
1494  /* We cannot use ctx->sendbuf here as it is reserved for collecting
1495  * the input for this function, i.e. buf == ctx->sendbuf.
1496  *
1497  * TODO: check if we can use the receive buf here. This would mean
1498  * that we might not be able to handle multiple records stuffed in
1499  * one UDP datagram */
1500  unsigned char sendbuf[DTLS_MAX_BUF];
1501  size_t len = sizeof(sendbuf);
1502  int res;
1503  unsigned int i;
1504  size_t overall_len = 0;
1505 
1506  res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1507 
1508  if (res < 0)
1509  return res;
1510 
1511  /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1512  /* update_hs_hash(peer, buf, buflen); */
1513 
1514  dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1515  for (i = 0; i < buf_array_len; i++) {
1516  dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1517  overall_len += buf_len_array[i];
1518  }
1519 
1520  if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1521  type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1522  /* copy handshake messages other than HelloVerify into retransmit buffer */
1523  netq_t *n = netq_node_new(overall_len);
1524  if (n) {
1525  dtls_tick_t now;
1526  dtls_ticks(&now);
1527  n->t = now + 2 * CLOCK_SECOND;
1528  n->retransmit_cnt = 0;
1529  n->timeout = 2 * CLOCK_SECOND;
1530  n->peer = peer;
1531  n->epoch = (security) ? security->epoch : 0;
1532  n->type = type;
1533  n->length = 0;
1534  for (i = 0; i < buf_array_len; i++) {
1535  memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1536  n->length += buf_len_array[i];
1537  }
1538 
1539  if (!netq_insert_node(&ctx->sendqueue, n)) {
1540  dtls_warn("cannot add packet to retransmit buffer\n");
1541  netq_node_free(n);
1542 #ifdef WITH_CONTIKI
1543  } else {
1544  /* must set timer within the context of the retransmit process */
1545  PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1546  etimer_set(&ctx->retransmit_timer, n->timeout);
1547  PROCESS_CONTEXT_END(&dtls_retransmit_process);
1548 #else /* WITH_CONTIKI */
1549  dtls_debug("copied to sendqueue\n");
1550 #endif /* WITH_CONTIKI */
1551  }
1552  } else
1553  dtls_warn("retransmit buffer full\n");
1554  }
1555 
1556  /* FIXME: copy to peer's sendqueue (after fragmentation if
1557  * necessary) and initialize retransmit timer */
1558  res = CALL(ctx, write, session, sendbuf, len);
1559 
1560  /* Guess number of bytes application data actually sent:
1561  * dtls_prepare_record() tells us in len the number of bytes to
1562  * send, res will contain the bytes actually sent. */
1563  return res <= 0 ? res : (int)(overall_len - (len - (unsigned int)res));
1564 }
1565 
1566 static inline int
1568  dtls_alert_t description) {
1569  uint8_t msg[] = { level, description };
1570 
1571  dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1572  return 0;
1573 }
1574 
1575 int
1576 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1577  int res = -1;
1578  dtls_peer_t *peer;
1579 
1580  peer = dtls_get_peer(ctx, remote);
1581 
1582  if (peer) {
1584  /* indicate tear down */
1585  peer->state = DTLS_STATE_CLOSING;
1586  }
1587  return res;
1588 }
1589 
1590 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1591 {
1592  if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1593  dtls_close(ctx, &peer->session);
1594  if (unlink) {
1595  DEL_PEER(ctx->peers, peer);
1596  dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1597  }
1598  dtls_free_peer(peer);
1599 }
1600 
1617 static int
1619  dtls_peer_t *peer,
1620  session_t *session,
1621  const dtls_state_t state,
1622  uint8 *data, size_t data_length)
1623 {
1625  uint8 *p = buf;
1626  int len = DTLS_COOKIE_LENGTH;
1627  uint8 *cookie = NULL;
1628  int err;
1629 #undef mycookie
1630 #define mycookie (buf + DTLS_HV_LENGTH)
1631 
1632  /* Store cookie where we can reuse it for the HelloVerify request. */
1633  err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1634  if (err < 0)
1635  return err;
1636 
1637  dtls_debug_dump("create cookie", mycookie, len);
1638 
1639  assert(len == DTLS_COOKIE_LENGTH);
1640 
1641  /* Perform cookie check. */
1642  len = dtls_get_cookie(data, data_length, &cookie);
1643  if (len < 0) {
1644  dtls_warn("error while fetching the cookie, err: %i\n", err);
1645  return err;
1646  }
1647 
1648  dtls_debug_dump("compare with cookie", cookie, len);
1649 
1650  /* check if cookies match */
1651  if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1652  dtls_debug("found matching cookie\n");
1653  return 0;
1654  }
1655 
1656  if (len > 0) {
1657  dtls_debug_dump("invalid cookie", cookie, len);
1658  } else {
1659  dtls_debug("cookie len is 0!\n");
1660  }
1661 
1662  /* ClientHello did not contain any valid cookie, hence we send a
1663  * HelloVerify request. */
1664 
1666  p += sizeof(uint16);
1667 
1669  p += sizeof(uint8);
1670 
1671  assert(p == mycookie);
1672 
1673  p += DTLS_COOKIE_LENGTH;
1674 
1675  /* TODO use the same record sequence number as in the ClientHello,
1676  see 4.2.1. Denial-of-Service Countermeasures */
1677  err = dtls_send_handshake_msg_hash(ctx,
1678  state == DTLS_STATE_CONNECTED ? peer : NULL,
1679  session,
1681  buf, p - buf, 0);
1682  if (err < 0) {
1683  dtls_warn("cannot send HelloVerify request\n");
1684  }
1685  return err; /* HelloVerify is sent, now we cannot do anything but wait */
1686 
1687 #undef mycookie
1688 }
1689 
1690 #ifdef DTLS_ECC
1691 static int
1692 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1693  unsigned char **result_r,
1694  unsigned char **result_s)
1695 {
1696  int i;
1697  uint8 *data_orig = data;
1698 
1700  dtls_alert("only sha256 is supported in certificate verify\n");
1702  }
1703  data += sizeof(uint8);
1704  data_length -= sizeof(uint8);
1705 
1707  dtls_alert("only ecdsa signature is supported in client verify\n");
1709  }
1710  data += sizeof(uint8);
1711  data_length -= sizeof(uint8);
1712 
1713  if (data_length < dtls_uint16_to_int(data)) {
1714  dtls_alert("signature length wrong\n");
1716  }
1717  data += sizeof(uint16);
1718  data_length -= sizeof(uint16);
1719 
1720  if (dtls_uint8_to_int(data) != 0x30) {
1721  dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1723  }
1724  data += sizeof(uint8);
1725  data_length -= sizeof(uint8);
1726 
1727  if (data_length < dtls_uint8_to_int(data)) {
1728  dtls_alert("signature length wrong\n");
1730  }
1731  data += sizeof(uint8);
1732  data_length -= sizeof(uint8);
1733 
1734  if (dtls_uint8_to_int(data) != 0x02) {
1735  dtls_alert("wrong ASN.1 struct, expected Integer\n");
1737  }
1738  data += sizeof(uint8);
1739  data_length -= sizeof(uint8);
1740 
1741  i = dtls_uint8_to_int(data);
1742  data += sizeof(uint8);
1743  data_length -= sizeof(uint8);
1744 
1745  /* Sometimes these values have a leeding 0 byte */
1746  *result_r = data + i - DTLS_EC_KEY_SIZE;
1747 
1748  data += i;
1749  data_length -= i;
1750 
1751  if (dtls_uint8_to_int(data) != 0x02) {
1752  dtls_alert("wrong ASN.1 struct, expected Integer\n");
1754  }
1755  data += sizeof(uint8);
1756  data_length -= sizeof(uint8);
1757 
1758  i = dtls_uint8_to_int(data);
1759  data += sizeof(uint8);
1760  data_length -= sizeof(uint8);
1761 
1762  /* Sometimes these values have a leeding 0 byte */
1763  *result_s = data + i - DTLS_EC_KEY_SIZE;
1764 
1765  data += i;
1766  data_length -= i;
1767 
1768  return data - data_orig;
1769 }
1770 
1771 static int
1773  dtls_peer_t *peer,
1774  uint8 *data, size_t data_length)
1775 {
1777  int ret;
1778  unsigned char *result_r;
1779  unsigned char *result_s;
1780  dtls_hash_ctx hs_hash;
1781  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1782 
1784 
1785  data += DTLS_HS_LENGTH;
1786 
1787  if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1788  dtls_alert("the packet length does not match the expected\n");
1790  }
1791 
1792  ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
1793  if (ret < 0) {
1794  return ret;
1795  }
1796  data += ret;
1797  data_length -= ret;
1798 
1799  copy_hs_hash(peer, &hs_hash);
1800 
1801  dtls_hash_finalize(sha256hash, &hs_hash);
1802 
1804  sizeof(config->keyx.ecdsa.other_pub_x),
1805  sha256hash, sizeof(sha256hash),
1806  result_r, result_s);
1807 
1808  if (ret < 0) {
1809  dtls_alert("wrong signature err: %i\n", ret);
1811  }
1812  return 0;
1813 }
1814 #endif /* DTLS_ECC */
1815 
1816 static int
1818 {
1819  /* Ensure that the largest message to create fits in our source
1820  * buffer. (The size of the destination buffer is checked by the
1821  * encoding function, so we do not need to guess.) */
1822  uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
1823  uint8 *p;
1824  int ecdsa;
1825  uint8 extension_size;
1826  dtls_handshake_parameters_t *handshake = peer->handshake_params;
1827  dtls_tick_t now;
1828 
1829  ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
1830 
1831  extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
1832 
1833  /* Handshake header */
1834  p = buf;
1835 
1836  /* ServerHello */
1838  p += sizeof(uint16);
1839 
1840  /* Set server random: First 4 bytes are the server's Unix timestamp,
1841  * followed by 28 bytes of generate random data. */
1842  dtls_ticks(&now);
1843  dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
1844  dtls_prng(handshake->tmp.random.server + 4, 28);
1845 
1846  memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
1847  p += DTLS_RANDOM_LENGTH;
1848 
1849  *p++ = 0; /* no session id */
1850 
1851  if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
1852  /* selected cipher suite */
1853  dtls_int_to_uint16(p, handshake->cipher);
1854  p += sizeof(uint16);
1855 
1856  /* selected compression method */
1857  *p++ = compression_methods[handshake->compression];
1858  }
1859 
1860  if (extension_size) {
1861  /* length of the extensions */
1862  dtls_int_to_uint16(p, extension_size - 2);
1863  p += sizeof(uint16);
1864  }
1865 
1866  if (ecdsa) {
1867  /* client certificate type extension */
1869  p += sizeof(uint16);
1870 
1871  /* length of this extension type */
1872  dtls_int_to_uint16(p, 1);
1873  p += sizeof(uint16);
1874 
1876  p += sizeof(uint8);
1877 
1878  /* client certificate type extension */
1880  p += sizeof(uint16);
1881 
1882  /* length of this extension type */
1883  dtls_int_to_uint16(p, 1);
1884  p += sizeof(uint16);
1885 
1887  p += sizeof(uint8);
1888 
1889  /* ec_point_formats */
1891  p += sizeof(uint16);
1892 
1893  /* length of this extension type */
1894  dtls_int_to_uint16(p, 2);
1895  p += sizeof(uint16);
1896 
1897  /* number of supported formats */
1898  dtls_int_to_uint8(p, 1);
1899  p += sizeof(uint8);
1900 
1902  p += sizeof(uint8);
1903  }
1904 
1905  assert((buf <= p) && ((unsigned int)(p - buf) <= sizeof(buf)));
1906 
1907  /* TODO use the same record sequence number as in the ClientHello,
1908  see 4.2.1. Denial-of-Service Countermeasures */
1910  buf, p - buf);
1911 }
1912 
1913 #ifdef DTLS_ECC
1914 #define DTLS_EC_SUBJECTPUBLICKEY_SIZE (2 * DTLS_EC_KEY_SIZE + sizeof(cert_asn1_header))
1915 
1916 static int
1918  const dtls_ecdsa_key_t *key)
1919 {
1920  uint8 buf[DTLS_CE_LENGTH];
1921  uint8 *p;
1922 
1923  /* Certificate
1924  *
1925  * Start message construction at beginning of buffer. */
1926  p = buf;
1927 
1928  /* length of this certificate */
1930  p += sizeof(uint24);
1931 
1932  memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
1933  p += sizeof(cert_asn1_header);
1934 
1935  memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
1936  p += DTLS_EC_KEY_SIZE;
1937 
1938  memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
1939  p += DTLS_EC_KEY_SIZE;
1940 
1941  assert(p - buf <= sizeof(buf));
1942 
1943  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
1944  buf, p - buf);
1945 }
1946 
1947 static uint8 *
1949 {
1950  int len_r;
1951  int len_s;
1952 
1953 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
1954 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
1955  /* store the pointer to the r component of the signature and make space */
1957  len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
1958 
1959 #undef R_KEY_OFFSET
1960 #undef S_KEY_OFFSET
1961 
1962  /* sha256 */
1964  p += sizeof(uint8);
1965 
1966  /* ecdsa */
1968  p += sizeof(uint8);
1969 
1970  /* length of signature */
1971  dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
1972  p += sizeof(uint16);
1973 
1974  /* ASN.1 SEQUENCE */
1975  dtls_int_to_uint8(p, 0x30);
1976  p += sizeof(uint8);
1977 
1978  dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
1979  p += sizeof(uint8);
1980 
1981  /* ASN.1 Integer r */
1982  dtls_int_to_uint8(p, 0x02);
1983  p += sizeof(uint8);
1984 
1985  dtls_int_to_uint8(p, len_r);
1986  p += sizeof(uint8);
1987 
1988  /* the pint r was added here */
1989  p += len_r;
1990 
1991  /* ASN.1 Integer s */
1992  dtls_int_to_uint8(p, 0x02);
1993  p += sizeof(uint8);
1994 
1995  dtls_int_to_uint8(p, len_s);
1996  p += sizeof(uint8);
1997 
1998  /* the pint s was added here */
1999  p += len_s;
2000 
2001  return p;
2002 }
2003 
2004 static int
2006  const dtls_ecdsa_key_t *key)
2007 {
2008  /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2009  * 33 bytes long add space for that */
2010  uint8 buf[DTLS_SKEXEC_LENGTH + 2];
2011  uint8 *p;
2012  uint8 *key_params;
2013  uint8 *ephemeral_pub_x;
2014  uint8 *ephemeral_pub_y;
2015  uint32_t point_r[9];
2016  uint32_t point_s[9];
2018 
2019  /* ServerKeyExchange
2020  *
2021  * Start message construction at beginning of buffer. */
2022  p = buf;
2023 
2024  key_params = p;
2025  /* ECCurveType curve_type: named_curve */
2026  dtls_int_to_uint8(p, 3);
2027  p += sizeof(uint8);
2028 
2029  /* NamedCurve namedcurve: secp256r1 */
2031  p += sizeof(uint16);
2032 
2033  dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2034  p += sizeof(uint8);
2035 
2036  /* This should be an uncompressed point, but I do not have access to the spec. */
2037  dtls_int_to_uint8(p, 4);
2038  p += sizeof(uint8);
2039 
2040  /* store the pointer to the x component of the pub key and make space */
2041  ephemeral_pub_x = p;
2042  p += DTLS_EC_KEY_SIZE;
2043 
2044  /* store the pointer to the y component of the pub key and make space */
2045  ephemeral_pub_y = p;
2046  p += DTLS_EC_KEY_SIZE;
2047 
2049  ephemeral_pub_x, ephemeral_pub_y,
2051 
2052  /* sign the ephemeral and its paramaters */
2054  config->tmp.random.client, DTLS_RANDOM_LENGTH,
2055  config->tmp.random.server, DTLS_RANDOM_LENGTH,
2056  key_params, p - key_params,
2057  point_r, point_s);
2058 
2059  p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2060 
2061  assert(p - buf <= sizeof(buf));
2062 
2064  buf, p - buf);
2065 }
2066 #endif /* DTLS_ECC */
2067 
2068 #ifdef DTLS_PSK
2069 static int
2071  const unsigned char *psk_hint, size_t len)
2072 {
2074  uint8 *p;
2075 
2076  p = buf;
2077 
2080  /* should never happen */
2081  dtls_warn("psk identity hint is too long\n");
2083  }
2084 
2085  dtls_int_to_uint16(p, len);
2086  p += sizeof(uint16);
2087 
2088  memcpy(p, psk_hint, len);
2089  p += len;
2090 
2091  assert((buf <= p) && ((unsigned int)(p - buf) <= sizeof(buf)));
2092 
2094  buf, p - buf);
2095 }
2096 #endif /* DTLS_PSK */
2097 
2098 #ifdef DTLS_ECC
2099 static int
2101 {
2102  uint8 buf[8];
2103  uint8 *p;
2104 
2105  /* ServerHelloDone
2106  *
2107  * Start message construction at beginning of buffer. */
2108  p = buf;
2109 
2110  /* certificate_types */
2111  dtls_int_to_uint8(p, 1);
2112  p += sizeof(uint8);
2113 
2114  /* ecdsa_sign */
2116  p += sizeof(uint8);
2117 
2118  /* supported_signature_algorithms */
2119  dtls_int_to_uint16(p, 2);
2120  p += sizeof(uint16);
2121 
2122  /* sha256 */
2124  p += sizeof(uint8);
2125 
2126  /* ecdsa */
2128  p += sizeof(uint8);
2129 
2130  /* certificate_authoritiess */
2131  dtls_int_to_uint16(p, 0);
2132  p += sizeof(uint16);
2133 
2134  assert(p - buf <= sizeof(buf));
2135 
2137  buf, p - buf);
2138 }
2139 #endif /* DTLS_ECC */
2140 
2141 static int
2143 {
2144 
2145  /* ServerHelloDone
2146  *
2147  * Start message construction at beginning of buffer. */
2148 
2150  NULL, 0);
2151 }
2152 
2153 static int
2155 {
2156  int res;
2157 
2158  res = dtls_send_server_hello(ctx, peer);
2159 
2160  if (res < 0) {
2161  dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2162  return res;
2163  }
2164 
2165 #ifdef DTLS_ECC
2167  const dtls_ecdsa_key_t *ecdsa_key;
2168 
2169  res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2170  if (res < 0) {
2171  dtls_crit("no ecdsa certificate to send in certificate\n");
2172  return res;
2173  }
2174 
2175  res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2176 
2177  if (res < 0) {
2178  dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2179  return res;
2180  }
2181 
2182  res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2183 
2184  if (res < 0) {
2185  dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2186  return res;
2187  }
2188 
2191  res = dtls_send_server_certificate_request(ctx, peer);
2192 
2193  if (res < 0) {
2194  dtls_debug("dtls_server_hello: cannot prepare certificate Request record\n");
2195  return res;
2196  }
2197  }
2198  }
2199 #endif /* DTLS_ECC */
2200 
2201 #ifdef DTLS_PSK
2203  unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2204  int len;
2205 
2206  /* The identity hint is optional, therefore we ignore the result
2207  * and check psk only. */
2208  len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2209  NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2210 
2211  if (len < 0) {
2212  dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2213  return len;
2214  }
2215 
2216  if (len > 0) {
2217  res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2218 
2219  if (res < 0) {
2220  dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2221  return res;
2222  }
2223  }
2224  }
2225 #endif /* DTLS_PSK */
2226 
2227  res = dtls_send_server_hello_done(ctx, peer);
2228 
2229  if (res < 0) {
2230  dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2231  return res;
2232  }
2233  return 0;
2234 }
2235 
2236 static inline int
2238  uint8 buf[1] = {1};
2239 
2240  return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2241 }
2242 
2243 
2244 static int
2246 {
2247  uint8 buf[DTLS_CKXEC_LENGTH];
2248  uint8 *p;
2249  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2250 
2251  p = buf;
2252 
2253  switch (handshake->cipher) {
2254 #ifdef DTLS_PSK
2256  int len;
2257 
2258  len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2259  handshake->keyx.psk.identity, handshake->keyx.psk.id_length,
2260  buf + sizeof(uint16),
2261  min(sizeof(buf) - sizeof(uint16),
2262  sizeof(handshake->keyx.psk.identity)));
2263  if (len < 0) {
2264  dtls_crit("no psk identity set in kx\n");
2265  return len;
2266  }
2267 
2268  if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2269  memset(&handshake->keyx.psk, 0, sizeof(dtls_handshake_parameters_psk_t));
2270  dtls_warn("the psk identity is too long\n");
2272  }
2273  handshake->keyx.psk.id_length = (unsigned int)len;
2274  memcpy(handshake->keyx.psk.identity, p + sizeof(uint16), len);
2275 
2276  dtls_int_to_uint16(p, handshake->keyx.psk.id_length);
2277  p += sizeof(uint16);
2278 
2279  memcpy(p, handshake->keyx.psk.identity, handshake->keyx.psk.id_length);
2280  p += handshake->keyx.psk.id_length;
2281 
2282  break;
2283  }
2284 #endif /* DTLS_PSK */
2285 #ifdef DTLS_ECC
2287  uint8 *ephemeral_pub_x;
2288  uint8 *ephemeral_pub_y;
2289 
2290  dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2291  p += sizeof(uint8);
2292 
2293  /* This should be an uncompressed point, but I do not have access to the spec. */
2294  dtls_int_to_uint8(p, 4);
2295  p += sizeof(uint8);
2296 
2297  ephemeral_pub_x = p;
2298  p += DTLS_EC_KEY_SIZE;
2299  ephemeral_pub_y = p;
2300  p += DTLS_EC_KEY_SIZE;
2301 
2303  ephemeral_pub_x, ephemeral_pub_y,
2305 
2306  break;
2307  }
2308 #endif /* DTLS_ECC */
2309 
2311  assert(!"NULL cipher requested");
2313 
2314  /* The following cases cover the enum symbols that are not
2315  * included in this build. These must be kept just above the
2316  * default case as they do nothing but fall through.
2317  */
2318 #ifndef DTLS_PSK
2320  /* fall through to default */
2321 #endif /* !DTLS_PSK */
2322 
2323 #ifndef DTLS_ECC
2325  /* fall through to default */
2326 #endif /* !DTLS_ECC */
2327 
2328  default:
2329  dtls_crit("cipher %x04 not supported\n", handshake->cipher);
2331  }
2332 
2333  assert((buf <= p) && ((unsigned int)(p - buf) <= sizeof(buf)));
2334 
2336  buf, p - buf);
2337 }
2338 
2339 #ifdef DTLS_ECC
2340 static int
2342  const dtls_ecdsa_key_t *key)
2343 {
2344  /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2345  * 33 bytes long add space for that */
2346  uint8 buf[DTLS_CV_LENGTH + 2];
2347  uint8 *p;
2348  uint32_t point_r[9];
2349  uint32_t point_s[9];
2350  dtls_hash_ctx hs_hash;
2351  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2352 
2353  /* ServerKeyExchange
2354  *
2355  * Start message construction at beginning of buffer. */
2356  p = buf;
2357 
2358  copy_hs_hash(peer, &hs_hash);
2359 
2360  dtls_hash_finalize(sha256hash, &hs_hash);
2361 
2362  /* sign the ephemeral and its paramaters */
2364  sha256hash, sizeof(sha256hash),
2365  point_r, point_s);
2366 
2367  p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2368 
2369  assert(p - buf <= sizeof(buf));
2370 
2372  buf, p - buf);
2373 }
2374 #endif /* DTLS_ECC */
2375 
2376 static int
2378  const unsigned char *label, size_t labellen)
2379 {
2380  int length;
2381  uint8 hash[DTLS_HMAC_MAX];
2382  uint8 buf[DTLS_FIN_LENGTH];
2383  dtls_hash_ctx hs_hash;
2384  uint8 *p = buf;
2385 
2386  copy_hs_hash(peer, &hs_hash);
2387 
2388  length = dtls_hash_finalize(hash, &hs_hash);
2389 
2392  label, labellen,
2393  PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2394  hash, length,
2395  p, DTLS_FIN_LENGTH);
2396 
2397  dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2398 
2399  p += DTLS_FIN_LENGTH;
2400 
2401  assert((buf <= p) && ((unsigned int)(p - buf) <= sizeof(buf)));
2402 
2403  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2404  buf, p - buf);
2405 }
2406 
2407 static int
2409  uint8 cookie[], size_t cookie_length) {
2411  uint8 *p = buf;
2412  uint8_t cipher_size;
2413  uint8_t extension_size;
2414  int psk;
2415  int ecdsa;
2416  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2417  dtls_tick_t now;
2418 
2419  psk = is_psk_supported(ctx);
2420  ecdsa = is_ecdsa_supported(ctx, 1);
2421 
2422  cipher_size = 2 + ((ecdsa) ? 2 : 0) + ((psk) ? 2 : 0);
2423  extension_size = (ecdsa) ? 2 + 6 + 6 + 8 + 6: 0;
2424 
2425  if (cipher_size == 0) {
2426  dtls_crit("no cipher callbacks implemented\n");
2427  }
2428 
2430  p += sizeof(uint16);
2431 
2432  if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2433  dtls_warn("the cookie is too long\n");
2435  }
2436 
2437  if (cookie_length == 0) {
2438  /* Set client random: First 4 bytes are the client's Unix timestamp,
2439  * followed by 28 bytes of generate random data. */
2440  dtls_ticks(&now);
2441  dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2442  dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2443  DTLS_RANDOM_LENGTH - sizeof(uint32));
2444  }
2445  /* we must use the same Client Random as for the previous request */
2446  memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2447  p += DTLS_RANDOM_LENGTH;
2448 
2449  /* session id (length 0) */
2450  dtls_int_to_uint8(p, 0);
2451  p += sizeof(uint8);
2452 
2453  /* cookie */
2454  dtls_int_to_uint8(p, cookie_length);
2455  p += sizeof(uint8);
2456  if (cookie_length != 0) {
2457  memcpy(p, cookie, cookie_length);
2458  p += cookie_length;
2459  }
2460 
2461  /* add known cipher(s) */
2462  dtls_int_to_uint16(p, cipher_size - 2);
2463  p += sizeof(uint16);
2464 
2465  if (ecdsa) {
2467  p += sizeof(uint16);
2468  }
2469  if (psk) {
2471  p += sizeof(uint16);
2472  }
2473 
2474  /* compression method */
2475  dtls_int_to_uint8(p, 1);
2476  p += sizeof(uint8);
2477 
2479  p += sizeof(uint8);
2480 
2481  if (extension_size) {
2482  /* length of the extensions */
2483  dtls_int_to_uint16(p, extension_size - 2);
2484  p += sizeof(uint16);
2485  }
2486 
2487  if (ecdsa) {
2488  /* client certificate type extension */
2490  p += sizeof(uint16);
2491 
2492  /* length of this extension type */
2493  dtls_int_to_uint16(p, 2);
2494  p += sizeof(uint16);
2495 
2496  /* length of the list */
2497  dtls_int_to_uint8(p, 1);
2498  p += sizeof(uint8);
2499 
2501  p += sizeof(uint8);
2502 
2503  /* client certificate type extension */
2505  p += sizeof(uint16);
2506 
2507  /* length of this extension type */
2508  dtls_int_to_uint16(p, 2);
2509  p += sizeof(uint16);
2510 
2511  /* length of the list */
2512  dtls_int_to_uint8(p, 1);
2513  p += sizeof(uint8);
2514 
2516  p += sizeof(uint8);
2517 
2518  /* elliptic_curves */
2520  p += sizeof(uint16);
2521 
2522  /* length of this extension type */
2523  dtls_int_to_uint16(p, 4);
2524  p += sizeof(uint16);
2525 
2526  /* length of the list */
2527  dtls_int_to_uint16(p, 2);
2528  p += sizeof(uint16);
2529 
2531  p += sizeof(uint16);
2532 
2533  /* ec_point_formats */
2535  p += sizeof(uint16);
2536 
2537  /* length of this extension type */
2538  dtls_int_to_uint16(p, 2);
2539  p += sizeof(uint16);
2540 
2541  /* number of supported formats */
2542  dtls_int_to_uint8(p, 1);
2543  p += sizeof(uint8);
2544 
2546  p += sizeof(uint8);
2547  }
2548 
2549  assert((buf <= p) && ((unsigned int)(p - buf) <= sizeof(buf)));
2550 
2551  if (cookie_length != 0)
2552  clear_hs_hash(peer);
2553 
2554  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2556  buf, p - buf, cookie_length != 0);
2557 }
2558 
2559 static int
2561  dtls_peer_t *peer,
2562  uint8 *data, size_t data_length)
2563 {
2564  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2565 
2566  /* This function is called when we expect a ServerHello (i.e. we
2567  * have sent a ClientHello). We might instead receive a HelloVerify
2568  * request containing a cookie. If so, we must repeat the
2569  * ClientHello with the given Cookie.
2570  */
2571  if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
2573 
2574  update_hs_hash(peer, data, data_length);
2575 
2576  /* FIXME: check data_length before accessing fields */
2577 
2578  /* Get the server's random data and store selected cipher suite
2579  * and compression method (like dtls_update_parameters().
2580  * Then calculate master secret and wait for ServerHelloDone. When received,
2581  * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
2582 
2583  /* check server version */
2584  data += DTLS_HS_LENGTH;
2585  data_length -= DTLS_HS_LENGTH;
2586 
2587  if (dtls_uint16_to_int(data) != DTLS_VERSION) {
2588  dtls_alert("unknown DTLS version\n");
2590  }
2591 
2592  data += sizeof(uint16); /* skip version field */
2593  data_length -= sizeof(uint16);
2594 
2595  /* store server random data */
2596  memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
2597  /* skip server random */
2598  data += DTLS_RANDOM_LENGTH;
2599  data_length -= DTLS_RANDOM_LENGTH;
2600 
2601  SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
2602 
2603  /* Check cipher suite. As we offer all we have, it is sufficient
2604  * to check if the cipher suite selected by the server is in our
2605  * list of known cipher suites. Subsets are not supported. */
2606  handshake->cipher = dtls_uint16_to_int(data);
2607  if (!known_cipher(ctx, handshake->cipher, 1)) {
2608  dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
2609  data[0], data[1]);
2611  }
2612  data += sizeof(uint16);
2613  data_length -= sizeof(uint16);
2614 
2615  /* Check if NULL compression was selected. We do not know any other. */
2616  if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
2617  dtls_alert("unsupported compression method 0x%02x\n", data[0]);
2619  }
2620  data += sizeof(uint8);
2621  data_length -= sizeof(uint8);
2622 
2623  return dtls_check_tls_extension(peer, data, data_length, 0);
2624 
2625 error:
2627 }
2628 
2629 static int
2631  dtls_peer_t *peer,
2632  uint8 *data, size_t data_length)
2633 {
2634  dtls_hello_verify_t *hv;
2635  int res;
2636 
2637  if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
2639 
2640  hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
2641 
2642  res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
2643 
2644  if (res < 0)
2645  dtls_warn("cannot send ClientHello\n");
2646 
2647  return res;
2648 }
2649 
2650 #ifdef DTLS_ECC
2651 static int
2653  dtls_peer_t *peer,
2654  uint8 *data, size_t data_length)
2655 {
2656  int err;
2658 
2659  update_hs_hash(peer, data, data_length);
2660 
2662 
2663  data += DTLS_HS_LENGTH;
2664 
2666  dtls_alert("expect length of %zu bytes for certificate\n",
2669  }
2670  data += sizeof(uint24);
2671 
2672  if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
2673  dtls_alert("got an unexpected Subject public key format\n");
2675  }
2676  data += sizeof(cert_asn1_header);
2677 
2678  memcpy(config->keyx.ecdsa.other_pub_x, data,
2679  sizeof(config->keyx.ecdsa.other_pub_x));
2680  data += sizeof(config->keyx.ecdsa.other_pub_x);
2681 
2682  memcpy(config->keyx.ecdsa.other_pub_y, data,
2683  sizeof(config->keyx.ecdsa.other_pub_y));
2684  data += sizeof(config->keyx.ecdsa.other_pub_y);
2685 
2686  err = CALL(ctx, verify_ecdsa_key, &peer->session,
2687  config->keyx.ecdsa.other_pub_x,
2688  config->keyx.ecdsa.other_pub_y,
2689  sizeof(config->keyx.ecdsa.other_pub_x));
2690  if (err < 0) {
2691  dtls_warn("The certificate was not accepted\n");
2692  return err;
2693  }
2694 
2695  return 0;
2696 }
2697 
2698 static int
2700  dtls_peer_t *peer,
2701  uint8 *data, size_t data_length)
2702 {
2704  int ret;
2705  unsigned char *result_r;
2706  unsigned char *result_s;
2707  unsigned char *key_params;
2708 
2709  update_hs_hash(peer, data, data_length);
2710 
2712 
2713  data += DTLS_HS_LENGTH;
2714 
2715  if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
2716  dtls_alert("the packet length does not match the expected\n");
2718  }
2719  key_params = data;
2720 
2722  dtls_alert("Only named curves supported\n");
2724  }
2725  data += sizeof(uint8);
2726  data_length -= sizeof(uint8);
2727 
2729  dtls_alert("secp256r1 supported\n");
2731  }
2732  data += sizeof(uint16);
2733  data_length -= sizeof(uint16);
2734 
2735  if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
2736  dtls_alert("expected 65 bytes long public point\n");
2738  }
2739  data += sizeof(uint8);
2740  data_length -= sizeof(uint8);
2741 
2742  if (dtls_uint8_to_int(data) != 4) {
2743  dtls_alert("expected uncompressed public point\n");
2745  }
2746  data += sizeof(uint8);
2747  data_length -= sizeof(uint8);
2748 
2749  memcpy(config->keyx.ecdsa.other_eph_pub_x, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
2750  data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
2751  data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
2752 
2753  memcpy(config->keyx.ecdsa.other_eph_pub_y, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
2754  data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
2755  data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
2756 
2757  ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
2758  if (ret < 0) {
2759  return ret;
2760  }
2761  data += ret;
2762  data_length -= ret;
2763 
2765  sizeof(config->keyx.ecdsa.other_pub_x),
2766  config->tmp.random.client, DTLS_RANDOM_LENGTH,
2767  config->tmp.random.server, DTLS_RANDOM_LENGTH,
2768  key_params,
2769  1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
2770  result_r, result_s);
2771 
2772  if (ret < 0) {
2773  dtls_alert("wrong signature\n");
2775  }
2776  return 0;
2777 }
2778 #endif /* DTLS_ECC */
2779 
2780 #ifdef DTLS_PSK
2781 static int
2783  dtls_peer_t *peer,
2784  uint8 *data, size_t data_length)
2785 {
2787  uint16_t len;
2788  (void)ctx;
2789 
2790  update_hs_hash(peer, data, data_length);
2791 
2793 
2794  data += DTLS_HS_LENGTH;
2795 
2796  if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
2797  dtls_alert("the packet length does not match the expected\n");
2799  }
2800 
2801  len = dtls_uint16_to_int(data);
2802  data += sizeof(uint16);
2803 
2804  if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
2805  dtls_warn("the length of the server identity hint is worng\n");
2807  }
2808 
2810  dtls_warn("please use a smaller server identity hint\n");
2812  }
2813 
2814  /* store the psk_identity_hint in config->keyx.psk for later use */
2815  config->keyx.psk.id_length = len;
2816  memcpy(config->keyx.psk.identity, data, len);
2817  return 0;
2818 }
2819 #endif /* DTLS_PSK */
2820 
2821 static int
2823  dtls_peer_t *peer,
2824  uint8 *data, size_t data_length)
2825 {
2826  unsigned int i;
2827  int auth_alg;
2828  int sig_alg;
2829  int hash_alg;
2830  (void)ctx;
2831 
2832  update_hs_hash(peer, data, data_length);
2833 
2835 
2836  data += DTLS_HS_LENGTH;
2837 
2838  if (data_length < DTLS_HS_LENGTH + 5) {
2839  dtls_alert("the packet length does not match the expected\n");
2841  }
2842 
2843  i = dtls_uint8_to_int(data);
2844  data += sizeof(uint8);
2845  if (i + 1 > data_length) {
2846  dtls_alert("the cerfificate types are too long\n");
2848  }
2849 
2850  auth_alg = 0;
2851  for (; i > 0 ; i -= sizeof(uint8)) {
2853  && auth_alg == 0)
2854  auth_alg = dtls_uint8_to_int(data);
2855  data += sizeof(uint8);
2856  }
2857 
2858  if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
2859  dtls_alert("the request authentication algorithm is not supproted\n");
2861  }
2862 
2863  i = dtls_uint16_to_int(data);
2864  data += sizeof(uint16);
2865  if (i + 1 > data_length) {
2866  dtls_alert("the signature and hash algorithm list is too long\n");
2868  }
2869 
2870  hash_alg = 0;
2871  sig_alg = 0;
2872  for (; i > 0 ; i -= sizeof(uint16)) {
2873  int current_hash_alg;
2874  int current_sig_alg;
2875 
2876  current_hash_alg = dtls_uint8_to_int(data);
2877  data += sizeof(uint8);
2878  current_sig_alg = dtls_uint8_to_int(data);
2879  data += sizeof(uint8);
2880 
2881  if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 &&
2882  current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
2883  hash_alg = current_hash_alg;
2884  sig_alg = current_sig_alg;
2885  }
2886  }
2887 
2888  if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
2889  sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
2890  dtls_alert("no supported hash and signature algorithem\n");
2892  }
2893 
2894  /* common names are ignored */
2895 
2896  peer->handshake_params->do_client_auth = 1;
2897  return 0;
2898 }
2899 
2900 static int
2902  dtls_peer_t *peer,
2903  uint8 *data, size_t data_length)
2904 {
2905  int res;
2906 #ifdef DTLS_ECC
2907  const dtls_ecdsa_key_t *ecdsa_key;
2908 #endif /* DTLS_ECC */
2909 
2910  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2911 
2912  /* calculate master key, send CCS */
2913 
2914  update_hs_hash(peer, data, data_length);
2915 
2916 #ifdef DTLS_ECC
2917  if (handshake->do_client_auth) {
2918 
2919  res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2920  if (res < 0) {
2921  dtls_crit("no ecdsa certificate to send in certificate\n");
2922  return res;
2923  }
2924 
2925  res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2926 
2927  if (res < 0) {
2928  dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2929  return res;
2930  }
2931  }
2932 #endif /* DTLS_ECC */
2933 
2934  /* send ClientKeyExchange */
2935  res = dtls_send_client_key_exchange(ctx, peer);
2936 
2937  if (res < 0) {
2938  dtls_debug("cannot send KeyExchange message\n");
2939  return res;
2940  }
2941 
2942 #ifdef DTLS_ECC
2943  if (handshake->do_client_auth) {
2944 
2945  res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
2946 
2947  if (res < 0) {
2948  dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2949  return res;
2950  }
2951  }
2952 #endif /* DTLS_ECC */
2953 
2954  res = calculate_key_block(ctx, handshake, peer,
2955  &peer->session, peer->role);
2956  if (res < 0) {
2957  return res;
2958  }
2959 
2960  res = dtls_send_ccs(ctx, peer);
2961  if (res < 0) {
2962  dtls_debug("cannot send CCS message\n");
2963  return res;
2964  }
2965 
2966  /* and switch cipher suite */
2968 
2969  /* Client Finished */
2970  return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
2971 }
2972 
2973 static int
2974 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
2975  uint8 **cleartext)
2976 {
2977  dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
2979  int clen;
2980 
2981  *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
2982  clen = length - sizeof(dtls_record_header_t);
2983 
2984  if (!security) {
2985  dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
2986  return -1;
2987  }
2988 
2989  if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
2990  /* no cipher suite selected */
2991  return clen;
2992  } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
2997 #define A_DATA_LEN 13
2998  unsigned char nonce[DTLS_CCM_BLOCKSIZE];
2999  unsigned char A_DATA[A_DATA_LEN];
3000 
3001  if (clen < 16) /* need at least IV and MAC */
3002  return -1;
3003 
3004  memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
3005  memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
3006  dtls_kb_iv_size(security, peer->role));
3007 
3008  /* read epoch and seq_num from message */
3009  memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
3010  *cleartext += 8;
3011  clen -= 8;
3012 
3013  dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
3014  dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
3015  dtls_kb_key_size(security, peer->role));
3016  dtls_debug_dump("ciphertext", *cleartext, clen);
3017 
3018  /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
3019  *
3020  * additional_data = seq_num + TLSCompressed.type +
3021  * TLSCompressed.version + TLSCompressed.length;
3022  */
3023  memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
3024  memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
3025  dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
3026 
3027  clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3028  dtls_kb_remote_write_key(security, peer->role),
3029  dtls_kb_key_size(security, peer->role),
3030  A_DATA, A_DATA_LEN);
3031  if (clen < 0)
3032  dtls_warn("decryption failed\n");
3033  else {
3034 #ifndef NDEBUG
3035  printf("decrypt_verify(): found %i bytes cleartext\n", clen);
3036 #endif
3038  dtls_debug_dump("cleartext", *cleartext, clen);
3039  }
3040  }
3041  return clen;
3042 }
3043 
3044 static int
3046 {
3047  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3049  NULL, 0, 0);
3050 }
3051 
3052 int
3054 {
3055  dtls_peer_t *peer = NULL;
3056  int err;
3057 
3058  peer = dtls_get_peer(ctx, dst);
3059 
3060  if (!peer) {
3061  return -1;
3062  }
3063  if (peer->state != DTLS_STATE_CONNECTED)
3064  return -1;
3065 
3067  if (!peer->handshake_params)
3068  return -1;
3069 
3070  peer->handshake_params->hs_state.mseq_r = 0;
3071  peer->handshake_params->hs_state.mseq_s = 0;
3072 
3073  if (peer->role == DTLS_CLIENT) {
3074  /* send ClientHello with empty Cookie */
3075  err = dtls_send_client_hello(ctx, peer, NULL, 0);
3076  if (err < 0)
3077  dtls_warn("cannot send ClientHello\n");
3078  else
3079  peer->state = DTLS_STATE_CLIENTHELLO;
3080  return err;
3081  } else if (peer->role == DTLS_SERVER) {
3082  return dtls_send_hello_request(ctx, peer);
3083  }
3084 
3085  return -1;
3086 }
3087 
3088 static int
3090  const dtls_peer_type role, const dtls_state_t state,
3091  uint8 *data, size_t data_length) {
3092 
3093  int err = 0;
3094 
3095  /* This will clear the retransmission buffer if we get an expected
3096  * handshake message. We have to make sure that no handshake message
3097  * should get expected when we still should retransmit something, when
3098  * we do everything accordingly to the DTLS 1.2 standard this should
3099  * not be a problem. */
3100  if (peer) {
3101  dtls_stop_retransmission(ctx, peer);
3102  }
3103 
3104  /* The following switch construct handles the given message with
3105  * respect to the current internal state for this peer. In case of
3106  * error, it is left with return 0. */
3107 
3108  dtls_debug("handle handshake packet of type: %s (%i)\n",
3109  dtls_handshake_type_to_name(data[0]), data[0]);
3110  switch (data[0]) {
3111 
3112  /************************************************************************
3113  * Client states
3114  ************************************************************************/
3116 
3117  if (state != DTLS_STATE_CLIENTHELLO) {
3119  }
3120 
3121  err = check_server_hello_verify_request(ctx, peer, data, data_length);
3122  if (err < 0) {
3123  dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3124  return err;
3125  }
3126 
3127  break;
3128  case DTLS_HT_SERVER_HELLO:
3129 
3130  if (state != DTLS_STATE_CLIENTHELLO) {
3132  }
3133 
3134  err = check_server_hello(ctx, peer, data, data_length);
3135  if (err < 0) {
3136  dtls_warn("error in check_server_hello err: %i\n", err);
3137  return err;
3138  }
3141  else
3143  /* update_hs_hash(peer, data, data_length); */
3144 
3145  break;
3146 
3147 #ifdef DTLS_ECC
3148  case DTLS_HT_CERTIFICATE:
3149 
3150  if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3151  (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3153  }
3154  err = check_server_certificate(ctx, peer, data, data_length);
3155  if (err < 0) {
3156  dtls_warn("error in check_server_certificate err: %i\n", err);
3157  return err;
3158  }
3159  if (role == DTLS_CLIENT) {
3161  } else if (role == DTLS_SERVER){
3163  }
3164  /* update_hs_hash(peer, data, data_length); */
3165 
3166  break;
3167 #endif /* DTLS_ECC */
3168 
3170 
3171 #ifdef DTLS_ECC
3173  if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3175  }
3176  err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3177  }
3178 #endif /* DTLS_ECC */
3179 #ifdef DTLS_PSK
3181  if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3183  }
3184  err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3185  }
3186 #endif /* DTLS_PSK */
3187 
3188  if (err < 0) {
3189  dtls_warn("error in check_server_key_exchange err: %i\n", err);
3190  return err;
3191  }
3193  /* update_hs_hash(peer, data, data_length); */
3194 
3195  break;
3196 
3198 
3199  if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3201  }
3202 
3203  err = check_server_hellodone(ctx, peer, data, data_length);
3204  if (err < 0) {
3205  dtls_warn("error in check_server_hellodone err: %i\n", err);
3206  return err;
3207  }
3209  /* update_hs_hash(peer, data, data_length); */
3210 
3211  break;
3212 
3214 
3215  if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3217  }
3218 
3219  err = check_certificate_request(ctx, peer, data, data_length);
3220  if (err < 0) {
3221  dtls_warn("error in check_certificate_request err: %i\n", err);
3222  return err;
3223  }
3224 
3225  break;
3226 
3227  case DTLS_HT_FINISHED:
3228  /* expect a Finished message from server */
3229 
3230  if (state != DTLS_STATE_WAIT_FINISHED) {
3232  }
3233 
3234  err = check_finished(ctx, peer, data, data_length);
3235  if (err < 0) {
3236  dtls_warn("error in check_finished err: %i\n", err);
3237  return err;
3238  }
3239  if (role == DTLS_SERVER) {
3240  /* send ServerFinished */
3241  update_hs_hash(peer, data, data_length);
3242 
3243  /* send change cipher spec message and switch to new configuration */
3244  err = dtls_send_ccs(ctx, peer);
3245  if (err < 0) {
3246  dtls_warn("cannot send CCS message\n");
3247  return err;
3248  }
3249 
3251 
3252  err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3253  if (err < 0) {
3254  dtls_warn("sending server Finished failed\n");
3255  return err;
3256  }
3257  }
3259  peer->handshake_params = NULL;
3260  dtls_debug("Handshake complete\n");
3261  check_stack();
3262  peer->state = DTLS_STATE_CONNECTED;
3263 
3264  /* return here to not increase the message receive counter */
3265  return err;
3266 
3267  /************************************************************************
3268  * Server states
3269  ************************************************************************/
3270 
3272  /* handle ClientHello, update msg and msglen and goto next if not finished */
3273 
3274  if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3276  }
3277 
3278  err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3279  if (err < 0) {
3280  dtls_warn("error in check_client_keyexchange err: %i\n", err);
3281  return err;
3282  }
3283  update_hs_hash(peer, data, data_length);
3284 
3288  else
3290  break;
3291 
3292 #ifdef DTLS_ECC
3294 
3295  if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
3297  }
3298 
3299  err = check_client_certificate_verify(ctx, peer, data, data_length);
3300  if (err < 0) {
3301  dtls_warn("error in check_client_certificate_verify err: %i\n", err);
3302  return err;
3303  }
3304 
3305  update_hs_hash(peer, data, data_length);
3307  break;
3308 #endif /* DTLS_ECC */
3309 
3310  case DTLS_HT_CLIENT_HELLO:
3311 
3312  if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
3313  (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
3315  }
3316 
3317  /* When no DTLS state exists for this peer, we only allow a
3318  Client Hello message with
3319 
3320  a) a valid cookie, or
3321  b) no cookie.
3322 
3323  Anything else will be rejected. Fragementation is not allowed
3324  here as it would require peer state as well.
3325  */
3326  err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
3327  if (err < 0) {
3328  dtls_warn("error in dtls_verify_peer err: %i\n", err);
3329  return err;
3330  }
3331 
3332  if (err > 0) {
3333  dtls_debug("server hello verify was sent\n");
3334  break;
3335  }
3336 
3337  /* At this point, we have a good relationship with this peer. This
3338  * state is left for re-negotiation of key material. */
3339  /* As per RFC 6347 - section 4.2.8 if this is an attempt to
3340  * rehandshake, we can delete the existing key material
3341  * as the client has demonstrated reachibility by completing
3342  * the cookie exchange */
3343  if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
3344  dtls_debug("removing the peer\n");
3345  DEL_PEER(ctx->peers, peer);
3346 
3347  dtls_free_peer(peer);
3348  peer = NULL;
3349  }
3350  if (!peer) {
3351  dtls_debug("creating new peer\n");
3352  dtls_security_parameters_t *security;
3353 
3354  /* msg contains a Client Hello with a valid cookie, so we can
3355  * safely create the server state machine and continue with
3356  * the handshake. */
3357  peer = dtls_new_peer(session);
3358  if (!peer) {
3359  dtls_alert("cannot create peer\n");
3361  }
3362  peer->role = DTLS_SERVER;
3363 
3364  /* Initialize record sequence number to 1 for new peers. The first
3365  * record with sequence number 0 is a stateless Hello Verify Request.
3366  */
3367  security = dtls_security_params(peer);
3368  security->rseq = 1;
3369 
3370  if (dtls_add_peer(ctx, peer) < 0) {
3371  dtls_alert("cannot add peer\n");
3372  dtls_free_peer(peer);
3374  }
3375  }
3376  if (peer && !peer->handshake_params) {
3378 
3380  if (!peer->handshake_params)
3382 
3383  peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
3384  peer->handshake_params->hs_state.mseq_s = 1;
3385  }
3386 
3387  clear_hs_hash(peer);
3388 
3389  /* First negotiation step: check for PSK
3390  *
3391  * Note that we already have checked that msg is a Handshake
3392  * message containing a ClientHello. dtls_get_cipher() therefore
3393  * does not check again.
3394  */
3395  err = dtls_update_parameters(ctx, peer, data, data_length);
3396  if (err < 0) {
3397  dtls_warn("error updating security parameters\n");
3398  return err;
3399  }
3400 
3401  /* update finish MAC */
3402  update_hs_hash(peer, data, data_length);
3403 
3404  err = dtls_send_server_hello_msgs(ctx, peer);
3405  if (err < 0) {
3406  return err;
3407  }
3411  else
3413 
3414  /* after sending the ServerHelloDone, we expect the
3415  * ClientKeyExchange (possibly containing the PSK id),
3416  * followed by a ChangeCipherSpec and an encrypted Finished.
3417  */
3418 
3419  break;
3420 
3421  case DTLS_HT_HELLO_REQUEST:
3422 
3423  if (state != DTLS_STATE_CONNECTED) {
3424  /* we should just ignore such packets when in handshake */
3425  return 0;
3426  }
3427 
3428  if (peer && !peer->handshake_params) {
3430  if (!peer->handshake_params)
3432 
3433  peer->handshake_params->hs_state.mseq_r = 0;
3434  peer->handshake_params->hs_state.mseq_s = 0;
3435  }
3436 
3437  /* send ClientHello with empty Cookie */
3438  err = dtls_send_client_hello(ctx, peer, NULL, 0);
3439  if (err < 0) {
3440  dtls_warn("cannot send ClientHello\n");
3441  return err;
3442  }
3443  peer->state = DTLS_STATE_CLIENTHELLO;
3444  break;
3445 
3446  default:
3447  dtls_crit("unhandled message %d\n", data[0]);
3449  }
3450 
3451  if (peer && peer->handshake_params && err >= 0) {
3452  peer->handshake_params->hs_state.mseq_r++;
3453  }
3454 
3455  return err;
3456 }
3457 
3458 static int
3460  const dtls_peer_type role, const dtls_state_t state,
3461  uint8 *data, size_t data_length)
3462 {
3463  dtls_handshake_header_t *hs_header;
3464  int res;
3465 
3466  if (data_length < DTLS_HS_LENGTH) {
3467  dtls_warn("handshake message too short\n");
3469  }
3470  hs_header = DTLS_HANDSHAKE_HEADER(data);
3471 
3472  dtls_debug("received handshake packet of type: %s (%i)\n",
3473  dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
3474 
3475  if (!peer || !peer->handshake_params) {
3476  /* This is the initial ClientHello */
3477  if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
3478  dtls_warn("If there is no peer only ClientHello is allowed\n");
3480  }
3481 
3482  /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
3483  if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
3484  hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
3485  return handle_handshake_msg(ctx, peer, session, role, state, data,
3486  data_length);
3487  } else {
3488  dtls_warn("ignore unexpected handshake message\n");
3489  return 0;
3490  }
3491  }
3492 
3493  if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
3494  dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
3495  peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
3496  return 0;
3497  } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
3498  /* A packet in between is missing, buffer this packet. */
3499  netq_t *n;
3500 
3501  /* TODO: only add packet that are not too new. */
3502  if (data_length > DTLS_MAX_BUF) {
3503  dtls_warn("the packet is too big to buffer for reoder\n");
3504  return 0;
3505  }
3506 
3508  while (node) {
3509  dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
3510  if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
3511  dtls_warn("a packet with this sequence number is already stored\n");
3512  return 0;
3513  }
3514  node = netq_next(node);
3515  }
3516 
3517  n = netq_node_new(data_length);
3518  if (!n) {
3519  dtls_warn("no space in reoder buffer\n");
3520  return 0;
3521  }
3522 
3523  n->peer = peer;
3524  n->length = data_length;
3525  memcpy(n->data, data, data_length);
3526 
3527  if (!netq_insert_node(&peer->handshake_params->reorder_queue, n)) {
3528  dtls_warn("cannot add packet to reoder buffer\n");
3529  netq_node_free(n);
3530  }
3531  dtls_info("Added packet for reordering\n");
3532  return 0;
3533  } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
3534  /* Found the expected packet, use this and all the buffered packet */
3535  int next = 1;
3536 
3537  res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
3538  if (res < 0)
3539  return res;
3540 
3541  /* We do not know in which order the packet are in the list just search the list for every packet. */
3542  while (next && peer->handshake_params) {
3543  next = 0;
3545  while (node) {
3546  dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
3547 
3548  if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
3550  next = 1;
3551  res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
3552  if (res < 0) {
3553  return res;
3554  }
3555 
3556  break;
3557  } else {
3558  node = netq_next(node);
3559  }
3560  }
3561  }
3562  return res;
3563  }
3564  assert(0);
3565  return 0;
3566 }
3567 
3568 static int
3570  uint8 *record_header, uint8 *data, size_t data_length)
3571 {
3572  int err;
3573  dtls_handshake_parameters_t *handshake = peer->handshake_params;
3574  (void)record_header;
3575 
3576  /* A CCS message is handled after a KeyExchange message was
3577  * received from the client. When security parameters have been
3578  * updated successfully and a ChangeCipherSpec message was sent
3579  * by ourself, the security context is switched and the record
3580  * sequence number is reset. */
3581 
3582  if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
3583  dtls_warn("expected ChangeCipherSpec during handshake\n");
3584  return 0;
3585  }
3586 
3587  if (data_length < 1 || data[0] != 1)
3589 
3590  /* Just change the cipher when we are on the same epoch */
3591  if (peer->role == DTLS_SERVER) {
3592  err = calculate_key_block(ctx, handshake, peer,
3593  &peer->session, peer->role);
3594  if (err < 0) {
3595  return err;
3596  }
3597  }
3598 
3600 
3601  return 0;
3602 }
3603 
3608 static int
3610  uint8 *record_header, uint8 *data, size_t data_length) {
3611  int free_peer = 0; /* indicates whether to free peer */
3612  (void)record_header;
3613 
3614  if (data_length < 2)
3616 
3617  dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
3618 
3619  if (!peer) {
3620  dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
3621  return 0;
3622  }
3623 
3624  /* The peer object is invalidated for FATAL alerts and close
3625  * notifies. This is done in two steps.: First, remove the object
3626  * from our list of peers. After that, the event handler callback is
3627  * invoked with the still existing peer object. Finally, the storage
3628  * used by peer is released.
3629  */
3630  if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
3631  dtls_alert("%d invalidate peer\n", data[1]);
3632 
3633  DEL_PEER(ctx->peers, peer);
3634 
3635 #ifdef WITH_CONTIKI
3636 #ifndef NDEBUG
3637  PRINTF("removed peer [");
3638  PRINT6ADDR(&peer->session.addr);
3639  PRINTF("]:%d\n", uip_ntohs(peer->session.port));
3640 #endif
3641 #endif /* WITH_CONTIKI */
3642 
3643  free_peer = 1;
3644 
3645  }
3646 
3647  (void)CALL(ctx, event, &peer->session,
3648  (dtls_alert_level_t)data[0], (unsigned short)data[1]);
3649  switch (data[1]) {
3651  /* If state is DTLS_STATE_CLOSING, we have already sent a
3652  * close_notify so, do not send that again. */
3653  if (peer->state != DTLS_STATE_CLOSING) {
3654  peer->state = DTLS_STATE_CLOSING;
3656  } else
3657  peer->state = DTLS_STATE_CLOSED;
3658  break;
3659  default:
3660  ;
3661  }
3662 
3663  if (free_peer) {
3664  dtls_stop_retransmission(ctx, peer);
3665  dtls_destroy_peer(ctx, peer, 1);
3666  }
3667 
3668  return free_peer;
3669 }
3670 
3672  session_t *session, int err)
3673 {
3674  int level;
3675  int desc;
3676 
3677  if (err < -(1 << 8) && err > -(3 << 8)) {
3678  level = ((-err) & 0xff00) >> 8;
3679  desc = (-err) & 0xff;
3680  if (!peer) {
3681  peer = dtls_get_peer(ctx, session);
3682  }
3683  if (peer) {
3684  peer->state = DTLS_STATE_CLOSING;
3685  return dtls_send_alert(ctx, peer, level, desc);
3686  }
3687  } else if (err == -1) {
3688  if (!peer) {
3689  peer = dtls_get_peer(ctx, session);
3690  }
3691  if (peer) {
3692  peer->state = DTLS_STATE_CLOSING;
3694  }
3695  }
3696  return -1;
3697 }
3698 
3702 int
3704  session_t *session,
3705  uint8 *msg, int msglen) {
3706  dtls_peer_t *peer = NULL;
3707  unsigned int rlen; /* record length */
3708  uint8 *data; /* (decrypted) payload */
3709  int data_length; /* length of decrypted payload
3710  (without MAC and padding) */
3711  int err;
3712 
3713  /* check if we have DTLS state for addr/port/ifindex */
3714  peer = dtls_get_peer(ctx, session);
3715 
3716  if (!peer) {
3717  dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
3718  dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
3719  } else {
3720  dtls_debug("dtls_handle_message: FOUND PEER\n");
3721  }
3722 
3723  while ((rlen = is_record(msg,msglen))) {
3724  dtls_peer_type role;
3725  dtls_state_t state;
3726 
3727  dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
3728  if (peer) {
3730 
3732  if (!security) {
3733  dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
3734  data_length = -1;
3735  } else {
3736  uint64_t pkt_seq_nr = dtls_uint48_to_int(header->sequence_number);
3737  if(pkt_seq_nr == 0 && security->cseq.cseq == 0) {
3738  data_length = decrypt_verify(peer, msg, rlen, &data);
3739  if (data_length) {
3740  security->cseq.cseq = 0;
3741  security->cseq.bitfield = -1;
3742  }
3743  } else if (pkt_seq_nr == security->cseq.cseq) {
3744  dtls_info("Duplicate packet arrived (cseq=%" PRIu64 ")\n", security->cseq.cseq);
3745  return 0;
3746  } else if ((int64_t)(security->cseq.cseq-pkt_seq_nr) > 0) { /* pkt_seq_nr < security->cseq.cseq */
3747  if (((security->cseq.cseq-1)-pkt_seq_nr) < 64) {
3748  if(security->cseq.bitfield & (1<<((security->cseq.cseq-1)-pkt_seq_nr))) {
3749  dtls_info("Duplicate packet arrived (bitfield)\n");
3750  /* seen it */
3751  return 0;
3752  } else {
3753  dtls_info("Packet arrived out of order\n");
3754  data_length = decrypt_verify(peer, msg, rlen, &data);
3755  if(data_length > 0) {
3756  security->cseq.bitfield |= (1<<((security->cseq.cseq-1)-pkt_seq_nr));
3757  }
3758  }
3759  } else {
3760  dtls_info("Packet from before the bitfield arrived\n");
3761  return 0;
3762  }
3763  } else { /* pkt_seq_nr > security->cseq.cseq */
3764  data_length = decrypt_verify(peer, msg, rlen, &data);
3765  if(data_length > 0) {
3766  security->cseq.bitfield <<= (pkt_seq_nr-security->cseq.cseq);
3767  security->cseq.bitfield |= 1<<((pkt_seq_nr-security->cseq.cseq)-1);
3768  security->cseq.cseq = pkt_seq_nr;
3769  dtls_debug("new packet arrived with seq_nr: %" PRIu64 "\n", pkt_seq_nr);
3770  dtls_debug("new bitfield is : %" PRIx64 "\n", security->cseq.bitfield);
3771  }
3772  }
3773  }
3774  if (data_length < 0) {
3775  if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
3776  data = msg + DTLS_RH_LENGTH;
3777  data_length = rlen - DTLS_RH_LENGTH;
3779  role = DTLS_SERVER;
3780  } else {
3782  dtls_info("decrypt_verify() failed\n");
3783  if (peer->state < DTLS_STATE_CONNECTED) {
3784  dtls_alert_send_from_err(ctx, peer, &peer->session, err);
3785  peer->state = DTLS_STATE_CLOSED;
3786  dtls_stop_retransmission(ctx, peer);
3787  dtls_destroy_peer(ctx, peer, 1);
3788  }
3789  return err;
3790  }
3791  } else {
3792  role = peer->role;
3793  state = peer->state;
3794  }
3795  } else {
3796  /* is_record() ensures that msg contains at least a record header */
3797  data = msg + DTLS_RH_LENGTH;
3798  data_length = rlen - DTLS_RH_LENGTH;
3800  role = DTLS_SERVER;
3801  }
3802 
3803  dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
3804  dtls_debug_hexdump("receive unencrypted", data, data_length);
3805 
3806  /* Handle received record according to the first byte of the
3807  * message, i.e. the subprotocol. We currently do not support
3808  * combining multiple fragments of one type into a single
3809  * record. */
3810 
3811  switch (msg[0]) {
3812 
3814  if (peer) {
3815  dtls_stop_retransmission(ctx, peer);
3816  }
3817  err = handle_ccs(ctx, peer, msg, data, data_length);
3818  if (err < 0) {
3819  dtls_warn("error while handling ChangeCipherSpec message\n");
3820  dtls_alert_send_from_err(ctx, peer, session, err);
3821 
3822  /* invalidate peer */
3823  dtls_destroy_peer(ctx, peer, 1);
3824  peer = NULL;
3825 
3826  return err;
3827  }
3828  break;
3829 
3830  case DTLS_CT_ALERT:
3831  if (peer) {
3832  dtls_stop_retransmission(ctx, peer);
3833  }
3834  err = handle_alert(ctx, peer, msg, data, data_length);
3835  if (err < 0 || err == 1) {
3836  dtls_warn("received alert, peer has been invalidated\n");
3837  /* handle alert has invalidated peer */
3838  peer = NULL;
3839  return err < 0 ?err:-1;
3840  }
3841  break;
3842 
3843  case DTLS_CT_HANDSHAKE:
3844  /* Handshake messages other than Finish must use the current
3845  * epoch, Finish has epoch + 1. */
3846 
3847  if (peer) {
3848  uint16_t expected_epoch = dtls_security_params(peer)->epoch;
3849  uint16_t msg_epoch =
3851 
3852  /* The new security parameters must be used for all messages
3853  * that are sent after the ChangeCipherSpec message. This
3854  * means that the client's Finished message uses epoch + 1
3855  * while the server is still in the old epoch.
3856  */
3857  if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
3858  expected_epoch++;
3859  }
3860 
3861  if (expected_epoch != msg_epoch) {
3862  if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
3864  role = DTLS_SERVER;
3865  } else {
3866  dtls_warn("Wrong epoch, expected %i, got: %i\n",
3867  expected_epoch, msg_epoch);
3868  break;
3869  }
3870  }
3871  }
3872 
3873  err = handle_handshake(ctx, peer, session, role, state, data, data_length);
3874  if (err < 0) {
3875  dtls_warn("error while handling handshake packet\n");
3876  dtls_alert_send_from_err(ctx, peer, session, err);
3877  return err;
3878  }
3879  if (peer && peer->state == DTLS_STATE_CONNECTED) {
3880  /* stop retransmissions */
3881  dtls_stop_retransmission(ctx, peer);
3882  CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
3883  }
3884  break;
3885 
3887  dtls_info("** application data:\n");
3888  if (!peer) {
3889  dtls_warn("no peer available, send an alert\n");
3890  // TODO: should we send a alert here?
3891  return -1;
3892  }
3893  dtls_stop_retransmission(ctx, peer);
3894  CALL(ctx, read, &peer->session, data, data_length);
3895  break;
3896  default:
3897  dtls_info("dropped unknown message of type %d\n",msg[0]);
3898  }
3899 
3900  /* advance msg by length of ciphertext */
3901  msg += rlen;
3902  msglen -= rlen;
3903  }
3904 
3905  return 0;
3906 }
3907 
3909 dtls_new_context(void *app_data) {
3910  dtls_context_t *c;
3911  dtls_tick_t now;
3912 #ifndef WITH_CONTIKI
3913  FILE *urandom = fopen("/dev/urandom", "r");
3914  unsigned char buf[sizeof(unsigned long)];
3915 #endif /* WITH_CONTIKI */
3916 
3917  dtls_ticks(&now);
3918 #ifdef WITH_CONTIKI
3919  /* FIXME: need something better to init PRNG here */
3920  dtls_prng_init(now);
3921 #else /* WITH_CONTIKI */
3922  if (!urandom) {
3923  dtls_emerg("cannot initialize PRNG\n");
3924  return NULL;
3925  }
3926 
3927  if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
3928  dtls_emerg("cannot initialize PRNG\n");
3929  return NULL;
3930  }
3931 
3932  fclose(urandom);
3933  dtls_prng_init((unsigned long)*buf);
3934 #endif /* WITH_CONTIKI */
3935 
3936  c = malloc_context();
3937  if (!c)
3938  goto error;
3939 
3940  memset(c, 0, sizeof(dtls_context_t));
3941  c->app = app_data;
3942 
3943 #ifdef WITH_CONTIKI
3944  process_start(&dtls_retransmit_process, (char *)c);
3945  PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
3946  /* the retransmit timer must be initialized to some large value */
3947  etimer_set(&c->retransmit_timer, 0xFFFF);
3948  PROCESS_CONTEXT_END(&coap_retransmit_process);
3949 #endif /* WITH_CONTIKI */
3950 
3952  c->cookie_secret_age = now;
3953  else
3954  goto error;
3955 
3956  return c;
3957 
3958  error:
3959  dtls_alert("cannot create DTLS context\n");
3960  if (c)
3961  dtls_free_context(c);
3962  return NULL;
3963 }
3964 
3966 {
3967  dtls_stop_retransmission(ctx, peer);
3968  dtls_destroy_peer(ctx, peer, 1);
3969 }
3970 
3971 void
3973  dtls_peer_t *p, *tmp;
3974 
3975  if (!ctx) {
3976  return;
3977  }
3978 
3979  if (ctx->peers) {
3980 #ifdef DTLS_PEERS_NOHASH
3981  LL_FOREACH_SAFE(ctx->peers, p, tmp) {
3982 #else /* DTLS_PEERS_NOHASH */
3983  HASH_ITER(hh, ctx->peers, p, tmp) {
3984 #endif /* DTLS_PEERS_NOHASH */
3985  dtls_destroy_peer(ctx, p, 1);
3986  }
3987  }
3988 
3989  free_context(ctx);
3990 }
3991 
3992 int
3994  int res;
3995 
3996  assert(peer);
3997  if (!peer)
3998  return -1;
3999 
4000  /* check if the same peer is already in our list */
4001  if (peer == dtls_get_peer(ctx, &peer->session)) {
4002  dtls_debug("found peer, try to re-connect\n");
4003  return dtls_renegotiate(ctx, &peer->session);
4004  }
4005 
4006  /* set local peer role to client, remote is server */
4007  peer->role = DTLS_CLIENT;
4008 
4009  if (dtls_add_peer(ctx, peer) < 0) {
4010  dtls_alert("cannot add peer\n");
4011  return -1;
4012  }
4013 
4014  /* send ClientHello with empty Cookie */
4016  if (!peer->handshake_params)
4017  return -1;
4018 
4019  peer->handshake_params->hs_state.mseq_r = 0;
4020  peer->handshake_params->hs_state.mseq_s = 0;
4021  res = dtls_send_client_hello(ctx, peer, NULL, 0);
4022  if (res < 0)
4023  dtls_warn("cannot send ClientHello\n");
4024  else
4025  peer->state = DTLS_STATE_CLIENTHELLO;
4026 
4027  return res;
4028 }
4029 
4030 int
4032  dtls_peer_t *peer;
4033  int res;
4034 
4035  peer = dtls_get_peer(ctx, dst);
4036 
4037  if (!peer)
4038  peer = dtls_new_peer(dst);
4039 
4040  if (!peer) {
4041  dtls_crit("cannot create new peer\n");
4042  return -1;
4043  }
4044 
4045  res = dtls_connect_peer(ctx, peer);
4046 
4047  /* Invoke event callback to indicate connection attempt or
4048  * re-negotiation. */
4049  if (res > 0) {
4050  CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
4051  } else if (res == 0) {
4052  CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
4053  }
4054 
4055  return res;
4056 }
4057 
4058 static void
4060  if (!context || !node)
4061  return;
4062 
4063  /* re-initialize timeout when maximum number of retransmissions are not reached yet */
4065  unsigned char sendbuf[DTLS_MAX_BUF];
4066  size_t len = sizeof(sendbuf);
4067  int err;
4068  unsigned char *data = node->data;
4069  size_t length = node->length;
4070  dtls_tick_t now;
4072 
4073  dtls_ticks(&now);
4074  node->retransmit_cnt++;
4075  node->t = now + (node->timeout << node->retransmit_cnt);
4076  netq_insert_node(&context->sendqueue, node);
4077 
4078  if (node->type == DTLS_CT_HANDSHAKE) {
4080 
4081  dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
4082  dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4083  } else {
4084  dtls_debug("** retransmit packet\n");
4085  }
4086 
4087  err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
4088  1, sendbuf, &len);
4089  if (err < 0) {
4090  dtls_warn("can not retransmit packet, err: %i\n", err);
4091  return;
4092  }
4093  dtls_debug_hexdump("retransmit header", sendbuf,
4094  sizeof(dtls_record_header_t));
4095  dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
4096 
4097  (void)CALL(context, write, &node->peer->session, sendbuf, len);
4098  return;
4099  }
4100 
4101  /* no more retransmissions, remove node from system */
4102 
4103  dtls_debug("** removed transaction\n");
4104 
4105  /* And finally delete the node */
4106  netq_node_free(node);
4107 }
4108 
4109 static void
4111  netq_t *node;
4112  node = netq_head(&context->sendqueue);
4113 
4114  while (node) {
4115  if (dtls_session_equals(&node->peer->session, &peer->session)) {
4116  netq_t *tmp = node;
4117  node = netq_next(node);
4118  netq_remove(&context->sendqueue, tmp);
4119  netq_node_free(tmp);
4120  } else
4121  node = netq_next(node);
4122  }
4123 }
4124 
4125 void
4127  dtls_tick_t now;
4128  netq_t *node = netq_head(&context->sendqueue);
4129 
4130  dtls_ticks(&now);
4131  while (node && node->t <= now) {
4132  netq_pop_first(&context->sendqueue);
4133  dtls_retransmit(context, node);
4134  node = netq_head(&context->sendqueue);
4135  }
4136 
4137  if (next) {
4138  *next = node ? node->t : 0;
4139  }
4140 }
4141 
4142 #ifdef WITH_CONTIKI
4143 /*---------------------------------------------------------------------------*/
4144 /* message retransmission */
4145 /*---------------------------------------------------------------------------*/
4146 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4147 {
4148  clock_time_t now;
4149  netq_t *node;
4150 
4151  PROCESS_BEGIN();
4152 
4153  dtls_debug("Started DTLS retransmit process\r\n");
4154 
4155  while(1) {
4156  PROCESS_YIELD();
4157  if (ev == PROCESS_EVENT_TIMER) {
4158  if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4159 
4160  node = netq_head(&the_dtls_context.sendqueue);
4161 
4162  now = clock_time();
4163  if (node && node->t <= now) {
4164  netq_pop_first(&the_dtls_context.sendqueue);
4165  dtls_retransmit(&the_dtls_context, node);
4166  node = netq_head(&the_dtls_context.sendqueue);
4167  }
4168 
4169  /* need to set timer to some value even if no nextpdu is available */
4170  if (node) {
4171  etimer_set(&the_dtls_context.retransmit_timer,
4172  node->t <= now ? 1 : node->t - now);
4173  } else {
4174  etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4175  }
4176  }
4177  }
4178  }
4179 
4180  PROCESS_END();
4181 }
4182 #endif /* WITH_CONTIKI */
int netq_insert_node(netq_t **queue, netq_t *node)
Definition: netq.c:66
#define CALL(Context, which,...)
Definition: dtls.c:205
#define DTLS_SH_LENGTH
Definition: dtls.c:107
unsigned char identity[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN]
Definition: crypto.h:86
static void copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash)
Definition: dtls.c:1157
static int is_psk_supported(dtls_context_t *ctx)
Definition: dtls.c:508
unsigned char retransmit_cnt
Definition: netq.h:56
struct netq_t * sendqueue
Definition: dtls.h:224
int dtls_connect(dtls_context_t *ctx, const session_t *dst)
Definition: dtls.c:4031
netq_t * netq_pop_first(netq_t **queue)
Definition: netq.c:109
void dtls_handshake_free(dtls_handshake_parameters_t *handshake)
Definition: crypto.c:136
static int check_server_hello(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2560
int dtls_session_equals(const session_t *a, const session_t *b)
Definition: session.c:70
int dtls_handle_message(dtls_context_t *ctx, session_t *session, uint8 *msg, int msglen)
Definition: dtls.c:3703
#define DTLS_HT_SERVER_HELLO
Definition: dtls.h:333
unsigned char cookie_secret[DTLS_COOKIE_SECRET_LENGTH]
Definition: dtls.h:216
static void clear_hs_hash(dtls_peer_t *peer)
Definition: dtls.c:1168
dtls_hs_state_t hs_state
Definition: crypto.h:124
public tinydtls API
#define R_KEY_OFFSET
#define DTLS_CT_HANDSHAKE
Definition: dtls.h:316
static int dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length, unsigned char **result_r, unsigned char **result_s)
Definition: dtls.c:1692
static int dtls_update_parameters(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:980
int(* get_ecdsa_key)(struct dtls_context_t *ctx, const session_t *session, const dtls_ecdsa_key_t **result)
Definition: dtls.h:174
#define dtls_kb_remote_iv(Param, Role)
Definition: crypto.h:171
static int check_server_hellodone(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2901
#define dtls_kb_local_iv(Param, Role)
Definition: crypto.h:175
void dtls_hmac_update(dtls_hmac_context_t *ctx, const unsigned char *input, size_t ilen)
Definition: hmac.c:70
int dtls_ecdh_pre_master_secret(unsigned char *priv_key, unsigned char *pub_key_x, unsigned char *pub_key_y, size_t key_size, unsigned char *result, size_t result_len)
Definition: crypto.c:391
static int dtls_alert_fatal_create(dtls_alert_t desc)
Definition: alert.h:69
static int dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type, uint8 *buf, size_t buflen)
Definition: dtls.c:231
const unsigned char * priv_key
Definition: dtls.h:55
int dtls_psk_pre_master_secret(unsigned char *key, size_t keylen, unsigned char *result, size_t result_len)
Definition: crypto.c:311
#define dtls_kb_server_mac_secret(Param, Role)
Definition: crypto.h:143
static int hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen, dtls_peer_t *peer)
Definition: dtls.c:575
int dtls_encrypt(const unsigned char *src, size_t length, unsigned char *buf, unsigned char *nounce, unsigned char *key, size_t keylen, const unsigned char *aad, size_t la)
Definition: crypto.c:517
static int dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer, const unsigned char *label, size_t labellen)
Definition: dtls.c:2377
static dtls_context_t * malloc_context(void)
Definition: dtls.c:182
dtls_cipher_t cipher
Definition: crypto.h:127
#define TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED
Definition: global.h:88
#define TLS_EXT_SERVER_CERTIFICATE_TYPE
Definition: global.h:81
dtls_state_t
Definition: state.h:32
#define DTLS_COOKIE_LENGTH
Definition: dtls.h:312
#define DTLS_CT_APPLICATION_DATA
Definition: dtls.h:317
#define DTLS_FIN_LENGTH
Definition: dtls.c:115
static uint8 * dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
Definition: dtls.c:1948
static int check_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2822
#define HASH_ITER(hh, head, el, tmp)
Definition: uthash.h:1133
netq_t * netq_next(netq_t *p)
Definition: netq.c:94
#define DTLS_HT_FINISHED
Definition: dtls.h:341
static void check_stack(void)
Definition: dtls_debug.h:51
struct dtls_handshake_parameters_t::@0::random_t random
#define DTLS_VERSION
Definition: dtls.h:46
static const unsigned char prf_label_client[]
Definition: dtls.c:147
dtls_peer_t * dtls_get_peer(const dtls_context_t *ctx, const session_t *session)
Definition: dtls.c:243
static int dtls_int_to_uint48(unsigned char *field, uint64_t value)
Definition: numeric.h:62
#define DTLS_SKEXECPSK_LENGTH_MAX
Definition: dtls.c:111
#define dtls_kb_size(Param, Role)
Definition: crypto.h:181
#define DTLS_HT_SERVER_KEY_EXCHANGE
Definition: dtls.h:336
static int dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer, const unsigned char *psk_hint, size_t len)
Definition: dtls.c:2070
void dtls_clock_init(void)
Definition: dtls_time.c:44
void dtls_ecdsa_create_sig_hash(const unsigned char *priv_key, size_t key_size, const unsigned char *sign_hash, size_t sign_hash_size, uint32_t point_r[9], uint32_t point_s[9])
Definition: crypto.c:439
clock_time_t dtls_tick_t
Definition: dtls_time.h:49
socklen_t size
Definition: session.h:41
#define DEL_PEER(head, delptr)
Definition: dtls.c:95
unsigned char data[]
Definition: netq.h:60
static int verify_ext_ec_point_formats(uint8 *data, size_t data_length)
Definition: dtls.c:829
Definition: netq.h:47
static int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
Definition: dtls.c:518
#define dtls_get_fragment_length(H)
Definition: dtls.c:70
static int dtls_int_to_uint24(unsigned char *field, uint32_t value)
Definition: numeric.h:45
static int dtls_send_handshake_msg_hash(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session, uint8 header_type, uint8 *data, size_t data_length, int add_hash)
Definition: dtls.c:1405
int(* get_psk_info)(struct dtls_context_t *ctx, const session_t *session, dtls_credentials_type_t type, const unsigned char *desc, size_t desc_len, unsigned char *result, size_t result_length)
Definition: dtls.h:145
dtls_record_header_t
Definition: dtls.h:327
#define dtls_debug_hexdump(name, buf, length)
Definition: dtls_debug.h:119
static int handle_alert(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *record_header, uint8 *data, size_t data_length)
Definition: dtls.c:3609
#define DTLS_CKXPSK_LENGTH_MIN
Definition: dtls.c:112
netq_t * netq_node_new(size_t size)
Definition: netq.c:119
dtls_alert_level_t
Definition: alert.h:26
static int dtls_verify_peer(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session, const dtls_state_t state, uint8 *data, size_t data_length)
Definition: dtls.c:1618
static uint8 * dtls_set_handshake_header(uint8 type, dtls_peer_t *peer, int length, int frag_offset, int frag_length, uint8 *buf)
Definition: dtls.c:450
#define TLS_EXT_ELLIPTIC_CURVES_SECP256R1
Definition: global.h:86
dtls_state_t state
Definition: peer.h:54
static void netq_init(void)
Definition: netq.h:67
static int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
Definition: dtls.c:487
dtls_sha256_ctx dtls_hash_ctx
Definition: hmac.h:31
clock_time_t cookie_secret_age
Definition: dtls.h:217
#define dtls_info(...)
Definition: dtls_debug.h:117
DTLS alert protocol.
netq_t * netq_head(netq_t **queue)
Definition: netq.c:89
#define assert(x)
Definition: hmac.c:25
#define DTLS_EVENT_CONNECT
Definition: alert.h:56
static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer)
Definition: dtls.c:4110
static dtls_security_parameters_t * dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
Definition: peer.h:60
#define DTLS_HANDSHAKE_HEADER(M)
Definition: dtls.c:124
static int dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level, dtls_alert_t description)
Definition: dtls.c:1567
#define TLS_EC_CURVE_TYPE_NAMED_CURVE
Definition: global.h:90
static int dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer, const dtls_ecdsa_key_t *key)
Definition: dtls.c:2341
static int check_client_certificate_verify(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:1772
dtls_peer_t * peers
Definition: dtls.h:219
#define dtls_kb_client_write_key(Param, Role)
Definition: crypto.h:154
void dtls_ecdsa_generate_key(unsigned char *priv_key, unsigned char *pub_key_x, unsigned char *pub_key_y, size_t key_size)
Definition: crypto.c:418
session_t session
Definition: peer.h:51
uint32_t clock_time_t
Definition: dtls_time.h:46
int dtls_ec_key_from_uint32_asn1(const uint32_t *key, size_t key_size, unsigned char *buf)
Definition: crypto.c:355
#define PRINTF(...)
Definition: dtls_debug.h:49
unsigned char uint48[6]
Definition: global.h:43
union dtls_handshake_parameters_t::@1 keyx
#define FIND_PEER(head, sess, out)
Definition: dtls.c:91
#define dtls_warn(...)
Definition: dtls_debug.h:115
int dtls_ecdsa_verify_sig(const unsigned char *pub_key_x, const unsigned char *pub_key_y, size_t key_size, const unsigned char *client_random, size_t client_random_size, const unsigned char *server_random, size_t server_random_size, const unsigned char *keyx_params, size_t keyx_params_size, unsigned char *result_r, unsigned char *result_s)
Definition: crypto.c:496
#define TLS_EXT_SIG_HASH_ALGO_SHA256
Definition: global.h:94
unsigned int do_client_auth
Definition: crypto.h:128
union dtls_handshake_parameters_t::@0 tmp
#define dtls_kb_iv_size(Param, Role)
Definition: crypto.h:179
static int known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client)
Definition: dtls.c:552
#define DTLS_HMAC_DIGEST_SIZE
Definition: hmac.h:62
static int dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer, const dtls_ecdsa_key_t *key)
Definition: dtls.c:2005
static uint8_t dtls_uint8_to_int(const unsigned char *field)
Definition: numeric.h:86
#define dtls_crit(...)
Definition: dtls_debug.h:114
#define TLS_EXT_SIG_HASH_ALGO_ECDSA
Definition: global.h:95
dtls_handler_t * h
Definition: dtls.h:228
unsigned char uint24[3]
Definition: global.h:41
#define dtls_kb_remote_write_key(Param, Role)
Definition: crypto.h:158
static void dtls_security_params_free_other(dtls_peer_t *peer)
Definition: peer.h:89
#define TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
Definition: global.h:92
static int dtls_alert_create(dtls_alert_level_t level, dtls_alert_t desc)
Definition: alert.h:63
static int dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2142
#define DTLS_HT_SERVER_HELLO_DONE
Definition: dtls.h:338
static int dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:1817
#define DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
Definition: crypto.h:79
#define TLS_EXT_ELLIPTIC_CURVES
Definition: global.h:77
#define DTLS_CH_LENGTH_MAX
Definition: dtls.c:105
Clock Handling.
dtls_hash_ctx hs_hash
Definition: state.h:54
#define DTLS_SKEXECPSK_LENGTH_MIN
Definition: dtls.c:110
#define DTLS_COOKIE_LENGTH_MAX
Definition: dtls.c:104
#define dtls_debug(...)
Definition: dtls_debug.h:118
clock_time_t t
Definition: netq.h:50
static int check_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2782
#define DTLS_HV_LENGTH
Definition: dtls.c:106
#define DTLS_CT_ALERT
Definition: dtls.h:315
#define MAX_KEYBLOCK_LENGTH
Definition: crypto.h:45
#define min(a, b)
Definition: dtls_debug.c:39
static const unsigned char prf_label_finished[]
Definition: dtls.c:149
dtls_handshake_header_t
Definition: dtls.h:351
static int dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2245
int(* verify_ecdsa_key)(struct dtls_context_t *ctx, const session_t *session, const unsigned char *other_pub_x, const unsigned char *other_pub_y, size_t key_size)
Definition: dtls.h:204
#define TLS_EXT_ENCRYPT_THEN_MAC
Definition: global.h:82
static int dtls_check_tls_extension(dtls_peer_t *peer, uint8 *data, size_t data_length, int client_hello)
Definition: dtls.c:857
dtls_handshake_parameters_psk_t psk
Definition: crypto.h:134
static int check_server_key_exchange_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2699
#define CLOCK_SECOND
Definition: dtls_time.h:43
struct netq_t * reorder_queue
Definition: crypto.h:123
#define DTLS_RANDOM_LENGTH
Definition: crypto.h:50
void dtls_hmac_init(dtls_hmac_context_t *ctx, const unsigned char *key, size_t klen)
Definition: hmac.c:88
#define TLS_EXT_EC_POINT_FORMATS
Definition: global.h:78
static int dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:3045
dtls_handshake_parameters_t * handshake_params
Definition: peer.h:57
static void dtls_hash_init(dtls_hash_t ctx)
Definition: hmac.h:36
#define dtls_debug_dump(name, buf, length)
Definition: dtls_debug.h:120
const unsigned char * pub_key_y
Definition: dtls.h:57
#define dtls_kb_mac_secret_size(Param, Role)
Definition: crypto.h:153
dtls_peer_t * peer
Definition: netq.h:53
static int check_client_keyexchange(dtls_context_t *ctx, dtls_handshake_parameters_t *handshake, uint8 *data, size_t length)
Definition: dtls.c:1086
int dtls_close(dtls_context_t *ctx, const session_t *remote)
Definition: dtls.c:1576
uint16_t epoch
Definition: netq.h:54
static int check_finished(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:1185
static int verify_ext_eliptic_curves(uint8 *data, size_t data_length)
Definition: dtls.c:781
#define SKIP_VAR_FIELD(P, L, T)
Definition: dtls.c:134
#define DTLS_CE_LENGTH
Definition: dtls.c:108
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)
Definition: dtls.c:660
#define DTLS_DEFAULT_MAX_RETRANSMIT
Definition: global.h:62
#define PRF_LABEL_SIZE(Label)
Definition: dtls.c:143
static int handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session, const dtls_peer_type role, const dtls_state_t state, uint8 *data, size_t data_length)
Definition: dtls.c:3459
#define DTLS_HT_CLIENT_HELLO
Definition: dtls.h:332
unsigned char uint8
Definition: global.h:39
dtls_compression_t compression
Definition: crypto.h:126
static uint8 * dtls_set_record_header(uint8 type, dtls_security_parameters_t *security, uint8 *buf)
Definition: dtls.c:416
static void dtls_retransmit(dtls_context_t *context, netq_t *node)
Definition: dtls.c:4059
void peer_init(void)
Definition: peer.c:23
static const unsigned char prf_label_key[]
Definition: dtls.c:146
void dtls_dsrv_log_addr(log_t level, const char *name, const session_t *addr)
Definition: dtls_debug.c:278
int dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:3993
static int dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2154
#define DTLS_HT_CERTIFICATE_VERIFY
Definition: dtls.h:339
#define DTLS_EC_KEY_SIZE
Definition: crypto.h:308
static int dtls_int_to_uint16(unsigned char *field, uint16_t value)
Definition: numeric.h:38
static void dtls_hash_update(dtls_hash_t ctx, const unsigned char *input, size_t len)
Definition: hmac.h:41
union session_t::@2 addr
#define DTLS_HASH_CTX_SIZE
Definition: hmac.h:33
High level DTLS API and visible structures.
uint64_t cseq
Definition: crypto.h:90
dtls_alert_t
Definition: alert.h:31
#define DTLS_HT_CERTIFICATE_REQUEST
Definition: dtls.h:337
#define mycookie
#define DTLS_RH_LENGTH
Definition: dtls.c:101
int dtls_hmac_finalize(dtls_hmac_context_t *ctx, unsigned char *result)
Definition: hmac.c:121
const unsigned char * pub_key_x
Definition: dtls.h:56
static uint16_t dtls_uint16_to_int(const unsigned char *field)
Definition: numeric.h:91
static const unsigned char prf_label_master[]
Definition: dtls.c:145
#define dtls_get_epoch(H)
Definition: dtls.c:68
static dtls_security_parameters_t * dtls_security_params(dtls_peer_t *peer)
Definition: peer.h:71
void dtls_ecdsa_create_sig(const unsigned char *priv_key, size_t key_size, const unsigned char *client_random, size_t client_random_size, const unsigned char *server_random, size_t server_random_size, const unsigned char *keyx_params, size_t keyx_params_size, uint32_t point_r[9], uint32_t point_s[9])
Definition: crypto.c:456
unsigned int timeout
Definition: netq.h:51
unsigned int uint32_t
Definition: uthash.h:78
#define dtls_kb_server_write_key(Param, Role)
Definition: crypto.h:156
int dtls_ecdsa_verify_sig_hash(const unsigned char *pub_key_x, const unsigned char *pub_key_y, size_t key_size, const unsigned char *sign_hash, size_t sign_hash_size, unsigned char *result_r, unsigned char *result_s)
Definition: crypto.c:476
uint16_t mseq_r
Definition: state.h:48
uint8_t type
Definition: netq.h:55
#define dtls_kb_client_mac_secret(Param, Role)
Definition: crypto.h:142
static const unsigned char prf_label_server[]
Definition: dtls.c:148
int dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
Definition: dtls.c:3053
#define dtls_alert(...)
Definition: dtls_debug.h:113
dtls_compression_t compression
Definition: crypto.h:95
dtls_cipher_t cipher
Definition: crypto.h:97
#define DTLS_MASTER_SECRET_LENGTH
Definition: crypto.h:49
void dtls_free_peer(dtls_peer_t *peer)
Definition: peer.c:33
uint8 key_block[MAX_KEYBLOCK_LENGTH]
Definition: crypto.h:107
static void dtls_security_params_switch(dtls_peer_t *peer)
Definition: peer.h:101
void dtls_free_context(dtls_context_t *ctx)
Definition: dtls.c:3972
dtls_peer_type
Definition: peer.h:39
#define DTLS_HMAC_MAX
Definition: hmac.h:63
static int dtls_int_to_uint32(unsigned char *field, uint32_t value)
Definition: numeric.h:53
static void update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length)
Definition: dtls.c:1151
#define DTLS_CKXEC_LENGTH
Definition: dtls.c:113
static const unsigned char cert_asn1_header[]
Definition: dtls.c:153
dtls_context_t * dtls_new_context(void *app_data)
Definition: dtls.c:3909
void dtls_hmac_storage_init(void)
Definition: hmac.c:46
void dtls_init(void)
Definition: dtls.c:193
#define LL_FOREACH_SAFE(head, el, tmp)
Definition: utlist.h:419
uint8 master_secret[DTLS_MASTER_SECRET_LENGTH]
Definition: crypto.h:121
#define A_DATA_LEN
static unsigned int is_record(uint8 *msg, size_t msglen)
Definition: dtls.c:387
#define DTLS_CV_LENGTH
Definition: dtls.c:114
#define DTLS_EVENT_CONNECTED
Definition: alert.h:57
void netq_remove(netq_t **queue, netq_t *p)
Definition: netq.c:102
static int dtls_send_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, uint8 header_type, uint8 *data, size_t data_length)
Definition: dtls.c:1443
#define PRF_LABEL(Label)
Definition: dtls.c:142
static int dtls_create_cookie(dtls_context_t *ctx, session_t *session, uint8 *msg, size_t msglen, uint8 *cookie, int *clen)
Definition: dtls.c:311
#define DTLS_RECORD_HEADER(M)
Definition: dtls.c:123
#define DTLS_HT_HELLO_REQUEST
Definition: dtls.h:331
dtls_cipher_t
Definition: global.h:66
#define DTLS_HT_HELLO_VERIFY_REQUEST
Definition: dtls.h:334
static void dtls_prng_init(unsigned short seed)
Definition: prng.h:49
static int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
Definition: dtls.c:532
#define DTLS_PSK_MAX_KEY_LEN
Definition: crypto.h:82
#define DTLS_CCM_BLOCKSIZE
Definition: ccm.h:25
static int check_server_hello_verify_request(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2630
dtls_handshake_parameters_ecdsa_t ecdsa
Definition: crypto.h:131
static int check_server_certificate(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2652
static int dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer, const dtls_ecdsa_key_t *key)
Definition: dtls.c:1917
static int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
Definition: dtls.c:498
void dtls_reset_peer(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:3965
#define dtls_kb_client_iv(Param, Role)
Definition: crypto.h:167
static uint64_t dtls_uint48_to_int(const unsigned char *field)
Definition: numeric.h:112
#define DTLS_EC_SUBJECTPUBLICKEY_SIZE
Definition: dtls.c:1914
static int dtls_prng(unsigned char *buf, size_t len)
Definition: prng.h:42
void netq_node_free(netq_t *node)
Definition: netq.c:135
#define DTLS_MAX_BUF
Definition: global.h:56
static int equals(unsigned char *a, unsigned char *b, size_t len)
Definition: global.h:119
#define dtls_kb_key_size(Param, Role)
Definition: crypto.h:166
static size_t dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx)
Definition: hmac.h:46
size_t length
Definition: netq.h:58
static int verify_ext_cert_type(uint8 *data, size_t data_length)
Definition: dtls.c:805
#define DTLS_SKEXEC_LENGTH
Definition: dtls.c:109
static dtls_security_parameters_t * dtls_security_params_next(dtls_peer_t *peer)
Definition: peer.h:76
static int dtls_int_to_uint8(unsigned char *field, uint8_t value)
Definition: numeric.h:32
unsigned char uint8_t
Definition: uthash.h:79
unsigned char uint32[4]
Definition: global.h:42
Pseudo Random Numbers.
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)
Definition: dtls.c:1489
static int dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer, uint8 cookie[], size_t cookie_length)
Definition: dtls.c:2408
dtls_client_hello_t
Definition: dtls.h:362
static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
Definition: dtls.c:1590
static int dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2100
#define S_KEY_OFFSET(len_s)
static void dtls_debug_keyblock(dtls_security_parameters_t *config)
Definition: dtls.c:594
#define dtls_emerg(...)
Definition: dtls_debug.h:112
dtls_peer_t * dtls_new_peer(const session_t *session)
Definition: peer.c:64
void * app
Definition: dtls.h:226
#define DTLS_EVENT_RENEGOTIATE
Definition: alert.h:60
#define DTLS_HT_CERTIFICATE
Definition: dtls.h:335
dtls_hello_verify_t
Definition: dtls.h:369
int dtls_write(struct dtls_context_t *ctx, session_t *dst, uint8 *buf, size_t len)
Definition: dtls.c:261
#define ADD_PEER(head, sess, add)
Definition: dtls.c:93
#define TLS_CERT_TYPE_RAW_PUBLIC_KEY
Definition: global.h:84
#define DTLS_CH_LENGTH
Definition: dtls.c:103
static int dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie)
Definition: dtls.c:286
static int dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security, unsigned char type, uint8 *data_array[], size_t data_len_array[], size_t data_array_len, uint8 *sendbuf, size_t *rlen)
Definition: dtls.c:1262
#define DTLS_HT_CLIENT_KEY_EXCHANGE
Definition: dtls.h:340
void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next)
Definition: dtls.c:4126
static int handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session, const dtls_peer_type role, const dtls_state_t state, uint8 *data, size_t data_length)
Definition: dtls.c:3089
#define DTLS_COOKIE_SECRET_LENGTH
Definition: dtls.h:61
#define dtls_kb_server_iv(Param, Role)
Definition: crypto.h:169
#define DTLS_HS_LENGTH
Definition: dtls.c:102
#define LOW(V)
Definition: dtls.c:121
uint64_t bitfield
Definition: crypto.h:91
static size_t finalize_hs_hash(dtls_peer_t *peer, uint8 *buf)
Definition: dtls.c:1163
static int dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:255
#define dtls_kb_local_write_key(Param, Role)
Definition: crypto.h:162
#define HIGH(V)
Definition: dtls.c:120
static char * dtls_handshake_type_to_name(int type)
Definition: dtls.c:626
dtls_handshake_parameters_t * dtls_handshake_new(void)
Definition: crypto.c:113
unsigned char uint16[2]
Definition: global.h:40
size_t dtls_prf(const unsigned char *key, size_t keylen, const unsigned char *label, size_t labellen, const unsigned char *random1, size_t random1len, const unsigned char *random2, size_t random2len, unsigned char *buf, size_t buflen)
Definition: crypto.c:240
#define DTLS_CT_CHANGE_CIPHER_SPEC
Definition: dtls.h:314
static uint32_t dtls_uint24_to_int(const unsigned char *field)
Definition: numeric.h:97
void crypto_init(void)
Definition: crypto.c:66
void dtls_ticks(dtls_tick_t *t)
Definition: dtls_time.c:57
static void free_context(dtls_context_t *context)
Definition: dtls.c:187
static uint8 compression_methods[]
Definition: dtls.c:482
static int dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2237
static int handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *record_header, uint8 *data, size_t data_length)
Definition: dtls.c:3569
static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session, int err)
Definition: dtls.c:3671
int dtls_decrypt(const unsigned char *src, size_t length, unsigned char *buf, unsigned char *nounce, unsigned char *key, size_t keylen, const unsigned char *aad, size_t la)
Definition: crypto.c:543
dtls_peer_type role
Definition: peer.h:53
uint16_t mseq_s
Definition: state.h:47
static int decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length, uint8 **cleartext)
Definition: dtls.c:2974
#define TLS_EXT_CLIENT_CERTIFICATE_TYPE
Definition: global.h:80