tinydtls  0.8.1
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups
dtls.c
Go to the documentation of this file.
1 /* dtls -- a very basic DTLS implementation
2  *
3  * Copyright (C) 2011--2012,2014 Olaf Bergmann <bergmann@tzi.org>
4  * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
5  *
6  * Permission is hereby granted, free of charge, to any person
7  * obtaining a copy of this software and associated documentation
8  * files (the "Software"), to deal in the Software without
9  * restriction, including without limitation the rights to use, copy,
10  * modify, merge, publish, distribute, sublicense, and/or sell copies
11  * of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24  * SOFTWARE.
25  */
26 
27 #include "tinydtls.h"
28 #include "dtls_config.h"
29 #include "dtls_time.h"
30 
31 #include <stdio.h>
32 #include <stdlib.h>
33 #ifdef HAVE_ASSERT_H
34 #include <assert.h>
35 #endif
36 #ifndef WITH_CONTIKI
37 #include <stdlib.h>
38 #include "uthash.h"
39 #endif /* WITH_CONTIKI */
40 
41 #include "debug.h"
42 #include "numeric.h"
43 #include "netq.h"
44 #include "dtls.h"
45 
46 #include "alert.h"
47 #include "session.h"
48 #include "prng.h"
49 
50 #ifdef WITH_SHA256
51 # include "sha2/sha2.h"
52 #endif
53 
54 #define dtls_set_version(H,V) dtls_int_to_uint16((H)->version, (V))
55 #define dtls_set_content_type(H,V) ((H)->content_type = (V) & 0xff)
56 #define dtls_set_length(H,V) ((H)->length = (V))
57 
58 #define dtls_get_content_type(H) ((H)->content_type & 0xff)
59 #define dtls_get_version(H) dtls_uint16_to_int((H)->version)
60 #define dtls_get_epoch(H) dtls_uint16_to_int((H)->epoch)
61 #define dtls_get_sequence_number(H) dtls_uint48_to_ulong((H)->sequence_number)
62 #define dtls_get_fragment_length(H) dtls_uint24_to_int((H)->fragment_length)
63 
64 #ifndef WITH_CONTIKI
65 #define HASH_FIND_PEER(head,sess,out) \
66  HASH_FIND(hh,head,sess,sizeof(session_t),out)
67 #define HASH_ADD_PEER(head,sess,add) \
68  HASH_ADD(hh,head,sess,sizeof(session_t),add)
69 #define HASH_DEL_PEER(head,delptr) \
70  HASH_DELETE(hh,head,delptr)
71 #endif /* WITH_CONTIKI */
72 
73 #define DTLS_RH_LENGTH sizeof(dtls_record_header_t)
74 #define DTLS_HS_LENGTH sizeof(dtls_handshake_header_t)
75 #define DTLS_CH_LENGTH sizeof(dtls_client_hello_t) /* no variable length fields! */
76 #define DTLS_COOKIE_LENGTH_MAX 32
77 #define DTLS_CH_LENGTH_MAX sizeof(dtls_client_hello_t) + DTLS_COOKIE_LENGTH_MAX + 12 + 26
78 #define DTLS_HV_LENGTH sizeof(dtls_hello_verify_t)
79 #define DTLS_SH_LENGTH (2 + DTLS_RANDOM_LENGTH + 1 + 2 + 1)
80 #define DTLS_CE_LENGTH (3 + 3 + 27 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
81 #define DTLS_SKEXEC_LENGTH (1 + 2 + 1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE + 1 + 1 + 2 + 70)
82 #define DTLS_SKEXECPSK_LENGTH_MIN 2
83 #define DTLS_SKEXECPSK_LENGTH_MAX 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
84 #define DTLS_CKXPSK_LENGTH_MIN 2
85 #define DTLS_CKXEC_LENGTH (1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
86 #define DTLS_CV_LENGTH (1 + 1 + 2 + 1 + 1 + 1 + 1 + DTLS_EC_KEY_SIZE + 1 + 1 + DTLS_EC_KEY_SIZE)
87 #define DTLS_FIN_LENGTH 12
88 
89 #define HS_HDR_LENGTH DTLS_RH_LENGTH + DTLS_HS_LENGTH
90 #define HV_HDR_LENGTH HS_HDR_LENGTH + DTLS_HV_LENGTH
91 
92 #define HIGH(V) (((V) >> 8) & 0xff)
93 #define LOW(V) ((V) & 0xff)
94 
95 #define DTLS_RECORD_HEADER(M) ((dtls_record_header_t *)(M))
96 #define DTLS_HANDSHAKE_HEADER(M) ((dtls_handshake_header_t *)(M))
97 
98 #define HANDSHAKE(M) ((dtls_handshake_header_t *)((M) + DTLS_RH_LENGTH))
99 #define CLIENTHELLO(M) ((dtls_client_hello_t *)((M) + HS_HDR_LENGTH))
100 
101 /* The length check here should work because dtls_*_to_int() works on
102  * unsigned char. Otherwise, broken messages could cause severe
103  * trouble. Note that this macro jumps out of the current program flow
104  * when the message is too short. Beware!
105  */
106 #define SKIP_VAR_FIELD(P,L,T) { \
107  if (L < dtls_ ## T ## _to_int(P) + sizeof(T)) \
108  goto error; \
109  L -= dtls_ ## T ## _to_int(P) + sizeof(T); \
110  P += dtls_ ## T ## _to_int(P) + sizeof(T); \
111  }
112 
113 /* some constants for the PRF */
114 #define PRF_LABEL(Label) prf_label_##Label
115 #define PRF_LABEL_SIZE(Label) (sizeof(PRF_LABEL(Label)) - 1)
116 
117 static const unsigned char prf_label_master[] = "master secret";
118 static const unsigned char prf_label_key[] = "key expansion";
119 static const unsigned char prf_label_client[] = "client";
120 static const unsigned char prf_label_server[] = "server";
121 static const unsigned char prf_label_finished[] = " finished";
122 
123 /* first part of Raw public key, the is the start of the Subject Public Key */
124 static const unsigned char cert_asn1_header[] = {
125  0x30, 0x59, /* SEQUENCE, length 89 bytes */
126  0x30, 0x13, /* SEQUENCE, length 19 bytes */
127  0x06, 0x07, /* OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1) */
128  0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01,
129  0x06, 0x08, /* OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7) */
130  0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07,
131  0x03, 0x42, 0x00, /* BIT STRING, length 66 bytes, 0 bits unused */
132  0x04 /* uncompressed, followed by the r und s values of the public key */
133 };
134 
135 #ifdef WITH_CONTIKI
136 PROCESS(dtls_retransmit_process, "DTLS retransmit process");
137 
138 static dtls_context_t the_dtls_context;
139 
140 static inline dtls_context_t *
141 malloc_context() {
142  return &the_dtls_context;
143 }
144 
145 static inline void
146 free_context(dtls_context_t *context) {
147 }
148 
149 #else /* WITH_CONTIKI */
150 
151 static inline dtls_context_t *
153  return (dtls_context_t *)malloc(sizeof(dtls_context_t));
154 }
155 
156 static inline void
158  free(context);
159 }
160 #endif
161 
162 void
164  dtls_clock_init();
165  crypto_init();
166  netq_init();
167  peer_init();
168 }
169 
170 /* Calls cb_alert() with given arguments if defined, otherwise an
171  * error message is logged and the result is -1. This is just an
172  * internal helper.
173  */
174 #define CALL(Context, which, ...) \
175  ((Context)->h && (Context)->h->which \
176  ? (Context)->h->which((Context), ##__VA_ARGS__) \
177  : -1)
178 
179 static int
181  dtls_security_parameters_t *security , session_t *session,
182  unsigned char type, uint8 *buf_array[],
183  size_t buf_len_array[], size_t buf_array_len);
184 
199 static int
200 dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
201  uint8 *buf, size_t buflen) {
202  return dtls_send_multi(ctx, peer, dtls_security_params(peer), &peer->session,
203  type, &buf, &buflen, 1);
204 }
205 
209 static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
210 
211 dtls_peer_t *
212 dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
213  dtls_peer_t *p = NULL;
214 
215 #ifndef WITH_CONTIKI
216  HASH_FIND_PEER(ctx->peers, session, p);
217 #else /* WITH_CONTIKI */
218  for (p = list_head(ctx->peers); p; p = list_item_next(p))
219  if (dtls_session_equals(&p->session, session))
220  return p;
221 #endif /* WITH_CONTIKI */
222 
223  return p;
224 }
225 
226 static void
228 #ifndef WITH_CONTIKI
229  HASH_ADD_PEER(ctx->peers, session, peer);
230 #else /* WITH_CONTIKI */
231  list_add(ctx->peers, peer);
232 #endif /* WITH_CONTIKI */
233 }
234 
235 int
237  session_t *dst, uint8 *buf, size_t len) {
238 
239  dtls_peer_t *peer = dtls_get_peer(ctx, dst);
240 
241  /* Check if peer connection already exists */
242  if (!peer) { /* no ==> create one */
243  int res;
244 
245  /* dtls_connect() returns a value greater than zero if a new
246  * connection attempt is made, 0 for session reuse. */
247  res = dtls_connect(ctx, dst);
248 
249  return (res >= 0) ? 0 : res;
250  } else { /* a session exists, check if it is in state connected */
251 
252  if (peer->state != DTLS_STATE_CONNECTED) {
253  return 0;
254  } else {
255  return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
256  }
257  }
258 }
259 
260 static int
261 dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie) {
262  /* To access the cookie, we have to determine the session id's
263  * length and skip the whole thing. */
264  if (msglen < DTLS_HS_LENGTH + DTLS_CH_LENGTH + sizeof(uint8))
266 
269 
270  msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
272 
273  SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
274 
275  if (msglen < (*msg & 0xff) + sizeof(uint8))
277 
278  *cookie = msg + sizeof(uint8);
279  return dtls_uint8_to_int(msg);
280 
281  error:
283 }
284 
285 static int
287  session_t *session,
288  uint8 *msg, size_t msglen,
289  uint8 *cookie, int *clen) {
290  unsigned char buf[DTLS_HMAC_MAX];
291  size_t len, e;
292 
293  /* create cookie with HMAC-SHA256 over:
294  * - SECRET
295  * - session parameters (only IP address?)
296  * - client version
297  * - random gmt and bytes
298  * - session id
299  * - cipher_suites
300  * - compression method
301  */
302 
303  /* We use our own buffer as hmac_context instead of a dynamic buffer
304  * created by dtls_hmac_new() to separate storage space for cookie
305  * creation from storage that is used in real sessions. Note that
306  * the buffer size must fit with the default hash algorithm (see
307  * implementation of dtls_hmac_context_new()). */
308 
309  dtls_hmac_context_t hmac_context;
311 
312  dtls_hmac_update(&hmac_context,
313  (unsigned char *)&session->addr, session->size);
314 
315  /* feed in the beginning of the Client Hello up to and including the
316  session id */
317  e = sizeof(dtls_client_hello_t);
318  e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
319  if (e + DTLS_HS_LENGTH > msglen)
321 
322  dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
323 
324  /* skip cookie bytes and length byte */
325  e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
326  e += sizeof(uint8);
327  if (e + DTLS_HS_LENGTH > msglen)
329 
330  dtls_hmac_update(&hmac_context,
331  msg + DTLS_HS_LENGTH + e,
333 
334  len = dtls_hmac_finalize(&hmac_context, buf);
335 
336  if (len < *clen) {
337  memset(cookie + len, 0, *clen - len);
338  *clen = len;
339  }
340 
341  memcpy(cookie, buf, *clen);
342  return 0;
343 }
344 
345 #ifdef DTLS_CHECK_CONTENTTYPE
346 /* used to check if a received datagram contains a DTLS message */
347 static char const content_types[] = {
352  0 /* end marker */
353 };
354 #endif
355 
360 static unsigned int
361 is_record(uint8 *msg, size_t msglen) {
362  unsigned int rlen = 0;
363 
364  if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
365 #ifdef DTLS_CHECK_CONTENTTYPE
366  && strchr(content_types, msg[0])
367 #endif
368  && msg[1] == HIGH(DTLS_VERSION)
369  && msg[2] == LOW(DTLS_VERSION))
370  {
371  rlen = DTLS_RH_LENGTH +
373 
374  /* we do not accept wrong length field in record header */
375  if (rlen > msglen)
376  rlen = 0;
377  }
378 
379  return rlen;
380 }
381 
389 static inline uint8 *
391  uint8 *buf) {
392 
393  dtls_int_to_uint8(buf, type);
394  buf += sizeof(uint8);
395 
397  buf += sizeof(uint16);
398 
399  if (security) {
400  dtls_int_to_uint16(buf, security->epoch);
401  buf += sizeof(uint16);
402 
403  dtls_int_to_uint48(buf, security->rseq);
404  buf += sizeof(uint48);
405 
406  /* increment record sequence counter by 1 */
407  security->rseq++;
408  } else {
409  memset(buf, 0, sizeof(uint16) + sizeof(uint48));
410  buf += sizeof(uint16) + sizeof(uint48);
411  }
412 
413  memset(buf, 0, sizeof(uint16));
414  return buf + sizeof(uint16);
415 }
416 
423 static inline uint8 *
425  int length,
426  int frag_offset, int frag_length,
427  uint8 *buf) {
428 
429  dtls_int_to_uint8(buf, type);
430  buf += sizeof(uint8);
431 
432  dtls_int_to_uint24(buf, length);
433  buf += sizeof(uint24);
434 
435  if (peer && peer->handshake_params) {
436  /* and copy the result to buf */
438 
439  /* increment handshake message sequence counter by 1 */
441  } else {
442  memset(buf, 0, sizeof(uint16));
443  }
444  buf += sizeof(uint16);
445 
446  dtls_int_to_uint24(buf, frag_offset);
447  buf += sizeof(uint24);
448 
449  dtls_int_to_uint24(buf, frag_length);
450  buf += sizeof(uint24);
451 
452  return buf;
453 }
454 
458 };
459 
462 {
463 #ifdef DTLS_ECC
464  return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
465 #else
466  return 0;
467 #endif /* DTLS_ECC */
468 }
469 
472 {
473 #ifdef DTLS_PSK
474  return cipher == TLS_PSK_WITH_AES_128_CCM_8;
475 #else
476  return 0;
477 #endif /* DTLS_PSK */
478 }
479 
481 static inline int is_psk_supported(dtls_context_t *ctx)
482 {
483 #ifdef DTLS_PSK
484  return ctx && ctx->h && ctx->h->get_psk_info;
485 #else
486  return 0;
487 #endif /* DTLS_PSK */
488 }
489 
491 static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
492 {
493 #ifdef DTLS_ECC
494  return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
495  (is_client && ctx->h->verify_ecdsa_key));
496 #else
497  return 0;
498 #endif /* DTLS_ECC */
499 }
500 
504 {
505 #ifdef DTLS_ECC
506  return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
507 #else
508  return 0;
509 #endif /* DTLS_ECC */
510 }
511 
521 static int
522 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
523  int psk;
524  int ecdsa;
525 
526  psk = is_psk_supported(ctx);
527  ecdsa = is_ecdsa_supported(ctx, is_client);
528  return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
529  (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
530 }
531 
534 {
535  dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
536  dtls_debug_dump(" client_MAC_secret",
537  dtls_kb_client_mac_secret(config, peer->role),
538  dtls_kb_mac_secret_size(config, peer->role));
539 
540  dtls_debug_dump(" server_MAC_secret",
541  dtls_kb_server_mac_secret(config, peer->role),
542  dtls_kb_mac_secret_size(config, peer->role));
543 
544  dtls_debug_dump(" client_write_key",
545  dtls_kb_client_write_key(config, peer->role),
546  dtls_kb_key_size(config, peer->role));
547 
548  dtls_debug_dump(" server_write_key",
549  dtls_kb_server_write_key(config, peer->role),
550  dtls_kb_key_size(config, peer->role));
551 
552  dtls_debug_dump(" client_IV",
553  dtls_kb_client_iv(config, peer->role),
554  dtls_kb_iv_size(config, peer->role));
555 
556  dtls_debug_dump(" server_IV",
557  dtls_kb_server_iv(config, peer->role),
558  dtls_kb_iv_size(config, peer->role));
559 }
560 
565 static char *dtls_handshake_type_to_name(int type)
566 {
567  switch (type) {
569  return "hello_request";
571  return "client_hello";
573  return "server_hello";
575  return "hello_verify_request";
576  case DTLS_HT_CERTIFICATE:
577  return "certificate";
579  return "server_key_exchange";
581  return "certificate_request";
583  return "server_hello_done";
585  return "certificate_verify";
587  return "client_key_exchange";
588  case DTLS_HT_FINISHED:
589  return "finished";
590  default:
591  return "unknown";
592  }
593 }
594 
598 static int
600  dtls_handshake_parameters_t *handshake,
601  dtls_peer_t *peer,
602  session_t *session,
603  dtls_peer_type role) {
604  unsigned char *pre_master_secret;
605  int pre_master_len = 0;
607  uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
608 
609  if (!security) {
611  }
612 
613  pre_master_secret = security->key_block;
614 
615  switch (handshake->cipher) {
616 #ifdef DTLS_PSK
618  unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
619  int len;
620 
621  len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
622  handshake->keyx.psk.identity,
623  handshake->keyx.psk.id_length,
624  psk, DTLS_PSK_MAX_KEY_LEN);
625  if (len < 0) {
626  dtls_crit("no psk key for session available\n");
627  return len;
628  }
629  /* Temporarily use the key_block storage space for the pre master secret. */
630  pre_master_len = dtls_psk_pre_master_secret(psk, len,
631  pre_master_secret,
633 
634  dtls_debug_hexdump("psk", psk, len);
635 
636  memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
637  if (pre_master_len < 0) {
638  dtls_crit("the psk was too long, for the pre master secret\n");
640  }
641 
642  break;
643  }
644 #endif /* DTLS_PSK */
645 #ifdef DTLS_ECC
647  pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecdsa.own_eph_priv,
648  handshake->keyx.ecdsa.other_eph_pub_x,
649  handshake->keyx.ecdsa.other_eph_pub_y,
650  sizeof(handshake->keyx.ecdsa.own_eph_priv),
651  pre_master_secret,
653  if (pre_master_len < 0) {
654  dtls_crit("the curve was too long, for the pre master secret\n");
656  }
657  break;
658  }
659 #endif /* DTLS_ECC */
660  default:
661  dtls_crit("calculate_key_block: unknown cipher\n");
663  }
664 
665  dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
666  dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
667  dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
668 
669  dtls_prf(pre_master_secret, pre_master_len,
670  PRF_LABEL(master), PRF_LABEL_SIZE(master),
671  handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
672  handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
673  master_secret,
675 
676  dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
677 
678  /* create key_block from master_secret
679  * key_block = PRF(master_secret,
680  "key expansion" + tmp.random.server + tmp.random.client) */
681 
682  dtls_prf(master_secret,
684  PRF_LABEL(key), PRF_LABEL_SIZE(key),
685  handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
686  handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
687  security->key_block,
688  dtls_kb_size(security, role));
689 
690  memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
691  dtls_debug_keyblock(security);
692 
693  security->cipher = handshake->cipher;
694  security->compression = handshake->compression;
695  security->rseq = 0;
696 
697  return 0;
698 }
699 
700 /* TODO: add a generic method which iterates over a list and searches for a specific key */
701 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
702  int i, curve_name;
703 
704  /* length of curve list */
705  i = dtls_uint16_to_int(data);
706  data += sizeof(uint16);
707  if (i + sizeof(uint16) != data_length) {
708  dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
710  }
711 
712  for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
713  /* check if this curve is supported */
714  curve_name = dtls_uint16_to_int(data);
715  data += sizeof(uint16);
716 
717  if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
718  return 0;
719  }
720 
721  dtls_warn("no supported elliptic curve found\n");
723 }
724 
725 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
726  int i, cert_type;
727 
728  /* length of cert type list */
729  i = dtls_uint8_to_int(data);
730  data += sizeof(uint8);
731  if (i + sizeof(uint8) != data_length) {
732  dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
734  }
735 
736  for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
737  /* check if this cert type is supported */
738  cert_type = dtls_uint8_to_int(data);
739  data += sizeof(uint8);
740 
741  if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
742  return 0;
743  }
744 
745  dtls_warn("no supported certificate type found\n");
747 }
748 
749 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
750  int i, cert_type;
751 
752  /* length of ec_point_formats list */
753  i = dtls_uint8_to_int(data);
754  data += sizeof(uint8);
755  if (i + sizeof(uint8) != data_length) {
756  dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
758  }
759 
760  for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
761  /* check if this ec_point_format is supported */
762  cert_type = dtls_uint8_to_int(data);
763  data += sizeof(uint8);
764 
765  if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
766  return 0;
767  }
768 
769  dtls_warn("no supported ec_point_format found\n");
771 }
772 
773 /*
774  * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
775  */
776 static int
778  uint8 *data, size_t data_length, int client_hello)
779 {
780  uint16_t i, j;
781  int ext_elliptic_curve = 0;
782  int ext_client_cert_type = 0;
783  int ext_server_cert_type = 0;
784  int ext_ec_point_formats = 0;
786 
787  if (data_length < sizeof(uint16)) {
788  /* no tls extensions specified */
790  goto error;
791  }
792  return 0;
793  }
794 
795  /* get the length of the tls extension list */
796  j = dtls_uint16_to_int(data);
797  data += sizeof(uint16);
798  data_length -= sizeof(uint16);
799 
800  if (data_length < j)
801  goto error;
802 
803  /* check for TLS extensions needed for this cipher */
804  while (data_length) {
805  if (data_length < sizeof(uint16) * 2)
806  goto error;
807 
808  /* get the tls extension type */
809  i = dtls_uint16_to_int(data);
810  data += sizeof(uint16);
811  data_length -= sizeof(uint16);
812 
813  /* get the length of the tls extension */
814  j = dtls_uint16_to_int(data);
815  data += sizeof(uint16);
816  data_length -= sizeof(uint16);
817 
818  if (data_length < j)
819  goto error;
820 
821  switch (i) {
823  ext_elliptic_curve = 1;
824  if (verify_ext_eliptic_curves(data, j))
825  goto error;
826  break;
828  ext_client_cert_type = 1;
829  if (client_hello) {
830  if (verify_ext_cert_type(data, j))
831  goto error;
832  } else {
834  goto error;
835  }
836  break;
838  ext_server_cert_type = 1;
839  if (client_hello) {
840  if (verify_ext_cert_type(data, j))
841  goto error;
842  } else {
844  goto error;
845  }
846  break;
848  ext_ec_point_formats = 1;
849  if (verify_ext_ec_point_formats(data, j))
850  goto error;
851  break;
853  /* As only AEAD cipher suites are currently available, this
854  * extension can be skipped.
855  */
856  dtls_info("skipped encrypt-then-mac extension\n");
857  break;
858  default:
859  dtls_warn("unsupported tls extension: %i\n", i);
860  break;
861  }
862  data += j;
863  data_length -= j;
864  }
865  if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
866  if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
867  || !ext_ec_point_formats) {
868  dtls_warn("not all required tls extensions found in client hello\n");
869  goto error;
870  }
871  } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
872  if (!ext_client_cert_type || !ext_server_cert_type) {
873  dtls_warn("not all required tls extensions found in server hello\n");
874  goto error;
875  }
876  }
877  return 0;
878 
879 error:
880  if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
882  } else {
884  }
885 }
886 
899 static int
901  dtls_peer_t *peer,
902  uint8 *data, size_t data_length) {
903  int i, j;
904  int ok;
907 
908  assert(config);
909  assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
910 
911  /* skip the handshake header and client version information */
912  data += DTLS_HS_LENGTH + sizeof(uint16);
913  data_length -= DTLS_HS_LENGTH + sizeof(uint16);
914 
915  /* store client random in config */
916  memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
917  data += DTLS_RANDOM_LENGTH;
918  data_length -= DTLS_RANDOM_LENGTH;
919 
920  /* Caution: SKIP_VAR_FIELD may jump to error: */
921  SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
922  SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
923 
924  i = dtls_uint16_to_int(data);
925  if (data_length < i + sizeof(uint16)) {
926  /* Looks like we do not have a cipher nor compression. This is ok
927  * for renegotiation, but not for the initial handshake. */
928 
929  if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
930  goto error;
931 
932  config->cipher = security->cipher;
933  config->compression = security->compression;
934 
935  return 0;
936  }
937 
938  data += sizeof(uint16);
939  data_length -= sizeof(uint16) + i;
940 
941  ok = 0;
942  while (i && !ok) {
943  config->cipher = dtls_uint16_to_int(data);
944  ok = known_cipher(ctx, config->cipher, 0);
945  i -= sizeof(uint16);
946  data += sizeof(uint16);
947  }
948 
949  /* skip remaining ciphers */
950  data += i;
951 
952  if (!ok) {
953  /* reset config cipher to a well-defined value */
955  dtls_warn("No matching cipher found\n");
956  goto error;
957  }
958 
959  if (data_length < sizeof(uint8)) {
960  /* no compression specified, take the current compression method */
961  if (security)
962  config->compression = security->compression;
963  else
965  return 0;
966  }
967 
968  i = dtls_uint8_to_int(data);
969  if (data_length < i + sizeof(uint8))
970  goto error;
971 
972  data += sizeof(uint8);
973  data_length -= sizeof(uint8) + i;
974 
975  ok = 0;
976  while (i && !ok) {
977  for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
978  if (dtls_uint8_to_int(data) == compression_methods[j]) {
979  config->compression = compression_methods[j];
980  ok = 1;
981  }
982  i -= sizeof(uint8);
983  data += sizeof(uint8);
984  }
985 
986  if (!ok) {
987  /* reset config cipher to a well-defined value */
988  goto error;
989  }
990 
991  return dtls_check_tls_extension(peer, data, data_length, 1);
992 error:
993  if (peer->state == DTLS_STATE_CONNECTED) {
995  } else {
997  }
998 }
999 
1004 static inline int
1006  dtls_handshake_parameters_t *handshake,
1007  uint8 *data, size_t length) {
1008 
1009 #ifdef DTLS_ECC
1011 
1012  if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1013  dtls_debug("The client key exchange is too short\n");
1015  }
1016  data += DTLS_HS_LENGTH;
1017 
1018  if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1019  dtls_alert("expected 65 bytes long public point\n");
1021  }
1022  data += sizeof(uint8);
1023 
1024  if (dtls_uint8_to_int(data) != 4) {
1025  dtls_alert("expected uncompressed public point\n");
1027  }
1028  data += sizeof(uint8);
1029 
1030  memcpy(handshake->keyx.ecdsa.other_eph_pub_x, data,
1031  sizeof(handshake->keyx.ecdsa.other_eph_pub_x));
1032  data += sizeof(handshake->keyx.ecdsa.other_eph_pub_x);
1033 
1034  memcpy(handshake->keyx.ecdsa.other_eph_pub_y, data,
1035  sizeof(handshake->keyx.ecdsa.other_eph_pub_y));
1036  data += sizeof(handshake->keyx.ecdsa.other_eph_pub_y);
1037  }
1038 #endif /* DTLS_ECC */
1039 #ifdef DTLS_PSK
1040  if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1041  int id_length;
1042 
1043  if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1044  dtls_debug("The client key exchange is too short\n");
1046  }
1047  data += DTLS_HS_LENGTH;
1048 
1049  id_length = dtls_uint16_to_int(data);
1050  data += sizeof(uint16);
1051 
1052  if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1053  dtls_debug("The identity has a wrong length\n");
1055  }
1056 
1057  if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1058  dtls_warn("please use a smaller client identity\n");
1060  }
1061 
1062  handshake->keyx.psk.id_length = id_length;
1063  memcpy(handshake->keyx.psk.identity, data, id_length);
1064  }
1065 #endif /* DTLS_PSK */
1066  return 0;
1067 }
1068 
1069 static inline void
1070 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1071  dtls_debug_dump("add MAC data", data, length);
1072  dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1073 }
1074 
1075 static void
1077  memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1078  sizeof(peer->handshake_params->hs_state.hs_hash));
1079 }
1080 
1081 static inline size_t
1083  return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1084 }
1085 
1086 static inline void
1088  assert(peer);
1089  dtls_debug("clear MAC\n");
1091 }
1092 
1103 static int
1105  uint8 *data, size_t data_length) {
1106  size_t digest_length, label_size;
1107  const unsigned char *label;
1108  unsigned char buf[DTLS_HMAC_MAX];
1109 
1110  if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1112 
1113  /* Use a union here to ensure that sufficient stack space is
1114  * reserved. As statebuf and verify_data are not used at the same
1115  * time, we can re-use the storage safely.
1116  */
1117  union {
1118  unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1119  unsigned char verify_data[DTLS_FIN_LENGTH];
1120  } b;
1121 
1122  /* temporarily store hash status for roll-back after finalize */
1123  memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1124 
1125  digest_length = finalize_hs_hash(peer, buf);
1126  /* clear_hash(); */
1127 
1128  /* restore hash status */
1129  memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1130 
1131  if (peer->role == DTLS_CLIENT) {
1132  label = PRF_LABEL(server);
1133  label_size = PRF_LABEL_SIZE(server);
1134  } else { /* server */
1135  label = PRF_LABEL(client);
1136  label_size = PRF_LABEL_SIZE(client);
1137  }
1138 
1141  label, label_size,
1142  PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1143  buf, digest_length,
1144  b.verify_data, sizeof(b.verify_data));
1145 
1146  dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1147  dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1148 
1149  /* compare verify data and create DTLS alert code when they differ */
1150  return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1151  ? 0
1153 }
1154 
1179 static int
1181  unsigned char type,
1182  uint8 *data_array[], size_t data_len_array[],
1183  size_t data_array_len,
1184  uint8 *sendbuf, size_t *rlen) {
1185  uint8 *p, *start;
1186  int res;
1187  unsigned int i;
1188 
1189  if (*rlen < DTLS_RH_LENGTH) {
1190  dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1192  }
1193 
1194  p = dtls_set_record_header(type, security, sendbuf);
1195  start = p;
1196 
1197  if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1198  /* no cipher suite */
1199 
1200  res = 0;
1201  for (i = 0; i < data_array_len; i++) {
1202  /* check the minimum that we need for packets that are not encrypted */
1203  if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1204  dtls_debug("dtls_prepare_record: send buffer too small\n");
1206  }
1207 
1208  memcpy(p, data_array[i], data_len_array[i]);
1209  p += data_len_array[i];
1210  res += data_len_array[i];
1211  }
1212  } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1217 #define A_DATA_LEN 13
1218  unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1219  unsigned char A_DATA[A_DATA_LEN];
1220 
1221  if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1222  dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1223  } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1224  dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1225  } else {
1226  dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1227  }
1228 
1229  /* set nonce
1230  from RFC 6655:
1231  The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1232  the "nonce" SHALL be 12 bytes long and is constructed as follows:
1233  (this is an example of a "partially explicit" nonce; see Section
1234  3.2.1 in [RFC5116]).
1235 
1236  struct {
1237  opaque salt[4];
1238  opaque nonce_explicit[8];
1239  } CCMNonce;
1240 
1241  [...]
1242 
1243  In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1244  48-bit seq_num.
1245 
1246  When the nonce_explicit is equal to the sequence number, the CCMNonce
1247  will have the structure of the CCMNonceExample given below.
1248 
1249  struct {
1250  uint32 client_write_IV; // low order 32-bits
1251  uint64 seq_num; // TLS sequence number
1252  } CCMClientNonce.
1253 
1254 
1255  struct {
1256  uint32 server_write_IV; // low order 32-bits
1257  uint64 seq_num; // TLS sequence number
1258  } CCMServerNonce.
1259 
1260 
1261  struct {
1262  case client:
1263  CCMClientNonce;
1264  case server:
1265  CCMServerNonce:
1266  } CCMNonceExample;
1267  */
1268 
1269  memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1270  p += 8;
1271  res = 8;
1272 
1273  for (i = 0; i < data_array_len; i++) {
1274  /* check the minimum that we need for packets that are not encrypted */
1275  if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1276  dtls_debug("dtls_prepare_record: send buffer too small\n");
1278  }
1279 
1280  memcpy(p, data_array[i], data_len_array[i]);
1281  p += data_len_array[i];
1282  res += data_len_array[i];
1283  }
1284 
1285  memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1286  memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1287  dtls_kb_iv_size(security, peer->role));
1288  memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
1289 
1290  dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1291  dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1292  dtls_kb_key_size(security, peer->role));
1293 
1294  /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1295  *
1296  * additional_data = seq_num + TLSCompressed.type +
1297  * TLSCompressed.version + TLSCompressed.length;
1298  */
1299  memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1300  memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1301  dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1302 
1303  res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1304  dtls_kb_local_write_key(security, peer->role),
1305  dtls_kb_key_size(security, peer->role),
1306  A_DATA, A_DATA_LEN);
1307 
1308  if (res < 0)
1309  return res;
1310 
1311  res += 8; /* increment res by size of nonce_explicit */
1312  dtls_debug_dump("message:", start, res);
1313  }
1314 
1315  /* fix length of fragment in sendbuf */
1316  dtls_int_to_uint16(sendbuf + 11, res);
1317 
1318  *rlen = DTLS_RH_LENGTH + res;
1319  return 0;
1320 }
1321 
1322 static int
1324  dtls_peer_t *peer,
1325  session_t *session,
1326  uint8 header_type,
1327  uint8 *data, size_t data_length,
1328  int add_hash)
1329 {
1330  uint8 buf[DTLS_HS_LENGTH];
1331  uint8 *data_array[2];
1332  size_t data_len_array[2];
1333  int i = 0;
1334  dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1335 
1336  dtls_set_handshake_header(header_type, peer, data_length, 0,
1337  data_length, buf);
1338 
1339  if (add_hash) {
1340  update_hs_hash(peer, buf, sizeof(buf));
1341  }
1342  data_array[i] = buf;
1343  data_len_array[i] = sizeof(buf);
1344  i++;
1345 
1346  if (data != NULL) {
1347  if (add_hash) {
1348  update_hs_hash(peer, data, data_length);
1349  }
1350  data_array[i] = data;
1351  data_len_array[i] = data_length;
1352  i++;
1353  }
1354  dtls_debug("send handshake packet of type: %s (%i)\n",
1355  dtls_handshake_type_to_name(header_type), header_type);
1356  return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1357  data_array, data_len_array, i);
1358 }
1359 
1360 static int
1362  dtls_peer_t *peer,
1363  uint8 header_type,
1364  uint8 *data, size_t data_length)
1365 {
1366  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1367  header_type, data, data_length, 1);
1368 }
1369 
1384 #define MUST_HASH(Type, Data, Length) \
1385  ((Type) == DTLS_CT_HANDSHAKE && \
1386  ((Data) != NULL) && ((Length) > 0) && \
1387  ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) && \
1388  ((Data)[0] != DTLS_HT_CLIENT_HELLO || \
1389  ((Length) >= HS_HDR_LENGTH && \
1390  (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) || \
1391  (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1392 
1406 static int
1408  dtls_security_parameters_t *security , session_t *session,
1409  unsigned char type, uint8 *buf_array[],
1410  size_t buf_len_array[], size_t buf_array_len)
1411 {
1412  /* We cannot use ctx->sendbuf here as it is reserved for collecting
1413  * the input for this function, i.e. buf == ctx->sendbuf.
1414  *
1415  * TODO: check if we can use the receive buf here. This would mean
1416  * that we might not be able to handle multiple records stuffed in
1417  * one UDP datagram */
1418  unsigned char sendbuf[DTLS_MAX_BUF];
1419  size_t len = sizeof(sendbuf);
1420  int res;
1421  unsigned int i;
1422  size_t overall_len = 0;
1423 
1424  res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1425 
1426  if (res < 0)
1427  return res;
1428 
1429  /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1430  /* update_hs_hash(peer, buf, buflen); */
1431 
1432  dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1433  for (i = 0; i < buf_array_len; i++) {
1434  dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1435  overall_len += buf_len_array[i];
1436  }
1437 
1438  if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1439  type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1440  /* copy handshake messages other than HelloVerify into retransmit buffer */
1441  netq_t *n = netq_node_new(overall_len);
1442  if (n) {
1443  dtls_tick_t now;
1444  dtls_ticks(&now);
1445  n->t = now + 2 * CLOCK_SECOND;
1446  n->retransmit_cnt = 0;
1447  n->timeout = 2 * CLOCK_SECOND;
1448  n->peer = peer;
1449  n->epoch = (security) ? security->epoch : 0;
1450  n->type = type;
1451  n->length = 0;
1452  for (i = 0; i < buf_array_len; i++) {
1453  memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1454  n->length += buf_len_array[i];
1455  }
1456 
1457  if (!netq_insert_node(ctx->sendqueue, n)) {
1458  dtls_warn("cannot add packet to retransmit buffer\n");
1459  netq_node_free(n);
1460 #ifdef WITH_CONTIKI
1461  } else {
1462  /* must set timer within the context of the retransmit process */
1463  PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1464  etimer_set(&ctx->retransmit_timer, n->timeout);
1465  PROCESS_CONTEXT_END(&dtls_retransmit_process);
1466 #else /* WITH_CONTIKI */
1467  dtls_debug("copied to sendqueue\n");
1468 #endif /* WITH_CONTIKI */
1469  }
1470  } else
1471  dtls_warn("retransmit buffer full\n");
1472  }
1473 
1474  /* FIXME: copy to peer's sendqueue (after fragmentation if
1475  * necessary) and initialize retransmit timer */
1476  res = CALL(ctx, write, session, sendbuf, len);
1477 
1478  /* Guess number of bytes application data actually sent:
1479  * dtls_prepare_record() tells us in len the number of bytes to
1480  * send, res will contain the bytes actually sent. */
1481  return res <= 0 ? res : overall_len - (len - res);
1482 }
1483 
1484 static inline int
1486  dtls_alert_t description) {
1487  uint8_t msg[] = { level, description };
1488 
1489  dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1490  return 0;
1491 }
1492 
1493 int
1494 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1495  int res = -1;
1496  dtls_peer_t *peer;
1497 
1498  peer = dtls_get_peer(ctx, remote);
1499 
1500  if (peer) {
1502  /* indicate tear down */
1503  peer->state = DTLS_STATE_CLOSING;
1504  }
1505  return res;
1506 }
1507 
1508 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1509 {
1510  if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1511  dtls_close(ctx, &peer->session);
1512  if (unlink) {
1513 #ifndef WITH_CONTIKI
1514  HASH_DEL_PEER(ctx->peers, peer);
1515 #else /* WITH_CONTIKI */
1516  list_remove(ctx->peers, peer);
1517 #endif /* WITH_CONTIKI */
1518 
1519  dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1520  }
1521  dtls_free_peer(peer);
1522 }
1523 
1539 static int
1541  dtls_peer_t *peer,
1542  session_t *session,
1543  uint8 *data, size_t data_length)
1544 {
1546  uint8 *p = buf;
1547  int len = DTLS_COOKIE_LENGTH;
1548  uint8 *cookie = NULL;
1549  int err;
1550 #undef mycookie
1551 #define mycookie (buf + DTLS_HV_LENGTH)
1552 
1553  /* Store cookie where we can reuse it for the HelloVerify request. */
1554  err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1555  if (err < 0)
1556  return err;
1557 
1558  dtls_debug_dump("create cookie", mycookie, len);
1559 
1560  assert(len == DTLS_COOKIE_LENGTH);
1561 
1562  /* Perform cookie check. */
1563  len = dtls_get_cookie(data, data_length, &cookie);
1564  if (len < 0) {
1565  dtls_warn("error while fetching the cookie, err: %i\n", err);
1566  return err;
1567  }
1568 
1569  dtls_debug_dump("compare with cookie", cookie, len);
1570 
1571  /* check if cookies match */
1572  if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1573  dtls_debug("found matching cookie\n");
1574  return 0;
1575  }
1576 
1577  if (len > 0) {
1578  dtls_debug_dump("invalid cookie", cookie, len);
1579  } else {
1580  dtls_debug("cookie len is 0!\n");
1581  }
1582 
1583  /* ClientHello did not contain any valid cookie, hence we send a
1584  * HelloVerify request. */
1585 
1587  p += sizeof(uint16);
1588 
1590  p += sizeof(uint8);
1591 
1592  assert(p == mycookie);
1593 
1594  p += DTLS_COOKIE_LENGTH;
1595 
1596  /* TODO use the same record sequence number as in the ClientHello,
1597  see 4.2.1. Denial-of-Service Countermeasures */
1598  err = dtls_send_handshake_msg_hash(ctx, peer, session,
1600  buf, p - buf, 0);
1601  if (err < 0) {
1602  dtls_warn("cannot send HelloVerify request\n");
1603  }
1604  return err; /* HelloVerify is sent, now we cannot do anything but wait */
1605 
1606 #undef mycookie
1607 }
1608 
1609 #ifdef DTLS_ECC
1610 static int
1611 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1612  unsigned char **result_r,
1613  unsigned char **result_s)
1614 {
1615  int i;
1616  uint8 *data_orig = data;
1617 
1619  dtls_alert("only sha256 is supported in certificate verify\n");
1621  }
1622  data += sizeof(uint8);
1623  data_length -= sizeof(uint8);
1624 
1626  dtls_alert("only ecdsa signature is supported in client verify\n");
1628  }
1629  data += sizeof(uint8);
1630  data_length -= sizeof(uint8);
1631 
1632  if (data_length < dtls_uint16_to_int(data)) {
1633  dtls_alert("signature length wrong\n");
1635  }
1636  data += sizeof(uint16);
1637  data_length -= sizeof(uint16);
1638 
1639  if (dtls_uint8_to_int(data) != 0x30) {
1640  dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1642  }
1643  data += sizeof(uint8);
1644  data_length -= sizeof(uint8);
1645 
1646  if (data_length < dtls_uint8_to_int(data)) {
1647  dtls_alert("signature length wrong\n");
1649  }
1650  data += sizeof(uint8);
1651  data_length -= sizeof(uint8);
1652 
1653  if (dtls_uint8_to_int(data) != 0x02) {
1654  dtls_alert("wrong ASN.1 struct, expected Integer\n");
1656  }
1657  data += sizeof(uint8);
1658  data_length -= sizeof(uint8);
1659 
1660  i = dtls_uint8_to_int(data);
1661  data += sizeof(uint8);
1662  data_length -= sizeof(uint8);
1663 
1664  /* Sometimes these values have a leeding 0 byte */
1665  *result_r = data + i - DTLS_EC_KEY_SIZE;
1666 
1667  data += i;
1668  data_length -= i;
1669 
1670  if (dtls_uint8_to_int(data) != 0x02) {
1671  dtls_alert("wrong ASN.1 struct, expected Integer\n");
1673  }
1674  data += sizeof(uint8);
1675  data_length -= sizeof(uint8);
1676 
1677  i = dtls_uint8_to_int(data);
1678  data += sizeof(uint8);
1679  data_length -= sizeof(uint8);
1680 
1681  /* Sometimes these values have a leeding 0 byte */
1682  *result_s = data + i - DTLS_EC_KEY_SIZE;
1683 
1684  data += i;
1685  data_length -= i;
1686 
1687  return data - data_orig;
1688 }
1689 
1690 static int
1692  dtls_peer_t *peer,
1693  uint8 *data, size_t data_length)
1694 {
1696  int ret;
1697  unsigned char *result_r;
1698  unsigned char *result_s;
1699  dtls_hash_ctx hs_hash;
1700  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1701 
1703 
1704  data += DTLS_HS_LENGTH;
1705 
1706  if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1707  dtls_alert("the packet length does not match the expected\n");
1709  }
1710 
1711  ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
1712  if (ret < 0) {
1713  return ret;
1714  }
1715  data += ret;
1716  data_length -= ret;
1717 
1718  copy_hs_hash(peer, &hs_hash);
1719 
1720  dtls_hash_finalize(sha256hash, &hs_hash);
1721 
1722  ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecdsa.other_pub_x, config->keyx.ecdsa.other_pub_y,
1723  sizeof(config->keyx.ecdsa.other_pub_x),
1724  sha256hash, sizeof(sha256hash),
1725  result_r, result_s);
1726 
1727  if (ret < 0) {
1728  dtls_alert("wrong signature err: %i\n", ret);
1730  }
1731  return 0;
1732 }
1733 #endif /* DTLS_ECC */
1734 
1735 static int
1737 {
1738  /* Ensure that the largest message to create fits in our source
1739  * buffer. (The size of the destination buffer is checked by the
1740  * encoding function, so we do not need to guess.) */
1741  uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
1742  uint8 *p;
1743  int ecdsa;
1744  uint8 extension_size;
1745  dtls_handshake_parameters_t *handshake = peer->handshake_params;
1746  dtls_tick_t now;
1747 
1748  ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
1749 
1750  extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
1751 
1752  /* Handshake header */
1753  p = buf;
1754 
1755  /* ServerHello */
1757  p += sizeof(uint16);
1758 
1759  /* Set server random: First 4 bytes are the server's Unix timestamp,
1760  * followed by 28 bytes of generate random data. */
1761  dtls_ticks(&now);
1762  dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
1763  dtls_prng(handshake->tmp.random.server + 4, 28);
1764 
1765  memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
1766  p += DTLS_RANDOM_LENGTH;
1767 
1768  *p++ = 0; /* no session id */
1769 
1770  if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
1771  /* selected cipher suite */
1772  dtls_int_to_uint16(p, handshake->cipher);
1773  p += sizeof(uint16);
1774 
1775  /* selected compression method */
1776  *p++ = compression_methods[handshake->compression];
1777  }
1778 
1779  if (extension_size) {
1780  /* length of the extensions */
1781  dtls_int_to_uint16(p, extension_size - 2);
1782  p += sizeof(uint16);
1783  }
1784 
1785  if (ecdsa) {
1786  /* client certificate type extension */
1788  p += sizeof(uint16);
1789 
1790  /* length of this extension type */
1791  dtls_int_to_uint16(p, 1);
1792  p += sizeof(uint16);
1793 
1795  p += sizeof(uint8);
1796 
1797  /* client certificate type extension */
1799  p += sizeof(uint16);
1800 
1801  /* length of this extension type */
1802  dtls_int_to_uint16(p, 1);
1803  p += sizeof(uint16);
1804 
1806  p += sizeof(uint8);
1807 
1808  /* ec_point_formats */
1810  p += sizeof(uint16);
1811 
1812  /* length of this extension type */
1813  dtls_int_to_uint16(p, 2);
1814  p += sizeof(uint16);
1815 
1816  /* number of supported formats */
1817  dtls_int_to_uint8(p, 1);
1818  p += sizeof(uint8);
1819 
1821  p += sizeof(uint8);
1822  }
1823 
1824  assert(p - buf <= sizeof(buf));
1825 
1826  /* TODO use the same record sequence number as in the ClientHello,
1827  see 4.2.1. Denial-of-Service Countermeasures */
1829  buf, p - buf);
1830 }
1831 
1832 #ifdef DTLS_ECC
1833 static int
1835  const dtls_ecdsa_key_t *key)
1836 {
1837  uint8 buf[DTLS_CE_LENGTH];
1838  uint8 *p;
1839 
1840  /* Certificate
1841  *
1842  * Start message construction at beginning of buffer. */
1843  p = buf;
1844 
1845  dtls_int_to_uint24(p, 94); /* certificates length */
1846  p += sizeof(uint24);
1847 
1848  dtls_int_to_uint24(p, 91); /* length of this certificate */
1849  p += sizeof(uint24);
1850 
1851  memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
1852  p += sizeof(cert_asn1_header);
1853 
1854  memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
1855  p += DTLS_EC_KEY_SIZE;
1856 
1857  memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
1858  p += DTLS_EC_KEY_SIZE;
1859 
1860  assert(p - buf <= sizeof(buf));
1861 
1862  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
1863  buf, p - buf);
1864 }
1865 
1866 static uint8 *
1867 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
1868 {
1869  int len_r;
1870  int len_s;
1871 
1872 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
1873 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
1874  /* store the pointer to the r component of the signature and make space */
1876  len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
1877 
1878 #undef R_KEY_OFFSET
1879 #undef S_KEY_OFFSET
1880 
1881  /* sha256 */
1883  p += sizeof(uint8);
1884 
1885  /* ecdsa */
1887  p += sizeof(uint8);
1888 
1889  /* length of signature */
1890  dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
1891  p += sizeof(uint16);
1892 
1893  /* ASN.1 SEQUENCE */
1894  dtls_int_to_uint8(p, 0x30);
1895  p += sizeof(uint8);
1896 
1897  dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
1898  p += sizeof(uint8);
1899 
1900  /* ASN.1 Integer r */
1901  dtls_int_to_uint8(p, 0x02);
1902  p += sizeof(uint8);
1903 
1904  dtls_int_to_uint8(p, len_r);
1905  p += sizeof(uint8);
1906 
1907  /* the pint r was added here */
1908  p += len_r;
1909 
1910  /* ASN.1 Integer s */
1911  dtls_int_to_uint8(p, 0x02);
1912  p += sizeof(uint8);
1913 
1914  dtls_int_to_uint8(p, len_s);
1915  p += sizeof(uint8);
1916 
1917  /* the pint s was added here */
1918  p += len_s;
1919 
1920  return p;
1921 }
1922 
1923 static int
1925  const dtls_ecdsa_key_t *key)
1926 {
1927  /* The ASN.1 Integer representation of an 32 byte unsigned int could be
1928  * 33 bytes long add space for that */
1929  uint8 buf[DTLS_SKEXEC_LENGTH + 2];
1930  uint8 *p;
1931  uint8 *key_params;
1932  uint8 *ephemeral_pub_x;
1933  uint8 *ephemeral_pub_y;
1934  uint32_t point_r[9];
1935  uint32_t point_s[9];
1937 
1938  /* ServerKeyExchange
1939  *
1940  * Start message construction at beginning of buffer. */
1941  p = buf;
1942 
1943  key_params = p;
1944  /* ECCurveType curve_type: named_curve */
1945  dtls_int_to_uint8(p, 3);
1946  p += sizeof(uint8);
1947 
1948  /* NamedCurve namedcurve: secp256r1 */
1950  p += sizeof(uint16);
1951 
1952  dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
1953  p += sizeof(uint8);
1954 
1955  /* This should be an uncompressed point, but I do not have access to the spec. */
1956  dtls_int_to_uint8(p, 4);
1957  p += sizeof(uint8);
1958 
1959  /* store the pointer to the x component of the pub key and make space */
1960  ephemeral_pub_x = p;
1961  p += DTLS_EC_KEY_SIZE;
1962 
1963  /* store the pointer to the y component of the pub key and make space */
1964  ephemeral_pub_y = p;
1965  p += DTLS_EC_KEY_SIZE;
1966 
1967  dtls_ecdsa_generate_key(config->keyx.ecdsa.own_eph_priv,
1968  ephemeral_pub_x, ephemeral_pub_y,
1970 
1971  /* sign the ephemeral and its paramaters */
1973  config->tmp.random.client, DTLS_RANDOM_LENGTH,
1974  config->tmp.random.server, DTLS_RANDOM_LENGTH,
1975  key_params, p - key_params,
1976  point_r, point_s);
1977 
1978  p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
1979 
1980  assert(p - buf <= sizeof(buf));
1981 
1983  buf, p - buf);
1984 }
1985 #endif /* DTLS_ECC */
1986 
1987 #ifdef DTLS_PSK
1988 static int
1990  const unsigned char *psk_hint, size_t len)
1991 {
1993  uint8 *p;
1994 
1995  p = buf;
1996 
1997  assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
1999  /* should never happen */
2000  dtls_warn("psk identity hint is too long\n");
2002  }
2003 
2004  dtls_int_to_uint16(p, len);
2005  p += sizeof(uint16);
2006 
2007  memcpy(p, psk_hint, len);
2008  p += len;
2009 
2010  assert(p - buf <= sizeof(buf));
2011 
2013  buf, p - buf);
2014 }
2015 #endif /* DTLS_PSK */
2016 
2017 #ifdef DTLS_ECC
2018 static int
2020 {
2021  uint8 buf[8];
2022  uint8 *p;
2023 
2024  /* ServerHelloDone
2025  *
2026  * Start message construction at beginning of buffer. */
2027  p = buf;
2028 
2029  /* certificate_types */
2030  dtls_int_to_uint8(p, 1);
2031  p += sizeof(uint8);
2032 
2033  /* ecdsa_sign */
2035  p += sizeof(uint8);
2036 
2037  /* supported_signature_algorithms */
2038  dtls_int_to_uint16(p, 2);
2039  p += sizeof(uint16);
2040 
2041  /* sha256 */
2043  p += sizeof(uint8);
2044 
2045  /* ecdsa */
2047  p += sizeof(uint8);
2048 
2049  /* certificate_authoritiess */
2050  dtls_int_to_uint16(p, 0);
2051  p += sizeof(uint16);
2052 
2053  assert(p - buf <= sizeof(buf));
2054 
2056  buf, p - buf);
2057 }
2058 #endif /* DTLS_ECC */
2059 
2060 static int
2062 {
2063 
2064  /* ServerHelloDone
2065  *
2066  * Start message construction at beginning of buffer. */
2067 
2069  NULL, 0);
2070 }
2071 
2072 static int
2074 {
2075  int res;
2076 
2077  res = dtls_send_server_hello(ctx, peer);
2078 
2079  if (res < 0) {
2080  dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2081  return res;
2082  }
2083 
2084 #ifdef DTLS_ECC
2086  const dtls_ecdsa_key_t *ecdsa_key;
2087 
2088  res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2089  if (res < 0) {
2090  dtls_crit("no ecdsa certificate to send in certificate\n");
2091  return res;
2092  }
2093 
2094  res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2095 
2096  if (res < 0) {
2097  dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2098  return res;
2099  }
2100 
2101  res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2102 
2103  if (res < 0) {
2104  dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2105  return res;
2106  }
2107 
2110  res = dtls_send_server_certificate_request(ctx, peer);
2111 
2112  if (res < 0) {
2113  dtls_debug("dtls_server_hello: cannot prepare certificate Request record\n");
2114  return res;
2115  }
2116  }
2117  }
2118 #endif /* DTLS_ECC */
2119 
2120 #ifdef DTLS_PSK
2122  unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2123  int len;
2124 
2125  /* The identity hint is optional, therefore we ignore the result
2126  * and check psk only. */
2127  len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2128  NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2129 
2130  if (len < 0) {
2131  dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2132  return len;
2133  }
2134 
2135  if (len > 0) {
2136  res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2137 
2138  if (res < 0) {
2139  dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2140  return res;
2141  }
2142  }
2143  }
2144 #endif /* DTLS_PSK */
2145 
2146  res = dtls_send_server_hello_done(ctx, peer);
2147 
2148  if (res < 0) {
2149  dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2150  return res;
2151  }
2152  return 0;
2153 }
2154 
2155 static inline int
2157  uint8 buf[1] = {1};
2158 
2159  return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2160 }
2161 
2162 
2163 static int
2165 {
2166  uint8 buf[DTLS_CKXEC_LENGTH];
2167  uint8 *p;
2168  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2169 
2170  p = buf;
2171 
2172  switch (handshake->cipher) {
2173 #ifdef DTLS_PSK
2175  int len;
2176 
2177  len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2178  handshake->keyx.psk.identity, handshake->keyx.psk.id_length,
2179  buf + sizeof(uint16),
2180  min(sizeof(buf) - sizeof(uint16),
2181  sizeof(handshake->keyx.psk.identity)));
2182  if (len < 0) {
2183  dtls_crit("no psk identity set in kx\n");
2184  return len;
2185  }
2186 
2187  if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2188  memset(&handshake->keyx.psk, 0, sizeof(dtls_handshake_parameters_psk_t));
2189  dtls_warn("the psk identity is too long\n");
2191  }
2192  handshake->keyx.psk.id_length = (unsigned int)len;
2193  memcpy(handshake->keyx.psk.identity, p + sizeof(uint16), len);
2194 
2195  dtls_int_to_uint16(p, handshake->keyx.psk.id_length);
2196  p += sizeof(uint16);
2197 
2198  memcpy(p, handshake->keyx.psk.identity, handshake->keyx.psk.id_length);
2199  p += handshake->keyx.psk.id_length;
2200 
2201  break;
2202  }
2203 #endif /* DTLS_PSK */
2204 #ifdef DTLS_ECC
2206  uint8 *ephemeral_pub_x;
2207  uint8 *ephemeral_pub_y;
2208 
2209  dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2210  p += sizeof(uint8);
2211 
2212  /* This should be an uncompressed point, but I do not have access to the spec. */
2213  dtls_int_to_uint8(p, 4);
2214  p += sizeof(uint8);
2215 
2216  ephemeral_pub_x = p;
2217  p += DTLS_EC_KEY_SIZE;
2218  ephemeral_pub_y = p;
2219  p += DTLS_EC_KEY_SIZE;
2220 
2221  dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecdsa.own_eph_priv,
2222  ephemeral_pub_x, ephemeral_pub_y,
2224 
2225  break;
2226  }
2227 #endif /* DTLS_ECC */
2228  default:
2229  dtls_crit("cipher not supported\n");
2231  }
2232 
2233  assert(p - buf <= sizeof(buf));
2234 
2236  buf, p - buf);
2237 }
2238 
2239 #ifdef DTLS_ECC
2240 static int
2242  const dtls_ecdsa_key_t *key)
2243 {
2244  /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2245  * 33 bytes long add space for that */
2246  uint8 buf[DTLS_CV_LENGTH + 2];
2247  uint8 *p;
2248  uint32_t point_r[9];
2249  uint32_t point_s[9];
2250  dtls_hash_ctx hs_hash;
2251  unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2252 
2253  /* ServerKeyExchange
2254  *
2255  * Start message construction at beginning of buffer. */
2256  p = buf;
2257 
2258  copy_hs_hash(peer, &hs_hash);
2259 
2260  dtls_hash_finalize(sha256hash, &hs_hash);
2261 
2262  /* sign the ephemeral and its paramaters */
2264  sha256hash, sizeof(sha256hash),
2265  point_r, point_s);
2266 
2267  p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2268 
2269  assert(p - buf <= sizeof(buf));
2270 
2272  buf, p - buf);
2273 }
2274 #endif /* DTLS_ECC */
2275 
2276 static int
2278  const unsigned char *label, size_t labellen)
2279 {
2280  int length;
2281  uint8 hash[DTLS_HMAC_MAX];
2282  uint8 buf[DTLS_FIN_LENGTH];
2283  dtls_hash_ctx hs_hash;
2284  uint8 *p = buf;
2285 
2286  copy_hs_hash(peer, &hs_hash);
2287 
2288  length = dtls_hash_finalize(hash, &hs_hash);
2289 
2292  label, labellen,
2293  PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2294  hash, length,
2295  p, DTLS_FIN_LENGTH);
2296 
2297  dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2298 
2299  p += DTLS_FIN_LENGTH;
2300 
2301  assert(p - buf <= sizeof(buf));
2302 
2303  return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2304  buf, p - buf);
2305 }
2306 
2307 static int
2309  uint8 cookie[], size_t cookie_length) {
2311  uint8 *p = buf;
2312  uint8_t cipher_size;
2313  uint8_t extension_size;
2314  int psk;
2315  int ecdsa;
2316  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2317  dtls_tick_t now;
2318 
2319  psk = is_psk_supported(ctx);
2320  ecdsa = is_ecdsa_supported(ctx, 1);
2321 
2322  cipher_size = 2 + ((ecdsa) ? 2 : 0) + ((psk) ? 2 : 0);
2323  extension_size = (ecdsa) ? 2 + 6 + 6 + 8 + 6: 0;
2324 
2325  if (cipher_size == 0) {
2326  dtls_crit("no cipher callbacks implemented\n");
2327  }
2328 
2330  p += sizeof(uint16);
2331 
2332  if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2333  dtls_warn("the cookie is too long\n");
2335  }
2336 
2337  if (cookie_length == 0) {
2338  /* Set client random: First 4 bytes are the client's Unix timestamp,
2339  * followed by 28 bytes of generate random data. */
2340  dtls_ticks(&now);
2341  dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2342  dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2343  DTLS_RANDOM_LENGTH - sizeof(uint32));
2344  }
2345  /* we must use the same Client Random as for the previous request */
2346  memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2347  p += DTLS_RANDOM_LENGTH;
2348 
2349  /* session id (length 0) */
2350  dtls_int_to_uint8(p, 0);
2351  p += sizeof(uint8);
2352 
2353  /* cookie */
2354  dtls_int_to_uint8(p, cookie_length);
2355  p += sizeof(uint8);
2356  if (cookie_length != 0) {
2357  memcpy(p, cookie, cookie_length);
2358  p += cookie_length;
2359  }
2360 
2361  /* add known cipher(s) */
2362  dtls_int_to_uint16(p, cipher_size - 2);
2363  p += sizeof(uint16);
2364 
2365  if (ecdsa) {
2367  p += sizeof(uint16);
2368  }
2369  if (psk) {
2371  p += sizeof(uint16);
2372  }
2373 
2374  /* compression method */
2375  dtls_int_to_uint8(p, 1);
2376  p += sizeof(uint8);
2377 
2379  p += sizeof(uint8);
2380 
2381  if (extension_size) {
2382  /* length of the extensions */
2383  dtls_int_to_uint16(p, extension_size - 2);
2384  p += sizeof(uint16);
2385  }
2386 
2387  if (ecdsa) {
2388  /* client certificate type extension */
2390  p += sizeof(uint16);
2391 
2392  /* length of this extension type */
2393  dtls_int_to_uint16(p, 2);
2394  p += sizeof(uint16);
2395 
2396  /* length of the list */
2397  dtls_int_to_uint8(p, 1);
2398  p += sizeof(uint8);
2399 
2401  p += sizeof(uint8);
2402 
2403  /* client certificate type extension */
2405  p += sizeof(uint16);
2406 
2407  /* length of this extension type */
2408  dtls_int_to_uint16(p, 2);
2409  p += sizeof(uint16);
2410 
2411  /* length of the list */
2412  dtls_int_to_uint8(p, 1);
2413  p += sizeof(uint8);
2414 
2416  p += sizeof(uint8);
2417 
2418  /* elliptic_curves */
2420  p += sizeof(uint16);
2421 
2422  /* length of this extension type */
2423  dtls_int_to_uint16(p, 4);
2424  p += sizeof(uint16);
2425 
2426  /* length of the list */
2427  dtls_int_to_uint16(p, 2);
2428  p += sizeof(uint16);
2429 
2431  p += sizeof(uint16);
2432 
2433  /* ec_point_formats */
2435  p += sizeof(uint16);
2436 
2437  /* length of this extension type */
2438  dtls_int_to_uint16(p, 2);
2439  p += sizeof(uint16);
2440 
2441  /* number of supported formats */
2442  dtls_int_to_uint8(p, 1);
2443  p += sizeof(uint8);
2444 
2446  p += sizeof(uint8);
2447  }
2448 
2449  assert(p - buf <= sizeof(buf));
2450 
2451  if (cookie_length != 0)
2452  clear_hs_hash(peer);
2453 
2454  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2456  buf, p - buf, cookie_length != 0);
2457 }
2458 
2459 static int
2461  dtls_peer_t *peer,
2462  uint8 *data, size_t data_length)
2463 {
2464  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2465 
2466  /* This function is called when we expect a ServerHello (i.e. we
2467  * have sent a ClientHello). We might instead receive a HelloVerify
2468  * request containing a cookie. If so, we must repeat the
2469  * ClientHello with the given Cookie.
2470  */
2471  if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
2473 
2474  update_hs_hash(peer, data, data_length);
2475 
2476  /* FIXME: check data_length before accessing fields */
2477 
2478  /* Get the server's random data and store selected cipher suite
2479  * and compression method (like dtls_update_parameters().
2480  * Then calculate master secret and wait for ServerHelloDone. When received,
2481  * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
2482 
2483  /* check server version */
2484  data += DTLS_HS_LENGTH;
2485  data_length -= DTLS_HS_LENGTH;
2486 
2487  if (dtls_uint16_to_int(data) != DTLS_VERSION) {
2488  dtls_alert("unknown DTLS version\n");
2490  }
2491 
2492  data += sizeof(uint16); /* skip version field */
2493  data_length -= sizeof(uint16);
2494 
2495  /* store server random data */
2496  memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
2497  /* skip server random */
2498  data += DTLS_RANDOM_LENGTH;
2499  data_length -= DTLS_RANDOM_LENGTH;
2500 
2501  SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
2502 
2503  /* Check cipher suite. As we offer all we have, it is sufficient
2504  * to check if the cipher suite selected by the server is in our
2505  * list of known cipher suites. Subsets are not supported. */
2506  handshake->cipher = dtls_uint16_to_int(data);
2507  if (!known_cipher(ctx, handshake->cipher, 1)) {
2508  dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
2509  data[0], data[1]);
2511  }
2512  data += sizeof(uint16);
2513  data_length -= sizeof(uint16);
2514 
2515  /* Check if NULL compression was selected. We do not know any other. */
2516  if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
2517  dtls_alert("unsupported compression method 0x%02x\n", data[0]);
2519  }
2520  data += sizeof(uint8);
2521  data_length -= sizeof(uint8);
2522 
2523  return dtls_check_tls_extension(peer, data, data_length, 0);
2524 
2525 error:
2527 }
2528 
2529 static int
2531  dtls_peer_t *peer,
2532  uint8 *data, size_t data_length)
2533 {
2534  dtls_hello_verify_t *hv;
2535  int res;
2536 
2537  if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
2539 
2540  hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
2541 
2542  res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
2543 
2544  if (res < 0)
2545  dtls_warn("cannot send ClientHello\n");
2546 
2547  return res;
2548 }
2549 
2550 #ifdef DTLS_ECC
2551 static int
2553  dtls_peer_t *peer,
2554  uint8 *data, size_t data_length)
2555 {
2556  int err;
2558 
2559  update_hs_hash(peer, data, data_length);
2560 
2562 
2563  data += DTLS_HS_LENGTH;
2564 
2565  if (dtls_uint24_to_int(data) != 94) {
2566  dtls_alert("expect length of 94 bytes for server certificate message\n");
2568  }
2569  data += sizeof(uint24);
2570 
2571  if (dtls_uint24_to_int(data) != 91) {
2572  dtls_alert("expect length of 91 bytes for certificate\n");
2574  }
2575  data += sizeof(uint24);
2576 
2577  if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
2578  dtls_alert("got an unexpected Subject public key format\n");
2580  }
2581  data += sizeof(cert_asn1_header);
2582 
2583  memcpy(config->keyx.ecdsa.other_pub_x, data,
2584  sizeof(config->keyx.ecdsa.other_pub_x));
2585  data += sizeof(config->keyx.ecdsa.other_pub_x);
2586 
2587  memcpy(config->keyx.ecdsa.other_pub_y, data,
2588  sizeof(config->keyx.ecdsa.other_pub_y));
2589  data += sizeof(config->keyx.ecdsa.other_pub_y);
2590 
2591  err = CALL(ctx, verify_ecdsa_key, &peer->session,
2592  config->keyx.ecdsa.other_pub_x,
2593  config->keyx.ecdsa.other_pub_y,
2594  sizeof(config->keyx.ecdsa.other_pub_x));
2595  if (err < 0) {
2596  dtls_warn("The certificate was not accepted\n");
2597  return err;
2598  }
2599 
2600  return 0;
2601 }
2602 
2603 static int
2605  dtls_peer_t *peer,
2606  uint8 *data, size_t data_length)
2607 {
2609  int ret;
2610  unsigned char *result_r;
2611  unsigned char *result_s;
2612  unsigned char *key_params;
2613 
2614  update_hs_hash(peer, data, data_length);
2615 
2617 
2618  data += DTLS_HS_LENGTH;
2619 
2620  if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
2621  dtls_alert("the packet length does not match the expected\n");
2623  }
2624  key_params = data;
2625 
2627  dtls_alert("Only named curves supported\n");
2629  }
2630  data += sizeof(uint8);
2631  data_length -= sizeof(uint8);
2632 
2634  dtls_alert("secp256r1 supported\n");
2636  }
2637  data += sizeof(uint16);
2638  data_length -= sizeof(uint16);
2639 
2640  if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
2641  dtls_alert("expected 65 bytes long public point\n");
2643  }
2644  data += sizeof(uint8);
2645  data_length -= sizeof(uint8);
2646 
2647  if (dtls_uint8_to_int(data) != 4) {
2648  dtls_alert("expected uncompressed public point\n");
2650  }
2651  data += sizeof(uint8);
2652  data_length -= sizeof(uint8);
2653 
2654  memcpy(config->keyx.ecdsa.other_eph_pub_x, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
2655  data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
2656  data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
2657 
2658  memcpy(config->keyx.ecdsa.other_eph_pub_y, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
2659  data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
2660  data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
2661 
2662  ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
2663  if (ret < 0) {
2664  return ret;
2665  }
2666  data += ret;
2667  data_length -= ret;
2668 
2669  ret = dtls_ecdsa_verify_sig(config->keyx.ecdsa.other_pub_x, config->keyx.ecdsa.other_pub_y,
2670  sizeof(config->keyx.ecdsa.other_pub_x),
2671  config->tmp.random.client, DTLS_RANDOM_LENGTH,
2672  config->tmp.random.server, DTLS_RANDOM_LENGTH,
2673  key_params,
2674  1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
2675  result_r, result_s);
2676 
2677  if (ret < 0) {
2678  dtls_alert("wrong signature\n");
2680  }
2681  return 0;
2682 }
2683 #endif /* DTLS_ECC */
2684 
2685 #ifdef DTLS_PSK
2686 static int
2688  dtls_peer_t *peer,
2689  uint8 *data, size_t data_length)
2690 {
2692  uint16_t len;
2693 
2694  update_hs_hash(peer, data, data_length);
2695 
2696  assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
2697 
2698  data += DTLS_HS_LENGTH;
2699 
2700  if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
2701  dtls_alert("the packet length does not match the expected\n");
2703  }
2704 
2705  len = dtls_uint16_to_int(data);
2706  data += sizeof(uint16);
2707 
2708  if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
2709  dtls_warn("the length of the server identity hint is worng\n");
2711  }
2712 
2714  dtls_warn("please use a smaller server identity hint\n");
2716  }
2717 
2718  /* store the psk_identity_hint in config->keyx.psk for later use */
2719  config->keyx.psk.id_length = len;
2720  memcpy(config->keyx.psk.identity, data, len);
2721  return 0;
2722 }
2723 #endif /* DTLS_PSK */
2724 
2725 static int
2727  dtls_peer_t *peer,
2728  uint8 *data, size_t data_length)
2729 {
2730  unsigned int i;
2731  int auth_alg;
2732  int sig_alg;
2733  int hash_alg;
2734 
2735  update_hs_hash(peer, data, data_length);
2736 
2738 
2739  data += DTLS_HS_LENGTH;
2740 
2741  if (data_length < DTLS_HS_LENGTH + 5) {
2742  dtls_alert("the packet length does not match the expected\n");
2744  }
2745 
2746  i = dtls_uint8_to_int(data);
2747  data += sizeof(uint8);
2748  if (i + 1 > data_length) {
2749  dtls_alert("the cerfificate types are too long\n");
2751  }
2752 
2753  auth_alg = 0;
2754  for (; i > 0 ; i -= sizeof(uint8)) {
2756  && auth_alg == 0)
2757  auth_alg = dtls_uint8_to_int(data);
2758  data += sizeof(uint8);
2759  }
2760 
2761  if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
2762  dtls_alert("the request authentication algorithm is not supproted\n");
2764  }
2765 
2766  i = dtls_uint16_to_int(data);
2767  data += sizeof(uint16);
2768  if (i + 1 > data_length) {
2769  dtls_alert("the signature and hash algorithm list is too long\n");
2771  }
2772 
2773  hash_alg = 0;
2774  sig_alg = 0;
2775  for (; i > 0 ; i -= sizeof(uint16)) {
2776  int current_hash_alg;
2777  int current_sig_alg;
2778 
2779  current_hash_alg = dtls_uint8_to_int(data);
2780  data += sizeof(uint8);
2781  current_sig_alg = dtls_uint8_to_int(data);
2782  data += sizeof(uint8);
2783 
2784  if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 &&
2785  current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
2786  hash_alg = current_hash_alg;
2787  sig_alg = current_sig_alg;
2788  }
2789  }
2790 
2791  if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
2792  sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
2793  dtls_alert("no supported hash and signature algorithem\n");
2795  }
2796 
2797  /* common names are ignored */
2798 
2799  peer->handshake_params->do_client_auth = 1;
2800  return 0;
2801 }
2802 
2803 static int
2805  dtls_peer_t *peer,
2806  uint8 *data, size_t data_length)
2807 {
2808  int res;
2809 #ifdef DTLS_ECC
2810  const dtls_ecdsa_key_t *ecdsa_key;
2811 #endif /* DTLS_ECC */
2812 
2813  dtls_handshake_parameters_t *handshake = peer->handshake_params;
2814 
2815  /* calculate master key, send CCS */
2816 
2817  update_hs_hash(peer, data, data_length);
2818 
2819 #ifdef DTLS_ECC
2820  if (handshake->do_client_auth) {
2821 
2822  res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2823  if (res < 0) {
2824  dtls_crit("no ecdsa certificate to send in certificate\n");
2825  return res;
2826  }
2827 
2828  res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2829 
2830  if (res < 0) {
2831  dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2832  return res;
2833  }
2834  }
2835 #endif /* DTLS_ECC */
2836 
2837  /* send ClientKeyExchange */
2838  res = dtls_send_client_key_exchange(ctx, peer);
2839 
2840  if (res < 0) {
2841  dtls_debug("cannot send KeyExchange message\n");
2842  return res;
2843  }
2844 
2845 #ifdef DTLS_ECC
2846  if (handshake->do_client_auth) {
2847 
2848  res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
2849 
2850  if (res < 0) {
2851  dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2852  return res;
2853  }
2854  }
2855 #endif /* DTLS_ECC */
2856 
2857  res = calculate_key_block(ctx, handshake, peer,
2858  &peer->session, peer->role);
2859  if (res < 0) {
2860  return res;
2861  }
2862 
2863  res = dtls_send_ccs(ctx, peer);
2864  if (res < 0) {
2865  dtls_debug("cannot send CCS message\n");
2866  return res;
2867  }
2868 
2869  /* and switch cipher suite */
2871 
2872  /* Client Finished */
2873  return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
2874 }
2875 
2876 static int
2877 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
2878  uint8 **cleartext)
2879 {
2880  dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
2882  int clen;
2883 
2884  *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
2885  clen = length - sizeof(dtls_record_header_t);
2886 
2887  if (!security) {
2888  dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
2889  return -1;
2890  }
2891 
2892  if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
2893  /* no cipher suite selected */
2894  return clen;
2895  } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
2900 #define A_DATA_LEN 13
2901  unsigned char nonce[DTLS_CCM_BLOCKSIZE];
2902  unsigned char A_DATA[A_DATA_LEN];
2903 
2904  if (clen < 16) /* need at least IV and MAC */
2905  return -1;
2906 
2907  memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
2908  memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
2909  dtls_kb_iv_size(security, peer->role));
2910 
2911  /* read epoch and seq_num from message */
2912  memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
2913  *cleartext += 8;
2914  clen -= 8;
2915 
2916  dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
2917  dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
2918  dtls_kb_key_size(security, peer->role));
2919  dtls_debug_dump("ciphertext", *cleartext, clen);
2920 
2921  /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
2922  *
2923  * additional_data = seq_num + TLSCompressed.type +
2924  * TLSCompressed.version + TLSCompressed.length;
2925  */
2926  memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
2927  memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
2928  dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
2929 
2930  clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
2931  dtls_kb_remote_write_key(security, peer->role),
2932  dtls_kb_key_size(security, peer->role),
2933  A_DATA, A_DATA_LEN);
2934  if (clen < 0)
2935  dtls_warn("decryption failed\n");
2936  else {
2937 #ifndef NDEBUG
2938  printf("decrypt_verify(): found %i bytes cleartext\n", clen);
2939 #endif
2941  dtls_debug_dump("cleartext", *cleartext, clen);
2942  }
2943  }
2944  return clen;
2945 }
2946 
2947 static int
2949 {
2950  return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2952  NULL, 0, 0);
2953 }
2954 
2955 int
2957 {
2958  dtls_peer_t *peer = NULL;
2959  int err;
2960 
2961  peer = dtls_get_peer(ctx, dst);
2962 
2963  if (!peer) {
2964  return -1;
2965  }
2966  if (peer->state != DTLS_STATE_CONNECTED)
2967  return -1;
2968 
2970  if (!peer->handshake_params)
2971  return -1;
2972 
2973  peer->handshake_params->hs_state.mseq_r = 0;
2974  peer->handshake_params->hs_state.mseq_s = 0;
2975 
2976  if (peer->role == DTLS_CLIENT) {
2977  /* send ClientHello with empty Cookie */
2978  err = dtls_send_client_hello(ctx, peer, NULL, 0);
2979  if (err < 0)
2980  dtls_warn("cannot send ClientHello\n");
2981  else
2982  peer->state = DTLS_STATE_CLIENTHELLO;
2983  return err;
2984  } else if (peer->role == DTLS_SERVER) {
2985  return dtls_send_hello_request(ctx, peer);
2986  }
2987 
2988  return -1;
2989 }
2990 
2991 static int
2993  const dtls_peer_type role, const dtls_state_t state,
2994  uint8 *data, size_t data_length) {
2995 
2996  int err = 0;
2997 
2998  /* This will clear the retransmission buffer if we get an expected
2999  * handshake message. We have to make sure that no handshake message
3000  * should get expected when we still should retransmit something, when
3001  * we do everything accordingly to the DTLS 1.2 standard this should
3002  * not be a problem. */
3003  if (peer) {
3004  dtls_stop_retransmission(ctx, peer);
3005  }
3006 
3007  /* The following switch construct handles the given message with
3008  * respect to the current internal state for this peer. In case of
3009  * error, it is left with return 0. */
3010 
3011  dtls_debug("handle handshake packet of type: %s (%i)\n",
3012  dtls_handshake_type_to_name(data[0]), data[0]);
3013  switch (data[0]) {
3014 
3015  /************************************************************************
3016  * Client states
3017  ************************************************************************/
3019 
3020  if (state != DTLS_STATE_CLIENTHELLO) {
3022  }
3023 
3024  err = check_server_hello_verify_request(ctx, peer, data, data_length);
3025  if (err < 0) {
3026  dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3027  return err;
3028  }
3029 
3030  break;
3031  case DTLS_HT_SERVER_HELLO:
3032 
3033  if (state != DTLS_STATE_CLIENTHELLO) {
3035  }
3036 
3037  err = check_server_hello(ctx, peer, data, data_length);
3038  if (err < 0) {
3039  dtls_warn("error in check_server_hello err: %i\n", err);
3040  return err;
3041  }
3044  else
3046  /* update_hs_hash(peer, data, data_length); */
3047 
3048  break;
3049 
3050 #ifdef DTLS_ECC
3051  case DTLS_HT_CERTIFICATE:
3052 
3053  if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3054  (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3056  }
3057  err = check_server_certificate(ctx, peer, data, data_length);
3058  if (err < 0) {
3059  dtls_warn("error in check_server_certificate err: %i\n", err);
3060  return err;
3061  }
3062  if (role == DTLS_CLIENT) {
3064  } else if (role == DTLS_SERVER){
3066  }
3067  /* update_hs_hash(peer, data, data_length); */
3068 
3069  break;
3070 #endif /* DTLS_ECC */
3071 
3073 
3074 #ifdef DTLS_ECC
3076  if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3078  }
3079  err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3080  }
3081 #endif /* DTLS_ECC */
3082 #ifdef DTLS_PSK
3084  if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3086  }
3087  err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3088  }
3089 #endif /* DTLS_PSK */
3090 
3091  if (err < 0) {
3092  dtls_warn("error in check_server_key_exchange err: %i\n", err);
3093  return err;
3094  }
3096  /* update_hs_hash(peer, data, data_length); */
3097 
3098  break;
3099 
3101 
3102  if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3104  }
3105 
3106  err = check_server_hellodone(ctx, peer, data, data_length);
3107  if (err < 0) {
3108  dtls_warn("error in check_server_hellodone err: %i\n", err);
3109  return err;
3110  }
3112  /* update_hs_hash(peer, data, data_length); */
3113 
3114  break;
3115 
3117 
3118  if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3120  }
3121 
3122  err = check_certificate_request(ctx, peer, data, data_length);
3123  if (err < 0) {
3124  dtls_warn("error in check_certificate_request err: %i\n", err);
3125  return err;
3126  }
3127 
3128  break;
3129 
3130  case DTLS_HT_FINISHED:
3131  /* expect a Finished message from server */
3132 
3133  if (state != DTLS_STATE_WAIT_FINISHED) {
3135  }
3136 
3137  err = check_finished(ctx, peer, data, data_length);
3138  if (err < 0) {
3139  dtls_warn("error in check_finished err: %i\n", err);
3140  return err;
3141  }
3142  if (role == DTLS_SERVER) {
3143  /* send ServerFinished */
3144  update_hs_hash(peer, data, data_length);
3145 
3146  /* send change cipher spec message and switch to new configuration */
3147  err = dtls_send_ccs(ctx, peer);
3148  if (err < 0) {
3149  dtls_warn("cannot send CCS message\n");
3150  return err;
3151  }
3152 
3154 
3155  err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3156  if (err < 0) {
3157  dtls_warn("sending server Finished failed\n");
3158  return err;
3159  }
3160  }
3162  peer->handshake_params = NULL;
3163  dtls_debug("Handshake complete\n");
3164  check_stack();
3165  peer->state = DTLS_STATE_CONNECTED;
3166 
3167  /* return here to not increase the message receive counter */
3168  return err;
3169 
3170  /************************************************************************
3171  * Server states
3172  ************************************************************************/
3173 
3175  /* handle ClientHello, update msg and msglen and goto next if not finished */
3176 
3177  if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3179  }
3180 
3181  err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3182  if (err < 0) {
3183  dtls_warn("error in check_client_keyexchange err: %i\n", err);
3184  return err;
3185  }
3186  update_hs_hash(peer, data, data_length);
3187 
3191  else
3193  break;
3194 
3195 #ifdef DTLS_ECC
3197 
3198  if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
3200  }
3201 
3202  err = check_client_certificate_verify(ctx, peer, data, data_length);
3203  if (err < 0) {
3204  dtls_warn("error in check_client_certificate_verify err: %i\n", err);
3205  return err;
3206  }
3207 
3208  update_hs_hash(peer, data, data_length);
3210  break;
3211 #endif /* DTLS_ECC */
3212 
3213  case DTLS_HT_CLIENT_HELLO:
3214 
3215  if ((peer && state != DTLS_STATE_CONNECTED) ||
3216  (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
3218  }
3219 
3220  /* When no DTLS state exists for this peer, we only allow a
3221  Client Hello message with
3222 
3223  a) a valid cookie, or
3224  b) no cookie.
3225 
3226  Anything else will be rejected. Fragementation is not allowed
3227  here as it would require peer state as well.
3228  */
3229  err = dtls_verify_peer(ctx, peer, session, data, data_length);
3230  if (err < 0) {
3231  dtls_warn("error in dtls_verify_peer err: %i\n", err);
3232  return err;
3233  }
3234 
3235  if (err > 0) {
3236  dtls_debug("server hello verify was sent\n");
3237  break;
3238  }
3239 
3240  /* At this point, we have a good relationship with this peer. This
3241  * state is left for re-negotiation of key material. */
3242  if (!peer) {
3243  dtls_security_parameters_t *security;
3244 
3245  /* msg contains a Client Hello with a valid cookie, so we can
3246  * safely create the server state machine and continue with
3247  * the handshake. */
3248  peer = dtls_new_peer(session);
3249  if (!peer) {
3250  dtls_alert("cannot create peer\n");
3252  }
3253  peer->role = DTLS_SERVER;
3254 
3255  /* Initialize record sequence number to 1 for new peers. The first
3256  * record with sequence number 0 is a stateless Hello Verify Request.
3257  */
3258  security = dtls_security_params(peer);
3259  security->rseq = 1;
3260  dtls_add_peer(ctx, peer);
3261  }
3262  if (peer && !peer->handshake_params) {
3264 
3266  if (!peer->handshake_params)
3268 
3269  LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3270  peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
3271  peer->handshake_params->hs_state.mseq_s = 1;
3272  }
3273 
3274  clear_hs_hash(peer);
3275 
3276  /* First negotiation step: check for PSK
3277  *
3278  * Note that we already have checked that msg is a Handshake
3279  * message containing a ClientHello. dtls_get_cipher() therefore
3280  * does not check again.
3281  */
3282  err = dtls_update_parameters(ctx, peer, data, data_length);
3283  if (err < 0) {
3284  dtls_warn("error updating security parameters\n");
3285  return err;
3286  }
3287 
3288  /* update finish MAC */
3289  update_hs_hash(peer, data, data_length);
3290 
3291  err = dtls_send_server_hello_msgs(ctx, peer);
3292  if (err < 0) {
3293  return err;
3294  }
3298  else
3300 
3301  /* after sending the ServerHelloDone, we expect the
3302  * ClientKeyExchange (possibly containing the PSK id),
3303  * followed by a ChangeCipherSpec and an encrypted Finished.
3304  */
3305 
3306  break;
3307 
3308  case DTLS_HT_HELLO_REQUEST:
3309 
3310  if (state != DTLS_STATE_CONNECTED) {
3311  /* we should just ignore such packets when in handshake */
3312  return 0;
3313  }
3314 
3315  if (peer && !peer->handshake_params) {
3317  if (!peer->handshake_params)
3319 
3320  LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3321  peer->handshake_params->hs_state.mseq_r = 0;
3322  peer->handshake_params->hs_state.mseq_s = 0;
3323  }
3324 
3325  /* send ClientHello with empty Cookie */
3326  err = dtls_send_client_hello(ctx, peer, NULL, 0);
3327  if (err < 0) {
3328  dtls_warn("cannot send ClientHello\n");
3329  return err;
3330  }
3331  peer->state = DTLS_STATE_CLIENTHELLO;
3332  break;
3333 
3334  default:
3335  dtls_crit("unhandled message %d\n", data[0]);
3337  }
3338 
3339  if (peer && peer->handshake_params && err >= 0) {
3340  peer->handshake_params->hs_state.mseq_r++;
3341  }
3342 
3343  return err;
3344 }
3345 
3346 static int
3348  const dtls_peer_type role, const dtls_state_t state,
3349  uint8 *data, size_t data_length)
3350 {
3351  dtls_handshake_header_t *hs_header;
3352  int res;
3353 
3354  if (data_length < DTLS_HS_LENGTH) {
3355  dtls_warn("handshake message too short\n");
3357  }
3358  hs_header = DTLS_HANDSHAKE_HEADER(data);
3359 
3360  dtls_debug("received handshake packet of type: %s (%i)\n",
3361  dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
3362 
3363  if (!peer || !peer->handshake_params) {
3364  /* This is the initial ClientHello */
3365  if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
3366  dtls_warn("If there is no peer only ClientHello is allowed\n");
3368  }
3369 
3370  /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
3371  if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
3372  hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
3373  return handle_handshake_msg(ctx, peer, session, role, state, data,
3374  data_length);
3375  } else {
3376  dtls_warn("ignore unexpected handshake message\n");
3377  return 0;
3378  }
3379  }
3380 
3381  if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
3382  dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
3383  peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
3384  return 0;
3385  } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
3386  /* A packet in between is missing, buffer this packet. */
3387  netq_t *n;
3388 
3389  /* TODO: only add packet that are not too new. */
3390  if (data_length > DTLS_MAX_BUF) {
3391  dtls_warn("the packet is too big to buffer for reoder\n");
3392  return 0;
3393  }
3394 
3395  netq_t *node = netq_head(peer->handshake_params->reorder_queue);
3396  while (node) {
3397  dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
3398  if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
3399  dtls_warn("a packet with this sequence number is already stored\n");
3400  return 0;
3401  }
3402  node = netq_next(node);
3403  }
3404 
3405  n = netq_node_new(data_length);
3406  if (!n) {
3407  dtls_warn("no space in reoder buffer\n");
3408  return 0;
3409  }
3410 
3411  n->peer = peer;
3412  n->length = data_length;
3413  memcpy(n->data, data, data_length);
3414 
3415  if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
3416  dtls_warn("cannot add packet to reoder buffer\n");
3417  netq_node_free(n);
3418  }
3419  dtls_info("Added packet for reordering\n");
3420  return 0;
3421  } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
3422  /* Found the expected packet, use this and all the buffered packet */
3423  int next = 1;
3424 
3425  res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
3426  if (res < 0)
3427  return res;
3428 
3429  /* We do not know in which order the packet are in the list just search the list for every packet. */
3430  while (next && peer->handshake_params) {
3431  next = 0;
3432  netq_t *node = netq_head(peer->handshake_params->reorder_queue);
3433  while (node) {
3434  dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
3435 
3436  if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
3437  netq_remove(peer->handshake_params->reorder_queue, node);
3438  next = 1;
3439  res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
3440  if (res < 0) {
3441  return res;
3442  }
3443 
3444  break;
3445  } else {
3446  node = netq_next(node);
3447  }
3448  }
3449  }
3450  return res;
3451  }
3452  assert(0);
3453  return 0;
3454 }
3455 
3456 static int
3458  uint8 *record_header, uint8 *data, size_t data_length)
3459 {
3460  int err;
3461  dtls_handshake_parameters_t *handshake = peer->handshake_params;
3462 
3463  /* A CCS message is handled after a KeyExchange message was
3464  * received from the client. When security parameters have been
3465  * updated successfully and a ChangeCipherSpec message was sent
3466  * by ourself, the security context is switched and the record
3467  * sequence number is reset. */
3468 
3469  if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
3470  dtls_warn("expected ChangeCipherSpec during handshake\n");
3471  return 0;
3472  }
3473 
3474  if (data_length < 1 || data[0] != 1)
3476 
3477  /* Just change the cipher when we are on the same epoch */
3478  if (peer->role == DTLS_SERVER) {
3479  err = calculate_key_block(ctx, handshake, peer,
3480  &peer->session, peer->role);
3481  if (err < 0) {
3482  return err;
3483  }
3484  }
3485 
3487 
3488  return 0;
3489 }
3490 
3495 static int
3497  uint8 *record_header, uint8 *data, size_t data_length) {
3498  int free_peer = 0; /* indicates whether to free peer */
3499 
3500  if (data_length < 2)
3502 
3503  dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
3504 
3505  if (!peer) {
3506  dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
3507  return 0;
3508  }
3509 
3510  /* The peer object is invalidated for FATAL alerts and close
3511  * notifies. This is done in two steps.: First, remove the object
3512  * from our list of peers. After that, the event handler callback is
3513  * invoked with the still existing peer object. Finally, the storage
3514  * used by peer is released.
3515  */
3516  if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
3517  dtls_alert("%d invalidate peer\n", data[1]);
3518 
3519 #ifndef WITH_CONTIKI
3520  HASH_DEL_PEER(ctx->peers, peer);
3521 #else /* WITH_CONTIKI */
3522  list_remove(ctx->peers, peer);
3523 
3524 #ifndef NDEBUG
3525  PRINTF("removed peer [");
3526  PRINT6ADDR(&peer->session.addr);
3527  PRINTF("]:%d\n", uip_ntohs(peer->session.port));
3528 #endif
3529 #endif /* WITH_CONTIKI */
3530 
3531  free_peer = 1;
3532 
3533  }
3534 
3535  (void)CALL(ctx, event, &peer->session,
3536  (dtls_alert_level_t)data[0], (unsigned short)data[1]);
3537  switch (data[1]) {
3539  /* If state is DTLS_STATE_CLOSING, we have already sent a
3540  * close_notify so, do not send that again. */
3541  if (peer->state != DTLS_STATE_CLOSING) {
3542  peer->state = DTLS_STATE_CLOSING;
3544  } else
3545  peer->state = DTLS_STATE_CLOSED;
3546  break;
3547  default:
3548  ;
3549  }
3550 
3551  if (free_peer) {
3552  dtls_stop_retransmission(ctx, peer);
3553  dtls_destroy_peer(ctx, peer, 0);
3554  }
3555 
3556  return free_peer;
3557 }
3558 
3560  session_t *session, int err)
3561 {
3562  int level;
3563  int desc;
3564 
3565  if (err < -(1 << 8) && err > -(3 << 8)) {
3566  level = ((-err) & 0xff00) >> 8;
3567  desc = (-err) & 0xff;
3568  if (!peer) {
3569  peer = dtls_get_peer(ctx, session);
3570  }
3571  if (peer) {
3572  peer->state = DTLS_STATE_CLOSING;
3573  return dtls_send_alert(ctx, peer, level, desc);
3574  }
3575  } else if (err == -1) {
3576  if (!peer) {
3577  peer = dtls_get_peer(ctx, session);
3578  }
3579  if (peer) {
3580  peer->state = DTLS_STATE_CLOSING;
3582  }
3583  }
3584  return -1;
3585 }
3586 
3590 int
3592  session_t *session,
3593  uint8 *msg, int msglen) {
3594  dtls_peer_t *peer = NULL;
3595  unsigned int rlen; /* record length */
3596  uint8 *data; /* (decrypted) payload */
3597  int data_length; /* length of decrypted payload
3598  (without MAC and padding) */
3599  int err;
3600 
3601  /* check if we have DTLS state for addr/port/ifindex */
3602  peer = dtls_get_peer(ctx, session);
3603 
3604  if (!peer) {
3605  dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
3606  dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
3607  } else {
3608  dtls_debug("dtls_handle_message: FOUND PEER\n");
3609  }
3610 
3611  while ((rlen = is_record(msg,msglen))) {
3612  dtls_peer_type role;
3613  dtls_state_t state;
3614 
3615  dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
3616  if (peer) {
3617  data_length = decrypt_verify(peer, msg, rlen, &data);
3618  if (data_length < 0) {
3620  dtls_info("decrypt_verify() failed\n");
3621  if (peer->state < DTLS_STATE_CONNECTED) {
3622  dtls_alert_send_from_err(ctx, peer, &peer->session, err);
3623  peer->state = DTLS_STATE_CLOSED;
3624  /* dtls_stop_retransmission(ctx, peer); */
3625  dtls_destroy_peer(ctx, peer, 1);
3626  }
3627  return err;
3628  }
3629  role = peer->role;
3630  state = peer->state;
3631  } else {
3632  /* is_record() ensures that msg contains at least a record header */
3633  data = msg + DTLS_RH_LENGTH;
3634  data_length = rlen - DTLS_RH_LENGTH;
3636  role = DTLS_SERVER;
3637  }
3638 
3639  dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
3640  dtls_debug_hexdump("receive unencrypted", data, data_length);
3641 
3642  /* Handle received record according to the first byte of the
3643  * message, i.e. the subprotocol. We currently do not support
3644  * combining multiple fragments of one type into a single
3645  * record. */
3646 
3647  switch (msg[0]) {
3648 
3650  if (peer) {
3651  dtls_stop_retransmission(ctx, peer);
3652  }
3653  err = handle_ccs(ctx, peer, msg, data, data_length);
3654  if (err < 0) {
3655  dtls_warn("error while handling ChangeCipherSpec message\n");
3656  dtls_alert_send_from_err(ctx, peer, session, err);
3657 
3658  /* invalidate peer */
3659  dtls_destroy_peer(ctx, peer, 1);
3660  peer = NULL;
3661 
3662  return err;
3663  }
3664  break;
3665 
3666  case DTLS_CT_ALERT:
3667  if (peer) {
3668  dtls_stop_retransmission(ctx, peer);
3669  }
3670  err = handle_alert(ctx, peer, msg, data, data_length);
3671  if (err < 0 || err == 1) {
3672  dtls_warn("received alert, peer has been invalidated\n");
3673  /* handle alert has invalidated peer */
3674  peer = NULL;
3675  return err < 0 ?err:-1;
3676  }
3677  break;
3678 
3679  case DTLS_CT_HANDSHAKE:
3680  /* Handshake messages other than Finish must use the current
3681  * epoch, Finish has epoch + 1. */
3682 
3683  if (peer) {
3684  uint16_t expected_epoch = dtls_security_params(peer)->epoch;
3685  uint16_t msg_epoch =
3687 
3688  /* The new security parameters must be used for all messages
3689  * that are sent after the ChangeCipherSpec message. This
3690  * means that the client's Finished message uses epoch + 1
3691  * while the server is still in the old epoch.
3692  */
3693  if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
3694  expected_epoch++;
3695  }
3696 
3697  if (expected_epoch != msg_epoch) {
3698  dtls_warn("Wrong epoch, expected %i, got: %i\n",
3699  expected_epoch, msg_epoch);
3700  break;
3701  }
3702  }
3703 
3704  err = handle_handshake(ctx, peer, session, role, state, data, data_length);
3705  if (err < 0) {
3706  dtls_warn("error while handling handshake packet\n");
3707  dtls_alert_send_from_err(ctx, peer, session, err);
3708  return err;
3709  }
3710  if (peer && peer->state == DTLS_STATE_CONNECTED) {
3711  /* stop retransmissions */
3712  dtls_stop_retransmission(ctx, peer);
3713  CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
3714  }
3715  break;
3716 
3718  dtls_info("** application data:\n");
3719  if (!peer) {
3720  dtls_warn("no peer available, send an alert\n");
3721  // TODO: should we send a alert here?
3722  return -1;
3723  }
3724  dtls_stop_retransmission(ctx, peer);
3725  CALL(ctx, read, &peer->session, data, data_length);
3726  break;
3727  default:
3728  dtls_info("dropped unknown message of type %d\n",msg[0]);
3729  }
3730 
3731  /* advance msg by length of ciphertext */
3732  msg += rlen;
3733  msglen -= rlen;
3734  }
3735 
3736  return 0;
3737 }
3738 
3740 dtls_new_context(void *app_data) {
3741  dtls_context_t *c;
3742  dtls_tick_t now;
3743 #ifndef WITH_CONTIKI
3744  FILE *urandom = fopen("/dev/urandom", "r");
3745  unsigned char buf[sizeof(unsigned long)];
3746 #endif /* WITH_CONTIKI */
3747 
3748  dtls_ticks(&now);
3749 #ifdef WITH_CONTIKI
3750  /* FIXME: need something better to init PRNG here */
3751  dtls_prng_init(now);
3752 #else /* WITH_CONTIKI */
3753  if (!urandom) {
3754  dtls_emerg("cannot initialize PRNG\n");
3755  return NULL;
3756  }
3757 
3758  if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
3759  dtls_emerg("cannot initialize PRNG\n");
3760  return NULL;
3761  }
3762 
3763  fclose(urandom);
3764  dtls_prng_init((unsigned long)*buf);
3765 #endif /* WITH_CONTIKI */
3766 
3767  c = malloc_context();
3768  if (!c)
3769  goto error;
3770 
3771  memset(c, 0, sizeof(dtls_context_t));
3772  c->app = app_data;
3773 
3774  LIST_STRUCT_INIT(c, sendqueue);
3775 
3776 #ifdef WITH_CONTIKI
3777  LIST_STRUCT_INIT(c, peers);
3778  /* LIST_STRUCT_INIT(c, key_store); */
3779 
3780  process_start(&dtls_retransmit_process, (char *)c);
3781  PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
3782  /* the retransmit timer must be initialized to some large value */
3783  etimer_set(&c->retransmit_timer, 0xFFFF);
3784  PROCESS_CONTEXT_END(&coap_retransmit_process);
3785 #endif /* WITH_CONTIKI */
3786 
3788  c->cookie_secret_age = now;
3789  else
3790  goto error;
3791 
3792  return c;
3793 
3794  error:
3795  dtls_alert("cannot create DTLS context\n");
3796  if (c)
3797  dtls_free_context(c);
3798  return NULL;
3799 }
3800 
3801 void
3803  dtls_peer_t *p;
3804 
3805  if (!ctx) {
3806  return;
3807  }
3808 
3809 #ifndef WITH_CONTIKI
3810  dtls_peer_t *tmp;
3811 
3812  if (ctx->peers) {
3813  HASH_ITER(hh, ctx->peers, p, tmp) {
3814  dtls_destroy_peer(ctx, p, 1);
3815  }
3816  }
3817 #else /* WITH_CONTIKI */
3818  for (p = list_head(ctx->peers); p; p = list_item_next(p))
3819  dtls_destroy_peer(ctx, p, 1);
3820 #endif /* WITH_CONTIKI */
3821 
3822  free_context(ctx);
3823 }
3824 
3825 int
3827  int res;
3828 
3829  assert(peer);
3830  if (!peer)
3831  return -1;
3832 
3833  /* check if the same peer is already in our list */
3834  if (peer == dtls_get_peer(ctx, &peer->session)) {
3835  dtls_debug("found peer, try to re-connect\n");
3836  return dtls_renegotiate(ctx, &peer->session);
3837  }
3838 
3839  /* set local peer role to client, remote is server */
3840  peer->role = DTLS_CLIENT;
3841 
3842  dtls_add_peer(ctx, peer);
3843 
3844  /* send ClientHello with empty Cookie */
3846  if (!peer->handshake_params)
3847  return -1;
3848 
3849  peer->handshake_params->hs_state.mseq_r = 0;
3850  peer->handshake_params->hs_state.mseq_s = 0;
3851  LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3852  res = dtls_send_client_hello(ctx, peer, NULL, 0);
3853  if (res < 0)
3854  dtls_warn("cannot send ClientHello\n");
3855  else
3856  peer->state = DTLS_STATE_CLIENTHELLO;
3857 
3858  return res;
3859 }
3860 
3861 int
3863  dtls_peer_t *peer;
3864  int res;
3865 
3866  peer = dtls_get_peer(ctx, dst);
3867 
3868  if (!peer)
3869  peer = dtls_new_peer(dst);
3870 
3871  if (!peer) {
3872  dtls_crit("cannot create new peer\n");
3873  return -1;
3874  }
3875 
3876  res = dtls_connect_peer(ctx, peer);
3877 
3878  /* Invoke event callback to indicate connection attempt or
3879  * re-negotiation. */
3880  if (res > 0) {
3881  CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
3882  } else if (res == 0) {
3883  CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
3884  }
3885 
3886  return res;
3887 }
3888 
3889 static void
3891  if (!context || !node)
3892  return;
3893 
3894  /* re-initialize timeout when maximum number of retransmissions are not reached yet */
3896  unsigned char sendbuf[DTLS_MAX_BUF];
3897  size_t len = sizeof(sendbuf);
3898  int err;
3899  unsigned char *data = node->data;
3900  size_t length = node->length;
3901  dtls_tick_t now;
3903 
3904  dtls_ticks(&now);
3905  node->retransmit_cnt++;
3906  node->t = now + (node->timeout << node->retransmit_cnt);
3907  netq_insert_node(context->sendqueue, node);
3908 
3909  if (node->type == DTLS_CT_HANDSHAKE) {
3911 
3912  dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
3913  dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
3914  } else {
3915  dtls_debug("** retransmit packet\n");
3916  }
3917 
3918  err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
3919  1, sendbuf, &len);
3920  if (err < 0) {
3921  dtls_warn("can not retransmit packet, err: %i\n", err);
3922  return;
3923  }
3924  dtls_debug_hexdump("retransmit header", sendbuf,
3925  sizeof(dtls_record_header_t));
3926  dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
3927 
3928  (void)CALL(context, write, &node->peer->session, sendbuf, len);
3929  return;
3930  }
3931 
3932  /* no more retransmissions, remove node from system */
3933 
3934  dtls_debug("** removed transaction\n");
3935 
3936  /* And finally delete the node */
3937  netq_node_free(node);
3938 }
3939 
3940 static void
3942  netq_t *node;
3943  node = list_head(context->sendqueue);
3944 
3945  while (node) {
3946  if (dtls_session_equals(&node->peer->session, &peer->session)) {
3947  netq_t *tmp = node;
3948  node = list_item_next(node);
3949  list_remove(context->sendqueue, tmp);
3950  netq_node_free(tmp);
3951  } else
3952  node = list_item_next(node);
3953  }
3954 }
3955 
3956 void
3958  dtls_tick_t now;
3959  netq_t *node = netq_head(context->sendqueue);
3960 
3961  dtls_ticks(&now);
3962  while (node && node->t <= now) {
3963  netq_pop_first(context->sendqueue);
3964  dtls_retransmit(context, node);
3965  node = netq_head(context->sendqueue);
3966  }
3967 
3968  if (next && node)
3969  *next = node->t;
3970 }
3971 
3972 #ifdef WITH_CONTIKI
3973 /*---------------------------------------------------------------------------*/
3974 /* message retransmission */
3975 /*---------------------------------------------------------------------------*/
3976 PROCESS_THREAD(dtls_retransmit_process, ev, data)
3977 {
3978  clock_time_t now;
3979  netq_t *node;
3980 
3981  PROCESS_BEGIN();
3982 
3983  dtls_debug("Started DTLS retransmit process\r\n");
3984 
3985  while(1) {
3986  PROCESS_YIELD();
3987  if (ev == PROCESS_EVENT_TIMER) {
3988  if (etimer_expired(&the_dtls_context.retransmit_timer)) {
3989 
3990  node = list_head(the_dtls_context.sendqueue);
3991 
3992  now = clock_time();
3993  if (node && node->t <= now) {
3994  dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
3995  node = list_head(the_dtls_context.sendqueue);
3996  }
3997 
3998  /* need to set timer to some value even if no nextpdu is available */
3999  if (node) {
4000  etimer_set(&the_dtls_context.retransmit_timer,
4001  node->t <= now ? 1 : node->t - now);
4002  } else {
4003  etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4004  }
4005  }
4006  }
4007  }
4008 
4009  PROCESS_END();
4010 }
4011 #endif /* WITH_CONTIKI */
#define CALL(Context, which,...)
Definition: dtls.c:174
#define DTLS_SH_LENGTH
Definition: dtls.c:79
static void copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash)
Definition: dtls.c:1076
static int is_psk_supported(dtls_context_t *ctx)
Definition: dtls.c:481
unsigned char retransmit_cnt
Definition: netq.h:47
int dtls_connect(dtls_context_t *ctx, const session_t *dst)
Definition: dtls.c:3862
void dtls_handshake_free(dtls_handshake_parameters_t *handshake)
Definition: crypto.c:146
static int check_server_hello(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2460
int dtls_session_equals(const session_t *a, const session_t *b)
Definition: session.c:80
int dtls_handle_message(dtls_context_t *ctx, session_t *session, uint8 *msg, int msglen)
Definition: dtls.c:3591
#define DTLS_HT_SERVER_HELLO
Definition: dtls.h:344
unsigned char cookie_secret[DTLS_COOKIE_SECRET_LENGTH]
Definition: dtls.h:224
static void clear_hs_hash(dtls_peer_t *peer)
Definition: dtls.c:1087
dtls_hs_state_t hs_state
Definition: crypto.h:125
public tinydtls API
#define R_KEY_OFFSET
#define DTLS_CT_HANDSHAKE
Definition: dtls.h:327
static int dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length, unsigned char **result_r, unsigned char **result_s)
Definition: dtls.c:1611
static int dtls_update_parameters(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:900
#define dtls_kb_remote_iv(Param, Role)
Definition: crypto.h:172
static int check_server_hellodone(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2804
#define dtls_kb_local_iv(Param, Role)
Definition: crypto.h:176
void dtls_hmac_update(dtls_hmac_context_t *ctx, const unsigned char *input, size_t ilen)
Definition: hmac.c:76
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:398
#define LIST_STRUCT_INIT(struct_ptr, name)
Definition: t_list.h:90
static int dtls_alert_fatal_create(dtls_alert_t desc)
Definition: alert.h:77
static int dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type, uint8 *buf, size_t buflen)
Definition: dtls.c:200
const unsigned char * priv_key
Definition: dtls.h:65
int dtls_psk_pre_master_secret(unsigned char *key, size_t keylen, unsigned char *result, size_t result_len)
Definition: crypto.c:318
#define dtls_kb_server_mac_secret(Param, Role)
Definition: crypto.h:144
static void * list_pop(list_t list)
Definition: t_list.h:117
SHA256_CTX dtls_hash_ctx
Definition: hmac.h:38
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:524
static int dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer, const unsigned char *label, size_t labellen)
Definition: dtls.c:2277
dtls_cipher_t cipher
Definition: crypto.h:128
#define TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED
Definition: global.h:96
#define TLS_EXT_SERVER_CERTIFICATE_TYPE
Definition: global.h:89
dtls_state_t
Definition: state.h:40
#define DTLS_COOKIE_LENGTH
Definition: dtls.h:323
#define DTLS_CT_APPLICATION_DATA
Definition: dtls.h:328
#define DTLS_FIN_LENGTH
Definition: dtls.c:87
static uint8 * dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
Definition: dtls.c:1867
static int check_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2726
#define HASH_ITER(hh, head, el, tmp)
Definition: uthash.h:895
netq_t * netq_next(netq_t *p)
Definition: netq.c:88
#define DTLS_HT_FINISHED
Definition: dtls.h:352
struct dtls_handshake_parameters_t::@0::random_t random
#define DTLS_VERSION
Definition: dtls.h:56
static const unsigned char prf_label_client[]
Definition: dtls.c:119
dtls_peer_t * dtls_get_peer(const dtls_context_t *ctx, const session_t *session)
Definition: dtls.c:212
#define min(a, b)
Definition: debug.c:114
static int dtls_int_to_uint48(unsigned char *field, uint64_t value)
Definition: numeric.h:70
#define DTLS_SKEXECPSK_LENGTH_MAX
Definition: dtls.c:83
#define dtls_kb_size(Param, Role)
Definition: crypto.h:182
#define DTLS_HT_SERVER_KEY_EXCHANGE
Definition: dtls.h:347
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:1989
void dtls_clock_init(void)
Definition: dtls_time.c:54
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:446
clock_time_t dtls_tick_t
Definition: dtls_time.h:58
socklen_t size
Definition: session.h:50
unsigned char data[]
Definition: netq.h:51
static int verify_ext_ec_point_formats(uint8 *data, size_t data_length)
Definition: dtls.c:749
Definition: netq.h:38
static int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
Definition: dtls.c:491
#define dtls_get_fragment_length(H)
Definition: dtls.c:62
static int dtls_int_to_uint24(unsigned char *field, uint32_t value)
Definition: numeric.h:53
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:1323
dtls_record_header_t
Definition: dtls.h:338
static int handle_alert(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *record_header, uint8 *data, size_t data_length)
Definition: dtls.c:3496
#define DTLS_CKXPSK_LENGTH_MIN
Definition: dtls.c:84
netq_t * netq_node_new(size_t size)
Definition: netq.c:111
dtls_alert_level_t
Definition: alert.h:34
#define PRINTF(...)
Definition: debug.h:57
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:424
#define TLS_EXT_ELLIPTIC_CURVES_SECP256R1
Definition: global.h:94
dtls_state_t state
Definition: peer.h:62
static int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
Definition: dtls.c:461
clock_time_t cookie_secret_age
Definition: dtls.h:225
DTLS alert protocol.
#define DTLS_EVENT_CONNECT
Definition: alert.h:64
static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer)
Definition: dtls.c:3941
#define dtls_info(...)
Definition: debug.h:138
static void list_add(list_t list, void *item)
Definition: t_list.h:106
static dtls_security_parameters_t * dtls_security_params_epoch(dtls_peer_t *peer, uint16_t epoch)
Definition: peer.h:68
void crypto_init()
Definition: crypto.c:76
#define DTLS_HANDSHAKE_HEADER(M)
Definition: dtls.c:96
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:1485
#define TLS_EC_CURVE_TYPE_NAMED_CURVE
Definition: global.h:98
static int dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer, const dtls_ecdsa_key_t *key)
Definition: dtls.c:2241
static int check_client_certificate_verify(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:1691
dtls_peer_t * peers
Definition: dtls.h:228
#define dtls_kb_client_write_key(Param, Role)
Definition: crypto.h:155
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:425
session_t session
Definition: peer.h:59
static void * list_item_next(void *item)
Definition: t_list.h:137
uint32_t clock_time_t
Definition: dtls_time.h:55
int dtls_ec_key_from_uint32_asn1(const uint32_t *key, size_t key_size, unsigned char *buf)
Definition: crypto.c:362
unsigned char uint48[6]
Definition: global.h:51
union dtls_handshake_parameters_t::@1 keyx
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:503
#define TLS_EXT_SIG_HASH_ALGO_SHA256
Definition: global.h:102
unsigned int do_client_auth
Definition: crypto.h:129
union dtls_handshake_parameters_t::@0 tmp
#define dtls_kb_iv_size(Param, Role)
Definition: crypto.h:180
static int known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client)
Definition: dtls.c:522
#define DTLS_HMAC_DIGEST_SIZE
Definition: hmac.h:74
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:1924
static uint8_t dtls_uint8_to_int(const unsigned char *field)
Definition: numeric.h:94
static int dtls_verify_peer(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session, uint8 *data, size_t data_length)
Definition: dtls.c:1540
#define TLS_EXT_SIG_HASH_ALGO_ECDSA
Definition: global.h:103
dtls_handler_t * h
Definition: dtls.h:239
unsigned char uint24[3]
Definition: global.h:49
#define dtls_kb_remote_write_key(Param, Role)
Definition: crypto.h:159
#define HASH_DEL_PEER(head, delptr)
Definition: dtls.c:69
static void dtls_security_params_free_other(dtls_peer_t *peer)
Definition: peer.h:97
#define TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
Definition: global.h:100
static int dtls_alert_create(dtls_alert_level_t level, dtls_alert_t desc)
Definition: alert.h:71
static int dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2061
#define dtls_debug(...)
Definition: debug.h:139
#define DTLS_HT_SERVER_HELLO_DONE
Definition: dtls.h:349
static int dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:1736
#define DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
Definition: crypto.h:89
#define TLS_EXT_ELLIPTIC_CURVES
Definition: global.h:85
#define DTLS_CH_LENGTH_MAX
Definition: dtls.c:77
Clock Handling.
dtls_hash_ctx hs_hash
Definition: state.h:62
#define DTLS_SKEXECPSK_LENGTH_MIN
Definition: dtls.c:82
#define DTLS_COOKIE_LENGTH_MAX
Definition: dtls.c:76
clock_time_t t
Definition: netq.h:41
static int check_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2687
#define DTLS_HV_LENGTH
Definition: dtls.c:78
#define DTLS_CT_ALERT
Definition: dtls.h:326
#define MAX_KEYBLOCK_LENGTH
Definition: crypto.h:55
static void netq_init()
Definition: netq.h:58
static const unsigned char prf_label_finished[]
Definition: dtls.c:121
dtls_handshake_header_t
Definition: dtls.h:362
#define HASH_FIND_PEER(head, sess, out)
Definition: dtls.c:65
static int dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2164
#define TLS_EXT_ENCRYPT_THEN_MAC
Definition: global.h:90
static int dtls_check_tls_extension(dtls_peer_t *peer, uint8 *data, size_t data_length, int client_hello)
Definition: dtls.c:777
dtls_handshake_parameters_t * dtls_handshake_new()
Definition: crypto.c:123
#define dtls_alert(...)
Definition: debug.h:134
netq_t * netq_head(list_t queue)
Definition: netq.c:80
static int check_server_key_exchange_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2604
#define CLOCK_SECOND
Definition: dtls_time.h:52
void dtls_dsrv_log_addr(log_t level, const char *name, const session_t *addr)
Definition: debug.c:277
#define DTLS_RANDOM_LENGTH
Definition: crypto.h:60
void dtls_hmac_init(dtls_hmac_context_t *ctx, const unsigned char *key, size_t klen)
Definition: hmac.c:94
static void check_stack()
Definition: debug.h:59
#define TLS_EXT_EC_POINT_FORMATS
Definition: global.h:86
static int dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2948
dtls_handshake_parameters_t * handshake_params
Definition: peer.h:65
static void dtls_hash_init(dtls_hash_t ctx)
Definition: hmac.h:43
const unsigned char * pub_key_y
Definition: dtls.h:67
#define dtls_kb_mac_secret_size(Param, Role)
Definition: crypto.h:154
dtls_peer_t * peer
Definition: netq.h:44
static int check_client_keyexchange(dtls_context_t *ctx, dtls_handshake_parameters_t *handshake, uint8 *data, size_t length)
Definition: dtls.c:1005
int dtls_close(dtls_context_t *ctx, const session_t *remote)
Definition: dtls.c:1494
uint16_t epoch
Definition: netq.h:45
static int check_finished(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:1104
#define dtls_crit(...)
Definition: debug.h:135
static int verify_ext_eliptic_curves(uint8 *data, size_t data_length)
Definition: dtls.c:701
#define SKIP_VAR_FIELD(P, L, T)
Definition: dtls.c:106
#define DTLS_CE_LENGTH
Definition: dtls.c:80
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:599
#define DTLS_DEFAULT_MAX_RETRANSMIT
Definition: global.h:70
#define PRF_LABEL_SIZE(Label)
Definition: dtls.c:115
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:3347
#define DTLS_HT_CLIENT_HELLO
Definition: dtls.h:343
#define HASH_ADD_PEER(head, sess, add)
Definition: dtls.c:67
unsigned char uint8
Definition: global.h:47
dtls_compression_t compression
Definition: crypto.h:127
static uint8 * dtls_set_record_header(uint8 type, dtls_security_parameters_t *security, uint8 *buf)
Definition: dtls.c:390
static void dtls_retransmit(dtls_context_t *context, netq_t *node)
Definition: dtls.c:3890
static const unsigned char prf_label_key[]
Definition: dtls.c:118
int dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:3826
static int dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2073
#define DTLS_HT_CERTIFICATE_VERIFY
Definition: dtls.h:350
#define DTLS_EC_KEY_SIZE
Definition: crypto.h:309
static int dtls_int_to_uint16(unsigned char *field, uint16_t value)
Definition: numeric.h:46
static void dtls_hash_update(dtls_hash_t ctx, const unsigned char *input, size_t len)
Definition: hmac.h:48
union session_t::@2 addr
#define DTLS_HASH_CTX_SIZE
Definition: hmac.h:40
High level DTLS API and visible structures.
dtls_alert_t
Definition: alert.h:39
#define DTLS_HT_CERTIFICATE_REQUEST
Definition: dtls.h:348
#define dtls_debug_dump(name, buf, length)
Definition: debug.h:141
#define mycookie
#define DTLS_RH_LENGTH
Definition: dtls.c:73
int dtls_hmac_finalize(dtls_hmac_context_t *ctx, unsigned char *result)
Definition: hmac.c:127
const unsigned char * pub_key_x
Definition: dtls.h:66
static uint16_t dtls_uint16_to_int(const unsigned char *field)
Definition: numeric.h:99
static const unsigned char prf_label_master[]
Definition: dtls.c:117
#define dtls_get_epoch(H)
Definition: dtls.c:60
static dtls_security_parameters_t * dtls_security_params(dtls_peer_t *peer)
Definition: peer.h:79
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:463
unsigned int timeout
Definition: netq.h:42
#define dtls_kb_server_write_key(Param, Role)
Definition: crypto.h:157
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:483
netq_t * netq_pop_first(list_t queue)
Definition: netq.c:103
uint16_t mseq_r
Definition: state.h:56
uint8_t type
Definition: netq.h:46
#define dtls_kb_client_mac_secret(Param, Role)
Definition: crypto.h:143
static const unsigned char prf_label_server[]
Definition: dtls.c:120
int dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
Definition: dtls.c:2956
dtls_compression_t compression
Definition: crypto.h:100
static void * list_head(list_t list)
Definition: t_list.h:96
dtls_cipher_t cipher
Definition: crypto.h:102
#define DTLS_MASTER_SECRET_LENGTH
Definition: crypto.h:59
void dtls_free_peer(dtls_peer_t *peer)
Definition: peer.c:41
uint8 key_block[MAX_KEYBLOCK_LENGTH]
Definition: crypto.h:112
static void dtls_security_params_switch(dtls_peer_t *peer)
Definition: peer.h:109
void dtls_free_context(dtls_context_t *ctx)
Definition: dtls.c:3802
dtls_peer_type
Definition: peer.h:47
#define DTLS_HMAC_MAX
Definition: hmac.h:75
static int dtls_int_to_uint32(unsigned char *field, uint32_t value)
Definition: numeric.h:61
static void update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length)
Definition: dtls.c:1070
#define DTLS_CKXEC_LENGTH
Definition: dtls.c:85
static const unsigned char cert_asn1_header[]
Definition: dtls.c:124
dtls_context_t * dtls_new_context(void *app_data)
Definition: dtls.c:3740
static void list_remove(list_t list, void *item)
Definition: t_list.h:101
uint8 master_secret[DTLS_MASTER_SECRET_LENGTH]
Definition: crypto.h:122
#define A_DATA_LEN
static unsigned int is_record(uint8 *msg, size_t msglen)
Definition: dtls.c:361
#define DTLS_CV_LENGTH
Definition: dtls.c:86
static dtls_context_t * malloc_context()
Definition: dtls.c:152
#define DTLS_EVENT_CONNECTED
Definition: alert.h:65
#define dtls_warn(...)
Definition: debug.h:136
void netq_remove(list_t queue, netq_t *p)
Definition: netq.c:96
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:1361
#define PRF_LABEL(Label)
Definition: dtls.c:114
static int dtls_create_cookie(dtls_context_t *ctx, session_t *session, uint8 *msg, size_t msglen, uint8 *cookie, int *clen)
Definition: dtls.c:286
#define DTLS_RECORD_HEADER(M)
Definition: dtls.c:95
#define DTLS_HT_HELLO_REQUEST
Definition: dtls.h:342
dtls_cipher_t
Definition: global.h:74
#define DTLS_HT_HELLO_VERIFY_REQUEST
Definition: dtls.h:345
static void dtls_prng_init(unsigned short seed)
Definition: prng.h:40
static int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
Definition: dtls.c:503
#define DTLS_PSK_MAX_KEY_LEN
Definition: crypto.h:92
#define DTLS_CCM_BLOCKSIZE
Definition: ccm.h:33
static int check_server_hello_verify_request(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2530
static int check_server_certificate(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *data, size_t data_length)
Definition: dtls.c:2552
static int dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer, const dtls_ecdsa_key_t *key)
Definition: dtls.c:1834
static int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
Definition: dtls.c:471
#define dtls_kb_client_iv(Param, Role)
Definition: crypto.h:168
void dtls_init()
Definition: dtls.c:163
static int dtls_prng(unsigned char *buf, size_t len)
Definition: prng.h:33
void netq_node_free(netq_t *node)
Definition: netq.c:127
#define DTLS_MAX_BUF
Definition: global.h:64
static int equals(unsigned char *a, unsigned char *b, size_t len)
Definition: global.h:127
#define dtls_debug_hexdump(name, buf, length)
Definition: debug.h:140
#define dtls_kb_key_size(Param, Role)
Definition: crypto.h:167
static size_t dtls_hash_finalize(unsigned char *buf, dtls_hash_t ctx)
Definition: hmac.h:53
size_t length
Definition: netq.h:49
static int verify_ext_cert_type(uint8 *data, size_t data_length)
Definition: dtls.c:725
#define DTLS_SKEXEC_LENGTH
Definition: dtls.c:81
static dtls_security_parameters_t * dtls_security_params_next(dtls_peer_t *peer)
Definition: peer.h:84
static int dtls_int_to_uint8(unsigned char *field, uint8_t value)
Definition: numeric.h:40
void peer_init()
Definition: peer.c:31
unsigned char uint32[4]
Definition: global.h:50
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:1407
static int dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer, uint8 cookie[], size_t cookie_length)
Definition: dtls.c:2308
dtls_client_hello_t
Definition: dtls.h:373
static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
Definition: dtls.c:1508
static int dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2019
#define S_KEY_OFFSET(len_s)
static void dtls_debug_keyblock(dtls_security_parameters_t *config)
Definition: dtls.c:533
dtls_peer_t * dtls_new_peer(const session_t *session)
Definition: peer.c:72
void * app
Definition: dtls.h:237
#define DTLS_EVENT_RENEGOTIATE
Definition: alert.h:68
#define DTLS_HT_CERTIFICATE
Definition: dtls.h:346
dtls_hello_verify_t
Definition: dtls.h:380
int dtls_write(struct dtls_context_t *ctx, session_t *dst, uint8 *buf, size_t len)
Definition: dtls.c:236
#define TLS_CERT_TYPE_RAW_PUBLIC_KEY
Definition: global.h:92
#define DTLS_CH_LENGTH
Definition: dtls.c:75
static int dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie)
Definition: dtls.c:261
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:1180
#define DTLS_HT_CLIENT_KEY_EXCHANGE
Definition: dtls.h:351
void dtls_check_retransmit(dtls_context_t *context, clock_time_t *next)
Definition: dtls.c:3957
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:2992
#define DTLS_COOKIE_SECRET_LENGTH
Definition: dtls.h:71
#define dtls_kb_server_iv(Param, Role)
Definition: crypto.h:170
#define DTLS_HS_LENGTH
Definition: dtls.c:74
#define LOW(V)
Definition: dtls.c:93
static size_t finalize_hs_hash(dtls_peer_t *peer, uint8 *buf)
Definition: dtls.c:1082
static void dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:227
#define dtls_kb_local_write_key(Param, Role)
Definition: crypto.h:163
#define HIGH(V)
Definition: dtls.c:92
static char * dtls_handshake_type_to_name(int type)
Definition: dtls.c:565
unsigned char uint16[2]
Definition: global.h:48
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:249
int netq_insert_node(list_t queue, netq_t *node)
Definition: netq.c:61
#define DTLS_CT_CHANGE_CIPHER_SPEC
Definition: dtls.h:325
static uint32_t dtls_uint24_to_int(const unsigned char *field)
Definition: numeric.h:105
void dtls_ticks(dtls_tick_t *t)
Definition: dtls_time.c:67
static void free_context(dtls_context_t *context)
Definition: dtls.c:157
static uint8 compression_methods[]
Definition: dtls.c:456
static int dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer)
Definition: dtls.c:2156
static int handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer, uint8 *record_header, uint8 *data, size_t data_length)
Definition: dtls.c:3457
static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session, int err)
Definition: dtls.c:3559
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:550
#define dtls_emerg(...)
Definition: debug.h:133
dtls_peer_type role
Definition: peer.h:61
uint16_t mseq_s
Definition: state.h:55
static int decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length, uint8 **cleartext)
Definition: dtls.c:2877
#define TLS_EXT_CLIENT_CERTIFICATE_TYPE
Definition: global.h:88