1 /* dtls -- a very basic DTLS implementation
3 * Copyright (C) 2011--2012,2014 Olaf Bergmann <bergmann@tzi.org>
4 * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
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:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
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
28 #include "dtls_config.h"
29 #include "dtls_time.h"
39 #endif /* WITH_CONTIKI */
51 # include "sha2/sha2.h"
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))
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)
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 */
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
89 #define HS_HDR_LENGTH DTLS_RH_LENGTH + DTLS_HS_LENGTH
90 #define HV_HDR_LENGTH HS_HDR_LENGTH + DTLS_HV_LENGTH
92 #define HIGH(V) (((V) >> 8) & 0xff)
93 #define LOW(V) ((V) & 0xff)
95 #define DTLS_RECORD_HEADER(M) ((dtls_record_header_t *)(M))
96 #define DTLS_HANDSHAKE_HEADER(M) ((dtls_handshake_header_t *)(M))
98 #define HANDSHAKE(M) ((dtls_handshake_header_t *)((M) + DTLS_RH_LENGTH))
99 #define CLIENTHELLO(M) ((dtls_client_hello_t *)((M) + HS_HDR_LENGTH))
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!
106 #define SKIP_VAR_FIELD(P,L,T) { \
107 if (L < dtls_ ## T ## _to_int(P) + sizeof(T)) \
109 L -= dtls_ ## T ## _to_int(P) + sizeof(T); \
110 P += dtls_ ## T ## _to_int(P) + sizeof(T); \
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)
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";
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 */
136 PROCESS(dtls_retransmit_process, "DTLS retransmit process");
138 static dtls_context_t the_dtls_context;
140 static inline dtls_context_t *
142 return &the_dtls_context;
146 free_context(dtls_context_t *context) {
149 #else /* WITH_CONTIKI */
151 static inline dtls_context_t *
153 return (dtls_context_t *)malloc(sizeof(dtls_context_t));
157 free_context(dtls_context_t *context) {
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
174 #define CALL(Context, which, ...) \
175 ((Context)->h && (Context)->h->which \
176 ? (Context)->h->which((Context), ##__VA_ARGS__) \
180 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
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);
186 * Sends the fragment of length \p buflen given in \p buf to the
187 * specified \p peer. The data will be MAC-protected and encrypted
188 * according to the selected cipher and split into one or more DTLS
189 * records of the specified \p type. This function returns the number
190 * of bytes that were sent, or \c -1 if an error occurred.
192 * \param ctx The DTLS context to use.
193 * \param peer The remote peer.
194 * \param type The content type of the record.
195 * \param buf The data to send.
196 * \param buflen The actual length of \p buf.
197 * \return Less than zero on error, the number of bytes written otherwise.
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);
207 * Stops ongoing retransmissions of handshake messages for @p peer.
209 static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
212 dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
213 dtls_peer_t *p = NULL;
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))
221 #endif /* WITH_CONTIKI */
227 dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
229 HASH_ADD_PEER(ctx->peers, session, peer);
230 #else /* WITH_CONTIKI */
231 list_add(ctx->peers, peer);
232 #endif /* WITH_CONTIKI */
236 dtls_write(struct dtls_context_t *ctx,
237 session_t *dst, uint8 *buf, size_t len) {
239 dtls_peer_t *peer = dtls_get_peer(ctx, dst);
241 /* Check if peer connection already exists */
242 if (!peer) { /* no ==> create one */
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);
249 return (res >= 0) ? 0 : res;
250 } else { /* a session exists, check if it is in state connected */
252 if (peer->state != DTLS_STATE_CONNECTED) {
255 return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
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))
265 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
267 if (dtls_uint16_to_int(msg + DTLS_HS_LENGTH) != DTLS_VERSION)
268 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
270 msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
271 msg += DTLS_HS_LENGTH + DTLS_CH_LENGTH;
273 SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
275 if (msglen < (*msg & 0xff) + sizeof(uint8))
276 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
278 *cookie = msg + sizeof(uint8);
279 return dtls_uint8_to_int(msg);
282 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
286 dtls_create_cookie(dtls_context_t *ctx,
288 uint8 *msg, size_t msglen,
289 uint8 *cookie, int *clen) {
290 unsigned char buf[DTLS_HMAC_MAX];
293 /* create cookie with HMAC-SHA256 over:
295 * - session parameters (only IP address?)
297 * - random gmt and bytes
300 * - compression method
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()). */
309 dtls_hmac_context_t hmac_context;
310 dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
312 dtls_hmac_update(&hmac_context,
313 (unsigned char *)&session->addr, session->size);
315 /* feed in the beginning of the Client Hello up to and including the
317 e = sizeof(dtls_client_hello_t);
318 e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
319 if (e + DTLS_HS_LENGTH > msglen)
320 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
322 dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
324 /* skip cookie bytes and length byte */
325 e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
327 if (e + DTLS_HS_LENGTH > msglen)
328 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
330 dtls_hmac_update(&hmac_context,
331 msg + DTLS_HS_LENGTH + e,
332 dtls_get_fragment_length(DTLS_HANDSHAKE_HEADER(msg)) - e);
334 len = dtls_hmac_finalize(&hmac_context, buf);
337 memset(cookie + len, 0, *clen - len);
341 memcpy(cookie, buf, *clen);
345 #ifdef DTLS_CHECK_CONTENTTYPE
346 /* used to check if a received datagram contains a DTLS message */
347 static char const content_types[] = {
348 DTLS_CT_CHANGE_CIPHER_SPEC,
351 DTLS_CT_APPLICATION_DATA,
357 * Checks if \p msg points to a valid DTLS record. If
361 is_record(uint8 *msg, size_t msglen) {
362 unsigned int rlen = 0;
364 if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
365 #ifdef DTLS_CHECK_CONTENTTYPE
366 && strchr(content_types, msg[0])
368 && msg[1] == HIGH(DTLS_VERSION)
369 && msg[2] == LOW(DTLS_VERSION))
371 rlen = DTLS_RH_LENGTH +
372 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->length);
374 /* we do not accept wrong length field in record header */
383 * Initializes \p buf as record header. The caller must ensure that \p
384 * buf is capable of holding at least \c sizeof(dtls_record_header_t)
385 * bytes. Increments sequence number counter of \p security.
386 * \return pointer to the next byte after the written header.
387 * The length will be set to 0 and has to be changed before sending.
389 static inline uint8 *
390 dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
393 dtls_int_to_uint8(buf, type);
394 buf += sizeof(uint8);
396 dtls_int_to_uint16(buf, DTLS_VERSION);
397 buf += sizeof(uint16);
400 dtls_int_to_uint16(buf, security->epoch);
401 buf += sizeof(uint16);
403 dtls_int_to_uint48(buf, security->rseq);
404 buf += sizeof(uint48);
406 /* increment record sequence counter by 1 */
409 memset(buf, 0, sizeof(uint16) + sizeof(uint48));
410 buf += sizeof(uint16) + sizeof(uint48);
413 memset(buf, 0, sizeof(uint16));
414 return buf + sizeof(uint16);
418 * Initializes \p buf as handshake header. The caller must ensure that \p
419 * buf is capable of holding at least \c sizeof(dtls_handshake_header_t)
420 * bytes. Increments message sequence number counter of \p peer.
421 * \return pointer to the next byte after \p buf
423 static inline uint8 *
424 dtls_set_handshake_header(uint8 type, dtls_peer_t *peer,
426 int frag_offset, int frag_length,
429 dtls_int_to_uint8(buf, type);
430 buf += sizeof(uint8);
432 dtls_int_to_uint24(buf, length);
433 buf += sizeof(uint24);
435 if (peer && peer->handshake_params) {
436 /* and copy the result to buf */
437 dtls_int_to_uint16(buf, peer->handshake_params->hs_state.mseq_s);
439 /* increment handshake message sequence counter by 1 */
440 peer->handshake_params->hs_state.mseq_s++;
442 memset(buf, 0, sizeof(uint16));
444 buf += sizeof(uint16);
446 dtls_int_to_uint24(buf, frag_offset);
447 buf += sizeof(uint24);
449 dtls_int_to_uint24(buf, frag_length);
450 buf += sizeof(uint24);
455 /** only one compression method is currently defined */
456 static uint8 compression_methods[] = {
460 /** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
461 static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
464 return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
467 #endif /* DTLS_ECC */
470 /** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
471 static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
474 return cipher == TLS_PSK_WITH_AES_128_CCM_8;
477 #endif /* DTLS_PSK */
480 /** returns true if the application is configured for psk */
481 static inline int is_psk_supported(dtls_context_t *ctx)
484 return ctx && ctx->h && ctx->h->get_psk_info;
487 #endif /* DTLS_PSK */
490 /** returns true if the application is configured for ecdhe_ecdsa */
491 static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
494 return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
495 (is_client && ctx->h->verify_ecdsa_key));
498 #endif /* DTLS_ECC */
501 /** Returns true if the application is configured for ecdhe_ecdsa with
502 * client authentication */
503 static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
506 return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
509 #endif /* DTLS_ECC */
513 * Returns @c 1 if @p code is a cipher suite other than @c
514 * TLS_NULL_WITH_NULL_NULL that we recognize.
516 * @param ctx The current DTLS context
517 * @param code The cipher suite identifier to check
518 * @param is_client 1 for a dtls client, 0 for server
519 * @return @c 1 iff @p code is recognized,
522 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
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));
532 /** Dump out the cipher keys and IVs used for the symetric cipher. */
533 static void dtls_debug_keyblock(dtls_security_parameters_t *config)
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));
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));
544 dtls_debug_dump(" client_write_key",
545 dtls_kb_client_write_key(config, peer->role),
546 dtls_kb_key_size(config, peer->role));
548 dtls_debug_dump(" server_write_key",
549 dtls_kb_server_write_key(config, peer->role),
550 dtls_kb_key_size(config, peer->role));
552 dtls_debug_dump(" client_IV",
553 dtls_kb_client_iv(config, peer->role),
554 dtls_kb_iv_size(config, peer->role));
556 dtls_debug_dump(" server_IV",
557 dtls_kb_server_iv(config, peer->role),
558 dtls_kb_iv_size(config, peer->role));
561 /** returns the name of the goven handshake type number.
562 * see IANA for a full list of types:
563 * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
565 static char *dtls_handshake_type_to_name(int type)
568 case DTLS_HT_HELLO_REQUEST:
569 return "hello_request";
570 case DTLS_HT_CLIENT_HELLO:
571 return "client_hello";
572 case DTLS_HT_SERVER_HELLO:
573 return "server_hello";
574 case DTLS_HT_HELLO_VERIFY_REQUEST:
575 return "hello_verify_request";
576 case DTLS_HT_CERTIFICATE:
577 return "certificate";
578 case DTLS_HT_SERVER_KEY_EXCHANGE:
579 return "server_key_exchange";
580 case DTLS_HT_CERTIFICATE_REQUEST:
581 return "certificate_request";
582 case DTLS_HT_SERVER_HELLO_DONE:
583 return "server_hello_done";
584 case DTLS_HT_CERTIFICATE_VERIFY:
585 return "certificate_verify";
586 case DTLS_HT_CLIENT_KEY_EXCHANGE:
587 return "client_key_exchange";
588 case DTLS_HT_FINISHED:
596 * Calculate the pre master secret and after that calculate the master-secret.
599 calculate_key_block(dtls_context_t *ctx,
600 dtls_handshake_parameters_t *handshake,
603 dtls_peer_type role) {
604 unsigned char *pre_master_secret;
605 int pre_master_len = 0;
606 dtls_security_parameters_t *security = dtls_security_params_next(peer);
607 uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
610 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
613 pre_master_secret = security->key_block;
615 switch (handshake->cipher) {
617 case TLS_PSK_WITH_AES_128_CCM_8: {
618 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
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);
626 dtls_crit("no psk key for session available\n");
629 /* Temporarily use the key_block storage space for the pre master secret. */
630 pre_master_len = dtls_psk_pre_master_secret(psk, len,
632 MAX_KEYBLOCK_LENGTH);
634 dtls_debug_hexdump("psk", psk, len);
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");
639 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
644 #endif /* DTLS_PSK */
646 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: {
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),
652 MAX_KEYBLOCK_LENGTH);
653 if (pre_master_len < 0) {
654 dtls_crit("the curve was too long, for the pre master secret\n");
655 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
659 #endif /* DTLS_ECC */
661 dtls_crit("calculate_key_block: unknown cipher\n");
662 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
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);
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,
674 DTLS_MASTER_SECRET_LENGTH);
676 dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
678 /* create key_block from master_secret
679 * key_block = PRF(master_secret,
680 "key expansion" + tmp.random.server + tmp.random.client) */
682 dtls_prf(master_secret,
683 DTLS_MASTER_SECRET_LENGTH,
684 PRF_LABEL(key), PRF_LABEL_SIZE(key),
685 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
686 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
688 dtls_kb_size(security, role));
690 memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
691 dtls_debug_keyblock(security);
693 security->cipher = handshake->cipher;
694 security->compression = handshake->compression;
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) {
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");
709 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
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);
717 if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
721 dtls_warn("no supported elliptic curve found\n");
722 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
725 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
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");
733 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
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);
741 if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
745 dtls_warn("no supported certificate type found\n");
746 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
749 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
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");
757 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
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);
765 if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
769 dtls_warn("no supported ec_point_format found\n");
770 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
774 * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
777 dtls_check_tls_extension(dtls_peer_t *peer,
778 uint8 *data, size_t data_length, int client_hello)
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;
785 dtls_handshake_parameters_t *handshake = peer->handshake_params;
787 if (data_length < sizeof(uint16)) {
788 /* no tls extensions specified */
789 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
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);
803 /* check for TLS extensions needed for this cipher */
804 while (data_length) {
805 if (data_length < sizeof(uint16) * 2)
808 /* get the tls extension type */
809 i = dtls_uint16_to_int(data);
810 data += sizeof(uint16);
811 data_length -= sizeof(uint16);
813 /* get the length of the tls extension */
814 j = dtls_uint16_to_int(data);
815 data += sizeof(uint16);
816 data_length -= sizeof(uint16);
822 case TLS_EXT_ELLIPTIC_CURVES:
823 ext_elliptic_curve = 1;
824 if (verify_ext_eliptic_curves(data, j))
827 case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
828 ext_client_cert_type = 1;
830 if (verify_ext_cert_type(data, j))
833 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
837 case TLS_EXT_SERVER_CERTIFICATE_TYPE:
838 ext_server_cert_type = 1;
840 if (verify_ext_cert_type(data, j))
843 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
847 case TLS_EXT_EC_POINT_FORMATS:
848 ext_ec_point_formats = 1;
849 if (verify_ext_ec_point_formats(data, j))
852 case TLS_EXT_ENCRYPT_THEN_MAC:
853 /* As only AEAD cipher suites are currently available, this
854 * extension can be skipped.
856 dtls_info("skipped encrypt-then-mac extension\n");
859 dtls_warn("unsupported tls extension: %i\n", i);
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");
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");
880 if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
881 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
883 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
888 * Parses the ClientHello from the client and updates the internal handshake
889 * parameters with the new data for the given \p peer. When the ClientHello
890 * handshake message in \p data does not contain a cipher suite or
891 * compression method, it is copied from the the current security parameters.
893 * \param ctx The current DTLS context.
894 * \param peer The remote peer whose security parameters are about to change.
895 * \param data The handshake message with a ClientHello.
896 * \param data_length The actual size of \p data.
897 * \return \c -Something if an error occurred, \c 0 on success.
900 dtls_update_parameters(dtls_context_t *ctx,
902 uint8 *data, size_t data_length) {
905 dtls_handshake_parameters_t *config = peer->handshake_params;
906 dtls_security_parameters_t *security = dtls_security_params(peer);
909 assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
911 /* skip the handshake header and client version information */
912 data += DTLS_HS_LENGTH + sizeof(uint16);
913 data_length -= DTLS_HS_LENGTH + sizeof(uint16);
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;
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 */
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. */
929 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
932 config->cipher = security->cipher;
933 config->compression = security->compression;
938 data += sizeof(uint16);
939 data_length -= sizeof(uint16) + i;
943 config->cipher = dtls_uint16_to_int(data);
944 ok = known_cipher(ctx, config->cipher, 0);
946 data += sizeof(uint16);
949 /* skip remaining ciphers */
953 /* reset config cipher to a well-defined value */
954 config->cipher = TLS_NULL_WITH_NULL_NULL;
955 dtls_warn("No matching cipher found\n");
959 if (data_length < sizeof(uint8)) {
960 /* no compression specified, take the current compression method */
962 config->compression = security->compression;
964 config->compression = TLS_COMPRESSION_NULL;
968 i = dtls_uint8_to_int(data);
969 if (data_length < i + sizeof(uint8))
972 data += sizeof(uint8);
973 data_length -= sizeof(uint8) + i;
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];
983 data += sizeof(uint8);
987 /* reset config cipher to a well-defined value */
991 return dtls_check_tls_extension(peer, data, data_length, 1);
993 if (peer->state == DTLS_STATE_CONNECTED) {
994 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
996 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1001 * Parse the ClientKeyExchange and update the internal handshake state with
1005 check_client_keyexchange(dtls_context_t *ctx,
1006 dtls_handshake_parameters_t *handshake,
1007 uint8 *data, size_t length) {
1010 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
1012 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1013 dtls_debug("The client key exchange is too short\n");
1014 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1016 data += DTLS_HS_LENGTH;
1018 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1019 dtls_alert("expected 65 bytes long public point\n");
1020 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1022 data += sizeof(uint8);
1024 if (dtls_uint8_to_int(data) != 4) {
1025 dtls_alert("expected uncompressed public point\n");
1026 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1028 data += sizeof(uint8);
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);
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);
1038 #endif /* DTLS_ECC */
1040 if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1043 if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1044 dtls_debug("The client key exchange is too short\n");
1045 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1047 data += DTLS_HS_LENGTH;
1049 id_length = dtls_uint16_to_int(data);
1050 data += sizeof(uint16);
1052 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1053 dtls_debug("The identity has a wrong length\n");
1054 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1057 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1058 dtls_warn("please use a smaller client identity\n");
1059 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1062 handshake->keyx.psk.id_length = id_length;
1063 memcpy(handshake->keyx.psk.identity, data, id_length);
1065 #endif /* DTLS_PSK */
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);
1076 copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
1077 memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1078 sizeof(peer->handshake_params->hs_state.hs_hash));
1081 static inline size_t
1082 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
1083 return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1087 clear_hs_hash(dtls_peer_t *peer) {
1089 dtls_debug("clear MAC\n");
1090 dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
1094 * Checks if \p record + \p data contain a Finished message with valid
1097 * \param ctx The current DTLS context.
1098 * \param peer The remote peer of the security association.
1099 * \param data The cleartext payload of the message.
1100 * \param data_length Actual length of \p data.
1101 * \return \c 0 if the Finished message is valid, \c negative number otherwise.
1104 check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
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];
1110 if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1111 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
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.
1118 unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1119 unsigned char verify_data[DTLS_FIN_LENGTH];
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);
1125 digest_length = finalize_hs_hash(peer, buf);
1128 /* restore hash status */
1129 memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
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);
1139 dtls_prf(peer->handshake_params->tmp.master_secret,
1140 DTLS_MASTER_SECRET_LENGTH,
1142 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1144 b.verify_data, sizeof(b.verify_data));
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));
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))
1152 : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
1156 * Prepares the payload given in \p data for sending with
1157 * dtls_send(). The \p data is encrypted and compressed according to
1158 * the current security parameters of \p peer. The result of this
1159 * operation is put into \p sendbuf with a prepended record header of
1160 * type \p type ready for sending. As some cipher suites add a MAC
1161 * before encryption, \p data must be large enough to hold this data
1162 * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
1164 * \param peer The remote peer the packet will be sent to.
1165 * \param security The encryption paramater used to encrypt
1166 * \param type The content type of this record.
1167 * \param data_array Array with payloads in correct order.
1168 * \param data_len_array sizes of the payloads in correct order.
1169 * \param data_array_len The number of payloads given.
1170 * \param sendbuf The output buffer where the encrypted record
1172 * \param rlen This parameter must be initialized with the
1173 * maximum size of \p sendbuf and will be updated
1174 * to hold the actual size of the stored packet
1175 * on success. On error, the value of \p rlen is
1177 * \return Less than zero on error, or greater than zero success.
1180 dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
1182 uint8 *data_array[], size_t data_len_array[],
1183 size_t data_array_len,
1184 uint8 *sendbuf, size_t *rlen) {
1189 if (*rlen < DTLS_RH_LENGTH) {
1190 dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1191 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1194 p = dtls_set_record_header(type, security, sendbuf);
1197 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1198 /* no cipher suite */
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");
1205 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1208 memcpy(p, data_array[i], data_len_array[i]);
1209 p += data_len_array[i];
1210 res += data_len_array[i];
1212 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1214 * length of additional_data for the AEAD cipher which consists of
1215 * seq_num(2+6) + type(1) + version(2) + length(2)
1217 #define A_DATA_LEN 13
1218 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1219 unsigned char A_DATA[A_DATA_LEN];
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");
1226 dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
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]).
1238 opaque nonce_explicit[8];
1243 In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1246 When the nonce_explicit is equal to the sequence number, the CCMNonce
1247 will have the structure of the CCMNonceExample given below.
1250 uint32 client_write_IV; // low order 32-bits
1251 uint64 seq_num; // TLS sequence number
1256 uint32 server_write_IV; // low order 32-bits
1257 uint64 seq_num; // TLS sequence number
1269 memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
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");
1277 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1280 memcpy(p, data_array[i], data_len_array[i]);
1281 p += data_len_array[i];
1282 res += data_len_array[i];
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 */
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));
1294 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1296 * additional_data = seq_num + TLSCompressed.type +
1297 * TLSCompressed.version + TLSCompressed.length;
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 */
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);
1311 res += 8; /* increment res by size of nonce_explicit */
1312 dtls_debug_dump("message:", start, res);
1315 /* fix length of fragment in sendbuf */
1316 dtls_int_to_uint16(sendbuf + 11, res);
1318 *rlen = DTLS_RH_LENGTH + res;
1323 dtls_send_handshake_msg_hash(dtls_context_t *ctx,
1327 uint8 *data, size_t data_length,
1330 uint8 buf[DTLS_HS_LENGTH];
1331 uint8 *data_array[2];
1332 size_t data_len_array[2];
1334 dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1336 dtls_set_handshake_header(header_type, peer, data_length, 0,
1340 update_hs_hash(peer, buf, sizeof(buf));
1342 data_array[i] = buf;
1343 data_len_array[i] = sizeof(buf);
1348 update_hs_hash(peer, data, data_length);
1350 data_array[i] = data;
1351 data_len_array[i] = data_length;
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);
1361 dtls_send_handshake_msg(dtls_context_t *ctx,
1364 uint8 *data, size_t data_length)
1366 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1367 header_type, data, data_length, 1);
1371 * Returns true if the message @p Data is a handshake message that
1372 * must be included in the calculation of verify_data in the Finished
1375 * @param Type The message type. Only handshake messages but the initial
1376 * Client Hello and Hello Verify Request are included in the hash,
1377 * @param Data The PDU to examine.
1378 * @param Length The length of @p Data.
1380 * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
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)))))
1394 * Sends the data passed in @p buf as a DTLS record of type @p type to
1395 * the given peer. The data will be encrypted and compressed according
1396 * to the security parameters for @p peer.
1398 * @param ctx The DTLS context in effect.
1399 * @param peer The remote party where the packet is sent.
1400 * @param type The content type of this record.
1401 * @param buf The data to send.
1402 * @param buflen The number of bytes to send from @p buf.
1403 * @return Less than zero in case of an error or the number of
1404 * bytes that have been sent otherwise.
1407 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
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)
1412 /* We cannot use ctx->sendbuf here as it is reserved for collecting
1413 * the input for this function, i.e. buf == ctx->sendbuf.
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);
1422 size_t overall_len = 0;
1424 res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1429 /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1430 /* update_hs_hash(peer, buf, buflen); */
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];
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);
1445 n->t = now + 2 * CLOCK_SECOND;
1446 n->retransmit_cnt = 0;
1447 n->timeout = 2 * CLOCK_SECOND;
1449 n->epoch = (security) ? security->epoch : 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];
1457 if (!netq_insert_node(ctx->sendqueue, n)) {
1458 dtls_warn("cannot add packet to retransmit buffer\n");
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 */
1471 dtls_warn("retransmit buffer full\n");
1474 /* FIXME: copy to peer's sendqueue (after fragmentation if
1475 * necessary) and initialize retransmit timer */
1476 res = CALL(ctx, write, session, sendbuf, len);
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);
1485 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
1486 dtls_alert_t description) {
1487 uint8_t msg[] = { level, description };
1489 dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1494 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1498 peer = dtls_get_peer(ctx, remote);
1501 res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
1502 /* indicate tear down */
1503 peer->state = DTLS_STATE_CLOSING;
1508 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1510 if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1511 dtls_close(ctx, &peer->session);
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 */
1519 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1521 dtls_free_peer(peer);
1525 * Checks a received Client Hello message for a valid cookie. When the
1526 * Client Hello contains no cookie, the function fails and a Hello
1527 * Verify Request is sent to the peer (using the write callback function
1528 * registered with \p ctx). The return value is \c -1 on error, \c 0 when
1529 * undecided, and \c 1 if the Client Hello was good.
1531 * \param ctx The DTLS context.
1532 * \param peer The remote party we are talking to, if any.
1533 * \param session Transport address of the remote peer.
1534 * \param msg The received datagram.
1535 * \param msglen Length of \p msg.
1536 * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
1540 dtls_verify_peer(dtls_context_t *ctx,
1543 uint8 *data, size_t data_length)
1545 uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
1547 int len = DTLS_COOKIE_LENGTH;
1548 uint8 *cookie = NULL;
1551 #define mycookie (buf + DTLS_HV_LENGTH)
1553 /* Store cookie where we can reuse it for the HelloVerify request. */
1554 err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1558 dtls_debug_dump("create cookie", mycookie, len);
1560 assert(len == DTLS_COOKIE_LENGTH);
1562 /* Perform cookie check. */
1563 len = dtls_get_cookie(data, data_length, &cookie);
1565 dtls_warn("error while fetching the cookie, err: %i\n", err);
1569 dtls_debug_dump("compare with cookie", cookie, len);
1571 /* check if cookies match */
1572 if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1573 dtls_debug("found matching cookie\n");
1578 dtls_debug_dump("invalid cookie", cookie, len);
1580 dtls_debug("cookie len is 0!\n");
1583 /* ClientHello did not contain any valid cookie, hence we send a
1584 * HelloVerify request. */
1586 dtls_int_to_uint16(p, DTLS_VERSION);
1587 p += sizeof(uint16);
1589 dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
1592 assert(p == mycookie);
1594 p += DTLS_COOKIE_LENGTH;
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,
1599 DTLS_HT_HELLO_VERIFY_REQUEST,
1602 dtls_warn("cannot send HelloVerify request\n");
1604 return err; /* HelloVerify is sent, now we cannot do anything but wait */
1611 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1612 unsigned char **result_r,
1613 unsigned char **result_s)
1616 uint8 *data_orig = data;
1618 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
1619 dtls_alert("only sha256 is supported in certificate verify\n");
1620 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1622 data += sizeof(uint8);
1623 data_length -= sizeof(uint8);
1625 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
1626 dtls_alert("only ecdsa signature is supported in client verify\n");
1627 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1629 data += sizeof(uint8);
1630 data_length -= sizeof(uint8);
1632 if (data_length < dtls_uint16_to_int(data)) {
1633 dtls_alert("signature length wrong\n");
1634 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1636 data += sizeof(uint16);
1637 data_length -= sizeof(uint16);
1639 if (dtls_uint8_to_int(data) != 0x30) {
1640 dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1641 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1643 data += sizeof(uint8);
1644 data_length -= sizeof(uint8);
1646 if (data_length < dtls_uint8_to_int(data)) {
1647 dtls_alert("signature length wrong\n");
1648 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1650 data += sizeof(uint8);
1651 data_length -= sizeof(uint8);
1653 if (dtls_uint8_to_int(data) != 0x02) {
1654 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1655 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1657 data += sizeof(uint8);
1658 data_length -= sizeof(uint8);
1660 i = dtls_uint8_to_int(data);
1661 data += sizeof(uint8);
1662 data_length -= sizeof(uint8);
1664 /* Sometimes these values have a leeding 0 byte */
1665 *result_r = data + i - DTLS_EC_KEY_SIZE;
1670 if (dtls_uint8_to_int(data) != 0x02) {
1671 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1672 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1674 data += sizeof(uint8);
1675 data_length -= sizeof(uint8);
1677 i = dtls_uint8_to_int(data);
1678 data += sizeof(uint8);
1679 data_length -= sizeof(uint8);
1681 /* Sometimes these values have a leeding 0 byte */
1682 *result_s = data + i - DTLS_EC_KEY_SIZE;
1687 return data - data_orig;
1691 check_client_certificate_verify(dtls_context_t *ctx,
1693 uint8 *data, size_t data_length)
1695 dtls_handshake_parameters_t *config = peer->handshake_params;
1697 unsigned char *result_r;
1698 unsigned char *result_s;
1699 dtls_hash_ctx hs_hash;
1700 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1702 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
1704 data += DTLS_HS_LENGTH;
1706 if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1707 dtls_alert("the packet length does not match the expected\n");
1708 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1711 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
1718 copy_hs_hash(peer, &hs_hash);
1720 dtls_hash_finalize(sha256hash, &hs_hash);
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);
1728 dtls_alert("wrong signature err: %i\n", ret);
1729 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1733 #endif /* DTLS_ECC */
1736 dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
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];
1744 uint8 extension_size;
1745 dtls_handshake_parameters_t *handshake = peer->handshake_params;
1748 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
1750 extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
1752 /* Handshake header */
1756 dtls_int_to_uint16(p, DTLS_VERSION);
1757 p += sizeof(uint16);
1759 /* Set server random: First 4 bytes are the server's Unix timestamp,
1760 * followed by 28 bytes of generate random data. */
1762 dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
1763 dtls_prng(handshake->tmp.random.server + 4, 28);
1765 memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
1766 p += DTLS_RANDOM_LENGTH;
1768 *p++ = 0; /* no session id */
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);
1775 /* selected compression method */
1776 *p++ = compression_methods[handshake->compression];
1779 if (extension_size) {
1780 /* length of the extensions */
1781 dtls_int_to_uint16(p, extension_size - 2);
1782 p += sizeof(uint16);
1786 /* client certificate type extension */
1787 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
1788 p += sizeof(uint16);
1790 /* length of this extension type */
1791 dtls_int_to_uint16(p, 1);
1792 p += sizeof(uint16);
1794 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
1797 /* client certificate type extension */
1798 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
1799 p += sizeof(uint16);
1801 /* length of this extension type */
1802 dtls_int_to_uint16(p, 1);
1803 p += sizeof(uint16);
1805 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
1808 /* ec_point_formats */
1809 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
1810 p += sizeof(uint16);
1812 /* length of this extension type */
1813 dtls_int_to_uint16(p, 2);
1814 p += sizeof(uint16);
1816 /* number of supported formats */
1817 dtls_int_to_uint8(p, 1);
1820 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
1824 assert(p - buf <= sizeof(buf));
1826 /* TODO use the same record sequence number as in the ClientHello,
1827 see 4.2.1. Denial-of-Service Countermeasures */
1828 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
1834 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
1835 const dtls_ecdsa_key_t *key)
1837 uint8 buf[DTLS_CE_LENGTH];
1842 * Start message construction at beginning of buffer. */
1845 dtls_int_to_uint24(p, 94); /* certificates length */
1846 p += sizeof(uint24);
1848 dtls_int_to_uint24(p, 91); /* length of this certificate */
1849 p += sizeof(uint24);
1851 memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
1852 p += sizeof(cert_asn1_header);
1854 memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
1855 p += DTLS_EC_KEY_SIZE;
1857 memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
1858 p += DTLS_EC_KEY_SIZE;
1860 assert(p - buf <= sizeof(buf));
1862 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
1867 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
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 */
1875 len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
1876 len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
1882 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
1886 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
1889 /* length of signature */
1890 dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
1891 p += sizeof(uint16);
1893 /* ASN.1 SEQUENCE */
1894 dtls_int_to_uint8(p, 0x30);
1897 dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
1900 /* ASN.1 Integer r */
1901 dtls_int_to_uint8(p, 0x02);
1904 dtls_int_to_uint8(p, len_r);
1907 /* the pint r was added here */
1910 /* ASN.1 Integer s */
1911 dtls_int_to_uint8(p, 0x02);
1914 dtls_int_to_uint8(p, len_s);
1917 /* the pint s was added here */
1924 dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
1925 const dtls_ecdsa_key_t *key)
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];
1932 uint8 *ephemeral_pub_x;
1933 uint8 *ephemeral_pub_y;
1934 uint32_t point_r[9];
1935 uint32_t point_s[9];
1936 dtls_handshake_parameters_t *config = peer->handshake_params;
1938 /* ServerKeyExchange
1940 * Start message construction at beginning of buffer. */
1944 /* ECCurveType curve_type: named_curve */
1945 dtls_int_to_uint8(p, 3);
1948 /* NamedCurve namedcurve: secp256r1 */
1949 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
1950 p += sizeof(uint16);
1952 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
1955 /* This should be an uncompressed point, but I do not have access to the spec. */
1956 dtls_int_to_uint8(p, 4);
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;
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;
1967 dtls_ecdsa_generate_key(config->keyx.ecdsa.own_eph_priv,
1968 ephemeral_pub_x, ephemeral_pub_y,
1971 /* sign the ephemeral and its paramaters */
1972 dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
1973 config->tmp.random.client, DTLS_RANDOM_LENGTH,
1974 config->tmp.random.server, DTLS_RANDOM_LENGTH,
1975 key_params, p - key_params,
1978 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
1980 assert(p - buf <= sizeof(buf));
1982 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
1985 #endif /* DTLS_ECC */
1989 dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
1990 const unsigned char *psk_hint, size_t len)
1992 uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
1997 assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
1998 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1999 /* should never happen */
2000 dtls_warn("psk identity hint is too long\n");
2001 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2004 dtls_int_to_uint16(p, len);
2005 p += sizeof(uint16);
2007 memcpy(p, psk_hint, len);
2010 assert(p - buf <= sizeof(buf));
2012 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2015 #endif /* DTLS_PSK */
2019 dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
2026 * Start message construction at beginning of buffer. */
2029 /* certificate_types */
2030 dtls_int_to_uint8(p, 1);
2034 dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
2037 /* supported_signature_algorithms */
2038 dtls_int_to_uint16(p, 2);
2039 p += sizeof(uint16);
2042 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2046 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2049 /* certificate_authoritiess */
2050 dtls_int_to_uint16(p, 0);
2051 p += sizeof(uint16);
2053 assert(p - buf <= sizeof(buf));
2055 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
2058 #endif /* DTLS_ECC */
2061 dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
2066 * Start message construction at beginning of buffer. */
2068 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
2073 dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
2077 res = dtls_send_server_hello(ctx, peer);
2080 dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2085 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2086 const dtls_ecdsa_key_t *ecdsa_key;
2088 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2090 dtls_crit("no ecdsa certificate to send in certificate\n");
2094 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2097 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2101 res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2104 dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2108 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
2109 is_ecdsa_client_auth_supported(ctx)) {
2110 res = dtls_send_server_certificate_request(ctx, peer);
2113 dtls_debug("dtls_server_hello: cannot prepare certificate Request record\n");
2118 #endif /* DTLS_ECC */
2121 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2122 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
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);
2131 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2136 res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2139 dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2144 #endif /* DTLS_PSK */
2146 res = dtls_send_server_hello_done(ctx, peer);
2149 dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2156 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
2159 return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2164 dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
2166 uint8 buf[DTLS_CKXEC_LENGTH];
2168 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2172 switch (handshake->cipher) {
2174 case TLS_PSK_WITH_AES_128_CCM_8: {
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)));
2183 dtls_crit("no psk identity set in kx\n");
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");
2190 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2192 handshake->keyx.psk.id_length = (unsigned int)len;
2193 memcpy(handshake->keyx.psk.identity, p + sizeof(uint16), len);
2195 dtls_int_to_uint16(p, handshake->keyx.psk.id_length);
2196 p += sizeof(uint16);
2198 memcpy(p, handshake->keyx.psk.identity, handshake->keyx.psk.id_length);
2199 p += handshake->keyx.psk.id_length;
2203 #endif /* DTLS_PSK */
2205 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: {
2206 uint8 *ephemeral_pub_x;
2207 uint8 *ephemeral_pub_y;
2209 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2212 /* This should be an uncompressed point, but I do not have access to the spec. */
2213 dtls_int_to_uint8(p, 4);
2216 ephemeral_pub_x = p;
2217 p += DTLS_EC_KEY_SIZE;
2218 ephemeral_pub_y = p;
2219 p += DTLS_EC_KEY_SIZE;
2221 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecdsa.own_eph_priv,
2222 ephemeral_pub_x, ephemeral_pub_y,
2227 #endif /* DTLS_ECC */
2229 dtls_crit("cipher not supported\n");
2230 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2233 assert(p - buf <= sizeof(buf));
2235 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
2241 dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2242 const dtls_ecdsa_key_t *key)
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];
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];
2253 /* ServerKeyExchange
2255 * Start message construction at beginning of buffer. */
2258 copy_hs_hash(peer, &hs_hash);
2260 dtls_hash_finalize(sha256hash, &hs_hash);
2262 /* sign the ephemeral and its paramaters */
2263 dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
2264 sha256hash, sizeof(sha256hash),
2267 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2269 assert(p - buf <= sizeof(buf));
2271 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
2274 #endif /* DTLS_ECC */
2277 dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
2278 const unsigned char *label, size_t labellen)
2281 uint8 hash[DTLS_HMAC_MAX];
2282 uint8 buf[DTLS_FIN_LENGTH];
2283 dtls_hash_ctx hs_hash;
2286 copy_hs_hash(peer, &hs_hash);
2288 length = dtls_hash_finalize(hash, &hs_hash);
2290 dtls_prf(peer->handshake_params->tmp.master_secret,
2291 DTLS_MASTER_SECRET_LENGTH,
2293 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2295 p, DTLS_FIN_LENGTH);
2297 dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2299 p += DTLS_FIN_LENGTH;
2301 assert(p - buf <= sizeof(buf));
2303 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2308 dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
2309 uint8 cookie[], size_t cookie_length) {
2310 uint8 buf[DTLS_CH_LENGTH_MAX];
2312 uint8_t cipher_size;
2313 uint8_t extension_size;
2316 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2319 psk = is_psk_supported(ctx);
2320 ecdsa = is_ecdsa_supported(ctx, 1);
2322 cipher_size = 2 + ((ecdsa) ? 2 : 0) + ((psk) ? 2 : 0);
2323 extension_size = (ecdsa) ? 2 + 6 + 6 + 8 + 6: 0;
2325 if (cipher_size == 0) {
2326 dtls_crit("no cipher callbacks implemented\n");
2329 dtls_int_to_uint16(p, DTLS_VERSION);
2330 p += sizeof(uint16);
2332 if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2333 dtls_warn("the cookie is too long\n");
2334 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
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. */
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));
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;
2349 /* session id (length 0) */
2350 dtls_int_to_uint8(p, 0);
2354 dtls_int_to_uint8(p, cookie_length);
2356 if (cookie_length != 0) {
2357 memcpy(p, cookie, cookie_length);
2361 /* add known cipher(s) */
2362 dtls_int_to_uint16(p, cipher_size - 2);
2363 p += sizeof(uint16);
2366 dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
2367 p += sizeof(uint16);
2370 dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
2371 p += sizeof(uint16);
2374 /* compression method */
2375 dtls_int_to_uint8(p, 1);
2378 dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
2381 if (extension_size) {
2382 /* length of the extensions */
2383 dtls_int_to_uint16(p, extension_size - 2);
2384 p += sizeof(uint16);
2388 /* client certificate type extension */
2389 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2390 p += sizeof(uint16);
2392 /* length of this extension type */
2393 dtls_int_to_uint16(p, 2);
2394 p += sizeof(uint16);
2396 /* length of the list */
2397 dtls_int_to_uint8(p, 1);
2400 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2403 /* client certificate type extension */
2404 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2405 p += sizeof(uint16);
2407 /* length of this extension type */
2408 dtls_int_to_uint16(p, 2);
2409 p += sizeof(uint16);
2411 /* length of the list */
2412 dtls_int_to_uint8(p, 1);
2415 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2418 /* elliptic_curves */
2419 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
2420 p += sizeof(uint16);
2422 /* length of this extension type */
2423 dtls_int_to_uint16(p, 4);
2424 p += sizeof(uint16);
2426 /* length of the list */
2427 dtls_int_to_uint16(p, 2);
2428 p += sizeof(uint16);
2430 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2431 p += sizeof(uint16);
2433 /* ec_point_formats */
2434 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2435 p += sizeof(uint16);
2437 /* length of this extension type */
2438 dtls_int_to_uint16(p, 2);
2439 p += sizeof(uint16);
2441 /* number of supported formats */
2442 dtls_int_to_uint8(p, 1);
2445 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2449 assert(p - buf <= sizeof(buf));
2451 if (cookie_length != 0)
2452 clear_hs_hash(peer);
2454 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2455 DTLS_HT_CLIENT_HELLO,
2456 buf, p - buf, cookie_length != 0);
2460 check_server_hello(dtls_context_t *ctx,
2462 uint8 *data, size_t data_length)
2464 dtls_handshake_parameters_t *handshake = peer->handshake_params;
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.
2471 if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
2472 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2474 update_hs_hash(peer, data, data_length);
2476 /* FIXME: check data_length before accessing fields */
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. */
2483 /* check server version */
2484 data += DTLS_HS_LENGTH;
2485 data_length -= DTLS_HS_LENGTH;
2487 if (dtls_uint16_to_int(data) != DTLS_VERSION) {
2488 dtls_alert("unknown DTLS version\n");
2489 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
2492 data += sizeof(uint16); /* skip version field */
2493 data_length -= sizeof(uint16);
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;
2501 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
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",
2510 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
2512 data += sizeof(uint16);
2513 data_length -= sizeof(uint16);
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]);
2518 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
2520 data += sizeof(uint8);
2521 data_length -= sizeof(uint8);
2523 return dtls_check_tls_extension(peer, data, data_length, 0);
2526 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2530 check_server_hello_verify_request(dtls_context_t *ctx,
2532 uint8 *data, size_t data_length)
2534 dtls_hello_verify_t *hv;
2537 if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
2538 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2540 hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
2542 res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
2545 dtls_warn("cannot send ClientHello\n");
2552 check_server_certificate(dtls_context_t *ctx,
2554 uint8 *data, size_t data_length)
2557 dtls_handshake_parameters_t *config = peer->handshake_params;
2559 update_hs_hash(peer, data, data_length);
2561 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
2563 data += DTLS_HS_LENGTH;
2565 if (dtls_uint24_to_int(data) != 94) {
2566 dtls_alert("expect length of 94 bytes for server certificate message\n");
2567 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2569 data += sizeof(uint24);
2571 if (dtls_uint24_to_int(data) != 91) {
2572 dtls_alert("expect length of 91 bytes for certificate\n");
2573 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2575 data += sizeof(uint24);
2577 if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
2578 dtls_alert("got an unexpected Subject public key format\n");
2579 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2581 data += sizeof(cert_asn1_header);
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);
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);
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));
2596 dtls_warn("The certificate was not accepted\n");
2604 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
2606 uint8 *data, size_t data_length)
2608 dtls_handshake_parameters_t *config = peer->handshake_params;
2610 unsigned char *result_r;
2611 unsigned char *result_s;
2612 unsigned char *key_params;
2614 update_hs_hash(peer, data, data_length);
2616 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
2618 data += DTLS_HS_LENGTH;
2620 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
2621 dtls_alert("the packet length does not match the expected\n");
2622 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2626 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
2627 dtls_alert("Only named curves supported\n");
2628 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2630 data += sizeof(uint8);
2631 data_length -= sizeof(uint8);
2633 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
2634 dtls_alert("secp256r1 supported\n");
2635 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2637 data += sizeof(uint16);
2638 data_length -= sizeof(uint16);
2640 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
2641 dtls_alert("expected 65 bytes long public point\n");
2642 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2644 data += sizeof(uint8);
2645 data_length -= sizeof(uint8);
2647 if (dtls_uint8_to_int(data) != 4) {
2648 dtls_alert("expected uncompressed public point\n");
2649 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2651 data += sizeof(uint8);
2652 data_length -= sizeof(uint8);
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);
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);
2662 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
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,
2674 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
2675 result_r, result_s);
2678 dtls_alert("wrong signature\n");
2679 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2683 #endif /* DTLS_ECC */
2687 check_server_key_exchange_psk(dtls_context_t *ctx,
2689 uint8 *data, size_t data_length)
2691 dtls_handshake_parameters_t *config = peer->handshake_params;
2694 update_hs_hash(peer, data, data_length);
2696 assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
2698 data += DTLS_HS_LENGTH;
2700 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
2701 dtls_alert("the packet length does not match the expected\n");
2702 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2705 len = dtls_uint16_to_int(data);
2706 data += sizeof(uint16);
2708 if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
2709 dtls_warn("the length of the server identity hint is worng\n");
2710 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2713 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2714 dtls_warn("please use a smaller server identity hint\n");
2715 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
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);
2723 #endif /* DTLS_PSK */
2726 check_certificate_request(dtls_context_t *ctx,
2728 uint8 *data, size_t data_length)
2735 update_hs_hash(peer, data, data_length);
2737 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
2739 data += DTLS_HS_LENGTH;
2741 if (data_length < DTLS_HS_LENGTH + 5) {
2742 dtls_alert("the packet length does not match the expected\n");
2743 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
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");
2750 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2754 for (; i > 0 ; i -= sizeof(uint8)) {
2755 if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
2757 auth_alg = dtls_uint8_to_int(data);
2758 data += sizeof(uint8);
2761 if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
2762 dtls_alert("the request authentication algorithm is not supproted\n");
2763 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
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");
2770 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2775 for (; i > 0 ; i -= sizeof(uint16)) {
2776 int current_hash_alg;
2777 int current_sig_alg;
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);
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;
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");
2794 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2797 /* common names are ignored */
2799 peer->handshake_params->do_client_auth = 1;
2804 check_server_hellodone(dtls_context_t *ctx,
2806 uint8 *data, size_t data_length)
2810 const dtls_ecdsa_key_t *ecdsa_key;
2811 #endif /* DTLS_ECC */
2813 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2815 /* calculate master key, send CCS */
2817 update_hs_hash(peer, data, data_length);
2820 if (handshake->do_client_auth) {
2822 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2824 dtls_crit("no ecdsa certificate to send in certificate\n");
2828 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2831 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2835 #endif /* DTLS_ECC */
2837 /* send ClientKeyExchange */
2838 res = dtls_send_client_key_exchange(ctx, peer);
2841 dtls_debug("cannot send KeyExchange message\n");
2846 if (handshake->do_client_auth) {
2848 res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
2851 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2855 #endif /* DTLS_ECC */
2857 res = calculate_key_block(ctx, handshake, peer,
2858 &peer->session, peer->role);
2863 res = dtls_send_ccs(ctx, peer);
2865 dtls_debug("cannot send CCS message\n");
2869 /* and switch cipher suite */
2870 dtls_security_params_switch(peer);
2872 /* Client Finished */
2873 return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
2877 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
2880 dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
2881 dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
2884 *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
2885 clen = length - sizeof(dtls_record_header_t);
2888 dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
2892 if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
2893 /* no cipher suite selected */
2895 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
2897 * length of additional_data for the AEAD cipher which consists of
2898 * seq_num(2+6) + type(1) + version(2) + length(2)
2900 #define A_DATA_LEN 13
2901 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
2902 unsigned char A_DATA[A_DATA_LEN];
2904 if (clen < 16) /* need at least IV and MAC */
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));
2911 /* read epoch and seq_num from message */
2912 memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
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);
2921 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
2923 * additional_data = seq_num + TLSCompressed.type +
2924 * TLSCompressed.version + TLSCompressed.length;
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 */
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);
2935 dtls_warn("decryption failed\n");
2938 printf("decrypt_verify(): found %i bytes cleartext\n", clen);
2940 dtls_security_params_free_other(peer);
2941 dtls_debug_dump("cleartext", *cleartext, clen);
2948 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
2950 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2951 DTLS_HT_HELLO_REQUEST,
2956 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
2958 dtls_peer_t *peer = NULL;
2961 peer = dtls_get_peer(ctx, dst);
2966 if (peer->state != DTLS_STATE_CONNECTED)
2969 peer->handshake_params = dtls_handshake_new();
2970 if (!peer->handshake_params)
2973 peer->handshake_params->hs_state.mseq_r = 0;
2974 peer->handshake_params->hs_state.mseq_s = 0;
2976 if (peer->role == DTLS_CLIENT) {
2977 /* send ClientHello with empty Cookie */
2978 err = dtls_send_client_hello(ctx, peer, NULL, 0);
2980 dtls_warn("cannot send ClientHello\n");
2982 peer->state = DTLS_STATE_CLIENTHELLO;
2984 } else if (peer->role == DTLS_SERVER) {
2985 return dtls_send_hello_request(ctx, peer);
2992 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
2993 const dtls_peer_type role, const dtls_state_t state,
2994 uint8 *data, size_t data_length) {
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. */
3004 dtls_stop_retransmission(ctx, peer);
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. */
3011 dtls_debug("handle handshake packet of type: %s (%i)\n",
3012 dtls_handshake_type_to_name(data[0]), data[0]);
3015 /************************************************************************
3017 ************************************************************************/
3018 case DTLS_HT_HELLO_VERIFY_REQUEST:
3020 if (state != DTLS_STATE_CLIENTHELLO) {
3021 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3024 err = check_server_hello_verify_request(ctx, peer, data, data_length);
3026 dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3031 case DTLS_HT_SERVER_HELLO:
3033 if (state != DTLS_STATE_CLIENTHELLO) {
3034 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3037 err = check_server_hello(ctx, peer, data, data_length);
3039 dtls_warn("error in check_server_hello err: %i\n", err);
3042 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3043 peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE;
3045 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3046 /* update_hs_hash(peer, data, data_length); */
3051 case DTLS_HT_CERTIFICATE:
3053 if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3054 (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3055 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3057 err = check_server_certificate(ctx, peer, data, data_length);
3059 dtls_warn("error in check_server_certificate err: %i\n", err);
3062 if (role == DTLS_CLIENT) {
3063 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3064 } else if (role == DTLS_SERVER){
3065 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3067 /* update_hs_hash(peer, data, data_length); */
3070 #endif /* DTLS_ECC */
3072 case DTLS_HT_SERVER_KEY_EXCHANGE:
3075 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3076 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3077 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3079 err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3081 #endif /* DTLS_ECC */
3083 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3084 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3085 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3087 err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3089 #endif /* DTLS_PSK */
3092 dtls_warn("error in check_server_key_exchange err: %i\n", err);
3095 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3096 /* update_hs_hash(peer, data, data_length); */
3100 case DTLS_HT_SERVER_HELLO_DONE:
3102 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3103 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3106 err = check_server_hellodone(ctx, peer, data, data_length);
3108 dtls_warn("error in check_server_hellodone err: %i\n", err);
3111 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3112 /* update_hs_hash(peer, data, data_length); */
3116 case DTLS_HT_CERTIFICATE_REQUEST:
3118 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3119 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3122 err = check_certificate_request(ctx, peer, data, data_length);
3124 dtls_warn("error in check_certificate_request err: %i\n", err);
3130 case DTLS_HT_FINISHED:
3131 /* expect a Finished message from server */
3133 if (state != DTLS_STATE_WAIT_FINISHED) {
3134 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3137 err = check_finished(ctx, peer, data, data_length);
3139 dtls_warn("error in check_finished err: %i\n", err);
3142 if (role == DTLS_SERVER) {
3143 /* send ServerFinished */
3144 update_hs_hash(peer, data, data_length);
3146 /* send change cipher spec message and switch to new configuration */
3147 err = dtls_send_ccs(ctx, peer);
3149 dtls_warn("cannot send CCS message\n");
3153 dtls_security_params_switch(peer);
3155 err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3157 dtls_warn("sending server Finished failed\n");
3161 dtls_handshake_free(peer->handshake_params);
3162 peer->handshake_params = NULL;
3163 dtls_debug("Handshake complete\n");
3165 peer->state = DTLS_STATE_CONNECTED;
3167 /* return here to not increase the message receive counter */
3170 /************************************************************************
3172 ************************************************************************/
3174 case DTLS_HT_CLIENT_KEY_EXCHANGE:
3175 /* handle ClientHello, update msg and msglen and goto next if not finished */
3177 if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3178 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3181 err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3183 dtls_warn("error in check_client_keyexchange err: %i\n", err);
3186 update_hs_hash(peer, data, data_length);
3188 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3189 is_ecdsa_client_auth_supported(ctx))
3190 peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY;
3192 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3196 case DTLS_HT_CERTIFICATE_VERIFY:
3198 if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
3199 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3202 err = check_client_certificate_verify(ctx, peer, data, data_length);
3204 dtls_warn("error in check_client_certificate_verify err: %i\n", err);
3208 update_hs_hash(peer, data, data_length);
3209 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3211 #endif /* DTLS_ECC */
3213 case DTLS_HT_CLIENT_HELLO:
3215 if ((peer && state != DTLS_STATE_CONNECTED) ||
3216 (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
3217 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3220 /* When no DTLS state exists for this peer, we only allow a
3221 Client Hello message with
3223 a) a valid cookie, or
3226 Anything else will be rejected. Fragementation is not allowed
3227 here as it would require peer state as well.
3229 err = dtls_verify_peer(ctx, peer, session, data, data_length);
3231 dtls_warn("error in dtls_verify_peer err: %i\n", err);
3236 dtls_debug("server hello verify was sent\n");
3240 /* At this point, we have a good relationship with this peer. This
3241 * state is left for re-negotiation of key material. */
3243 dtls_security_parameters_t *security;
3245 /* msg contains a Client Hello with a valid cookie, so we can
3246 * safely create the server state machine and continue with
3248 peer = dtls_new_peer(session);
3250 dtls_alert("cannot create peer\n");
3251 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3253 peer->role = DTLS_SERVER;
3255 /* Initialize record sequence number to 1 for new peers. The first
3256 * record with sequence number 0 is a stateless Hello Verify Request.
3258 security = dtls_security_params(peer);
3260 dtls_add_peer(ctx, peer);
3262 if (peer && !peer->handshake_params) {
3263 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3265 peer->handshake_params = dtls_handshake_new();
3266 if (!peer->handshake_params)
3267 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
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;
3274 clear_hs_hash(peer);
3276 /* First negotiation step: check for PSK
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.
3282 err = dtls_update_parameters(ctx, peer, data, data_length);
3284 dtls_warn("error updating security parameters\n");
3288 /* update finish MAC */
3289 update_hs_hash(peer, data, data_length);
3291 err = dtls_send_server_hello_msgs(ctx, peer);
3295 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3296 is_ecdsa_client_auth_supported(ctx))
3297 peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE;
3299 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3301 /* after sending the ServerHelloDone, we expect the
3302 * ClientKeyExchange (possibly containing the PSK id),
3303 * followed by a ChangeCipherSpec and an encrypted Finished.
3308 case DTLS_HT_HELLO_REQUEST:
3310 if (state != DTLS_STATE_CONNECTED) {
3311 /* we should just ignore such packets when in handshake */
3315 if (peer && !peer->handshake_params) {
3316 peer->handshake_params = dtls_handshake_new();
3317 if (!peer->handshake_params)
3318 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
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;
3325 /* send ClientHello with empty Cookie */
3326 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3328 dtls_warn("cannot send ClientHello\n");
3331 peer->state = DTLS_STATE_CLIENTHELLO;
3335 dtls_crit("unhandled message %d\n", data[0]);
3336 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3339 if (peer && peer->handshake_params && err >= 0) {
3340 peer->handshake_params->hs_state.mseq_r++;
3347 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3348 const dtls_peer_type role, const dtls_state_t state,
3349 uint8 *data, size_t data_length)
3351 dtls_handshake_header_t *hs_header;
3354 if (data_length < DTLS_HS_LENGTH) {
3355 dtls_warn("handshake message too short\n");
3356 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3358 hs_header = DTLS_HANDSHAKE_HEADER(data);
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);
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");
3367 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
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,
3376 dtls_warn("ignore unexpected handshake message\n");
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));
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. */
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");
3395 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
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");
3402 node = netq_next(node);
3405 n = netq_node_new(data_length);
3407 dtls_warn("no space in reoder buffer\n");
3412 n->length = data_length;
3413 memcpy(n->data, data, data_length);
3415 if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
3416 dtls_warn("cannot add packet to reoder buffer\n");
3419 dtls_info("Added packet for reordering\n");
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 */
3425 res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
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) {
3432 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
3434 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
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);
3439 res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
3446 node = netq_next(node);
3457 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
3458 uint8 *record_header, uint8 *data, size_t data_length)
3461 dtls_handshake_parameters_t *handshake = peer->handshake_params;
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. */
3469 if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
3470 dtls_warn("expected ChangeCipherSpec during handshake\n");
3474 if (data_length < 1 || data[0] != 1)
3475 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
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);
3486 peer->state = DTLS_STATE_WAIT_FINISHED;
3492 * Handles incoming Alert messages. This function returns \c 1 if the
3493 * connection should be closed and the peer is to be invalidated.
3496 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
3497 uint8 *record_header, uint8 *data, size_t data_length) {
3498 int free_peer = 0; /* indicates whether to free peer */
3500 if (data_length < 2)
3501 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3503 dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
3506 dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
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.
3516 if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
3517 dtls_alert("%d invalidate peer\n", data[1]);
3519 #ifndef WITH_CONTIKI
3520 HASH_DEL_PEER(ctx->peers, peer);
3521 #else /* WITH_CONTIKI */
3522 list_remove(ctx->peers, peer);
3525 PRINTF("removed peer [");
3526 PRINT6ADDR(&peer->session.addr);
3527 PRINTF("]:%d\n", uip_ntohs(peer->session.port));
3529 #endif /* WITH_CONTIKI */
3535 (void)CALL(ctx, event, &peer->session,
3536 (dtls_alert_level_t)data[0], (unsigned short)data[1]);
3538 case DTLS_ALERT_CLOSE_NOTIFY:
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;
3543 dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
3545 peer->state = DTLS_STATE_CLOSED;
3552 dtls_stop_retransmission(ctx, peer);
3553 dtls_destroy_peer(ctx, peer, 0);
3559 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
3560 session_t *session, int err)
3565 if (err < -(1 << 8) && err > -(3 << 8)) {
3566 level = ((-err) & 0xff00) >> 8;
3567 desc = (-err) & 0xff;
3569 peer = dtls_get_peer(ctx, session);
3572 peer->state = DTLS_STATE_CLOSING;
3573 return dtls_send_alert(ctx, peer, level, desc);
3575 } else if (err == -1) {
3577 peer = dtls_get_peer(ctx, session);
3580 peer->state = DTLS_STATE_CLOSING;
3581 return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
3588 * Handles incoming data as DTLS message from given peer.
3591 dtls_handle_message(dtls_context_t *ctx,
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) */
3601 /* check if we have DTLS state for addr/port/ifindex */
3602 peer = dtls_get_peer(ctx, session);
3605 dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
3606 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
3608 dtls_debug("dtls_handle_message: FOUND PEER\n");
3611 while ((rlen = is_record(msg,msglen))) {
3612 dtls_peer_type role;
3615 dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
3617 data_length = decrypt_verify(peer, msg, rlen, &data);
3618 if (data_length < 0) {
3619 int err = dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
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);
3630 state = peer->state;
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;
3635 state = DTLS_STATE_WAIT_CLIENTHELLO;
3639 dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
3640 dtls_debug_hexdump("receive unencrypted", data, data_length);
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
3649 case DTLS_CT_CHANGE_CIPHER_SPEC:
3651 dtls_stop_retransmission(ctx, peer);
3653 err = handle_ccs(ctx, peer, msg, data, data_length);
3655 dtls_warn("error while handling ChangeCipherSpec message\n");
3656 dtls_alert_send_from_err(ctx, peer, session, err);
3658 /* invalidate peer */
3659 dtls_destroy_peer(ctx, peer, 1);
3668 dtls_stop_retransmission(ctx, peer);
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 */
3675 return err < 0 ?err:-1;
3679 case DTLS_CT_HANDSHAKE:
3680 /* Handshake messages other than Finish must use the current
3681 * epoch, Finish has epoch + 1. */
3684 uint16_t expected_epoch = dtls_security_params(peer)->epoch;
3685 uint16_t msg_epoch =
3686 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
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.
3693 if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
3697 if (expected_epoch != msg_epoch) {
3698 dtls_warn("Wrong epoch, expected %i, got: %i\n",
3699 expected_epoch, msg_epoch);
3704 err = handle_handshake(ctx, peer, session, role, state, data, data_length);
3706 dtls_warn("error while handling handshake packet\n");
3707 dtls_alert_send_from_err(ctx, peer, session, err);
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);
3717 case DTLS_CT_APPLICATION_DATA:
3718 dtls_info("** application data:\n");
3720 dtls_warn("no peer available, send an alert\n");
3721 // TODO: should we send a alert here?
3724 dtls_stop_retransmission(ctx, peer);
3725 CALL(ctx, read, &peer->session, data, data_length);
3728 dtls_info("dropped unknown message of type %d\n",msg[0]);
3731 /* advance msg by length of ciphertext */
3740 dtls_new_context(void *app_data) {
3743 #ifndef WITH_CONTIKI
3744 FILE *urandom = fopen("/dev/urandom", "r");
3745 unsigned char buf[sizeof(unsigned long)];
3746 #endif /* WITH_CONTIKI */
3750 /* FIXME: need something better to init PRNG here */
3751 dtls_prng_init(now);
3752 #else /* WITH_CONTIKI */
3754 dtls_emerg("cannot initialize PRNG\n");
3758 if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
3759 dtls_emerg("cannot initialize PRNG\n");
3764 dtls_prng_init((unsigned long)*buf);
3765 #endif /* WITH_CONTIKI */
3767 c = malloc_context();
3771 memset(c, 0, sizeof(dtls_context_t));
3774 LIST_STRUCT_INIT(c, sendqueue);
3777 LIST_STRUCT_INIT(c, peers);
3778 /* LIST_STRUCT_INIT(c, key_store); */
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 */
3787 if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
3788 c->cookie_secret_age = now;
3795 dtls_alert("cannot create DTLS context\n");
3797 dtls_free_context(c);
3802 dtls_free_context(dtls_context_t *ctx) {
3809 #ifndef WITH_CONTIKI
3813 HASH_ITER(hh, ctx->peers, p, tmp) {
3814 dtls_destroy_peer(ctx, p, 1);
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 */
3826 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
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);
3839 /* set local peer role to client, remote is server */
3840 peer->role = DTLS_CLIENT;
3842 dtls_add_peer(ctx, peer);
3844 /* send ClientHello with empty Cookie */
3845 peer->handshake_params = dtls_handshake_new();
3846 if (!peer->handshake_params)
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);
3854 dtls_warn("cannot send ClientHello\n");
3856 peer->state = DTLS_STATE_CLIENTHELLO;
3862 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
3866 peer = dtls_get_peer(ctx, dst);
3869 peer = dtls_new_peer(dst);
3872 dtls_crit("cannot create new peer\n");
3876 res = dtls_connect_peer(ctx, peer);
3878 /* Invoke event callback to indicate connection attempt or
3879 * re-negotiation. */
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);
3890 dtls_retransmit(dtls_context_t *context, netq_t *node) {
3891 if (!context || !node)
3894 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
3895 if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
3896 unsigned char sendbuf[DTLS_MAX_BUF];
3897 size_t len = sizeof(sendbuf);
3899 unsigned char *data = node->data;
3900 size_t length = node->length;
3902 dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
3905 node->retransmit_cnt++;
3906 node->t = now + (node->timeout << node->retransmit_cnt);
3907 netq_insert_node(context->sendqueue, node);
3909 if (node->type == DTLS_CT_HANDSHAKE) {
3910 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
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);
3915 dtls_debug("** retransmit packet\n");
3918 err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
3921 dtls_warn("can not retransmit packet, err: %i\n", err);
3924 dtls_debug_hexdump("retransmit header", sendbuf,
3925 sizeof(dtls_record_header_t));
3926 dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
3928 (void)CALL(context, write, &node->peer->session, sendbuf, len);
3932 /* no more retransmissions, remove node from system */
3934 dtls_debug("** removed transaction\n");
3936 /* And finally delete the node */
3937 netq_node_free(node);
3941 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
3943 node = list_head(context->sendqueue);
3946 if (dtls_session_equals(&node->peer->session, &peer->session)) {
3948 node = list_item_next(node);
3949 list_remove(context->sendqueue, tmp);
3950 netq_node_free(tmp);
3952 node = list_item_next(node);
3957 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
3959 netq_t *node = netq_head(context->sendqueue);
3962 while (node && node->t <= now) {
3963 netq_pop_first(context->sendqueue);
3964 dtls_retransmit(context, node);
3965 node = netq_head(context->sendqueue);
3973 /*---------------------------------------------------------------------------*/
3974 /* message retransmission */
3975 /*---------------------------------------------------------------------------*/
3976 PROCESS_THREAD(dtls_retransmit_process, ev, data)
3983 dtls_debug("Started DTLS retransmit process\r\n");
3987 if (ev == PROCESS_EVENT_TIMER) {
3988 if (etimer_expired(&the_dtls_context.retransmit_timer)) {
3990 node = list_head(the_dtls_context.sendqueue);
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);
3998 /* need to set timer to some value even if no nextpdu is available */
4000 etimer_set(&the_dtls_context.retransmit_timer,
4001 node->t <= now ? 1 : node->t - now);
4003 etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4011 #endif /* WITH_CONTIKI */