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));
533 * This method detects if we already have a established DTLS session with
534 * peer and the peer is attempting to perform a fresh handshake by sending
535 * messages with epoch = 0. This is to handle situations mentioned in
536 * RFC 6347 - section 4.2.8.
538 * @param msg The packet received from Client
539 * @param msglen Packet length
540 * @param peer peer who is the sender for this packet
541 * @return @c 1 if this is a rehandshake attempt by
545 hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
548 if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
549 if (msg[0] == DTLS_CT_HANDSHAKE) {
550 uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
551 if (msg_epoch == 0) {
552 dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
553 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
554 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
563 /** Dump out the cipher keys and IVs used for the symetric cipher. */
564 static void dtls_debug_keyblock(dtls_security_parameters_t *config)
566 dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
567 dtls_debug_dump(" client_MAC_secret",
568 dtls_kb_client_mac_secret(config, peer->role),
569 dtls_kb_mac_secret_size(config, peer->role));
571 dtls_debug_dump(" server_MAC_secret",
572 dtls_kb_server_mac_secret(config, peer->role),
573 dtls_kb_mac_secret_size(config, peer->role));
575 dtls_debug_dump(" client_write_key",
576 dtls_kb_client_write_key(config, peer->role),
577 dtls_kb_key_size(config, peer->role));
579 dtls_debug_dump(" server_write_key",
580 dtls_kb_server_write_key(config, peer->role),
581 dtls_kb_key_size(config, peer->role));
583 dtls_debug_dump(" client_IV",
584 dtls_kb_client_iv(config, peer->role),
585 dtls_kb_iv_size(config, peer->role));
587 dtls_debug_dump(" server_IV",
588 dtls_kb_server_iv(config, peer->role),
589 dtls_kb_iv_size(config, peer->role));
592 /** returns the name of the goven handshake type number.
593 * see IANA for a full list of types:
594 * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
596 static char *dtls_handshake_type_to_name(int type)
599 case DTLS_HT_HELLO_REQUEST:
600 return "hello_request";
601 case DTLS_HT_CLIENT_HELLO:
602 return "client_hello";
603 case DTLS_HT_SERVER_HELLO:
604 return "server_hello";
605 case DTLS_HT_HELLO_VERIFY_REQUEST:
606 return "hello_verify_request";
607 case DTLS_HT_CERTIFICATE:
608 return "certificate";
609 case DTLS_HT_SERVER_KEY_EXCHANGE:
610 return "server_key_exchange";
611 case DTLS_HT_CERTIFICATE_REQUEST:
612 return "certificate_request";
613 case DTLS_HT_SERVER_HELLO_DONE:
614 return "server_hello_done";
615 case DTLS_HT_CERTIFICATE_VERIFY:
616 return "certificate_verify";
617 case DTLS_HT_CLIENT_KEY_EXCHANGE:
618 return "client_key_exchange";
619 case DTLS_HT_FINISHED:
627 * Calculate the pre master secret and after that calculate the master-secret.
630 calculate_key_block(dtls_context_t *ctx,
631 dtls_handshake_parameters_t *handshake,
634 dtls_peer_type role) {
635 unsigned char *pre_master_secret;
636 int pre_master_len = 0;
637 dtls_security_parameters_t *security = dtls_security_params_next(peer);
638 uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
641 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
644 pre_master_secret = security->key_block;
646 switch (handshake->cipher) {
648 case TLS_PSK_WITH_AES_128_CCM_8: {
649 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
652 len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
653 handshake->keyx.psk.identity,
654 handshake->keyx.psk.id_length,
655 psk, DTLS_PSK_MAX_KEY_LEN);
657 dtls_crit("no psk key for session available\n");
660 /* Temporarily use the key_block storage space for the pre master secret. */
661 pre_master_len = dtls_psk_pre_master_secret(psk, len,
663 MAX_KEYBLOCK_LENGTH);
665 dtls_debug_hexdump("psk", psk, len);
667 memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
668 if (pre_master_len < 0) {
669 dtls_crit("the psk was too long, for the pre master secret\n");
670 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
675 #endif /* DTLS_PSK */
677 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: {
678 pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecdsa.own_eph_priv,
679 handshake->keyx.ecdsa.other_eph_pub_x,
680 handshake->keyx.ecdsa.other_eph_pub_y,
681 sizeof(handshake->keyx.ecdsa.own_eph_priv),
683 MAX_KEYBLOCK_LENGTH);
684 if (pre_master_len < 0) {
685 dtls_crit("the curve was too long, for the pre master secret\n");
686 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
690 #endif /* DTLS_ECC */
692 dtls_crit("calculate_key_block: unknown cipher\n");
693 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
696 dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
697 dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
698 dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
700 dtls_prf(pre_master_secret, pre_master_len,
701 PRF_LABEL(master), PRF_LABEL_SIZE(master),
702 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
703 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
705 DTLS_MASTER_SECRET_LENGTH);
707 dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
709 /* create key_block from master_secret
710 * key_block = PRF(master_secret,
711 "key expansion" + tmp.random.server + tmp.random.client) */
713 dtls_prf(master_secret,
714 DTLS_MASTER_SECRET_LENGTH,
715 PRF_LABEL(key), PRF_LABEL_SIZE(key),
716 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
717 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
719 dtls_kb_size(security, role));
721 memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
722 dtls_debug_keyblock(security);
724 security->cipher = handshake->cipher;
725 security->compression = handshake->compression;
731 /* TODO: add a generic method which iterates over a list and searches for a specific key */
732 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
735 /* length of curve list */
736 i = dtls_uint16_to_int(data);
737 data += sizeof(uint16);
738 if (i + sizeof(uint16) != data_length) {
739 dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
740 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
743 for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
744 /* check if this curve is supported */
745 curve_name = dtls_uint16_to_int(data);
746 data += sizeof(uint16);
748 if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
752 dtls_warn("no supported elliptic curve found\n");
753 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
756 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
759 /* length of cert type list */
760 i = dtls_uint8_to_int(data);
761 data += sizeof(uint8);
762 if (i + sizeof(uint8) != data_length) {
763 dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
764 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
767 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
768 /* check if this cert type is supported */
769 cert_type = dtls_uint8_to_int(data);
770 data += sizeof(uint8);
772 if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
776 dtls_warn("no supported certificate type found\n");
777 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
780 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
783 /* length of ec_point_formats list */
784 i = dtls_uint8_to_int(data);
785 data += sizeof(uint8);
786 if (i + sizeof(uint8) != data_length) {
787 dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
788 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
791 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
792 /* check if this ec_point_format is supported */
793 cert_type = dtls_uint8_to_int(data);
794 data += sizeof(uint8);
796 if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
800 dtls_warn("no supported ec_point_format found\n");
801 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
805 * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
808 dtls_check_tls_extension(dtls_peer_t *peer,
809 uint8 *data, size_t data_length, int client_hello)
812 int ext_elliptic_curve = 0;
813 int ext_client_cert_type = 0;
814 int ext_server_cert_type = 0;
815 int ext_ec_point_formats = 0;
816 dtls_handshake_parameters_t *handshake = peer->handshake_params;
818 if (data_length < sizeof(uint16)) {
819 /* no tls extensions specified */
820 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
826 /* get the length of the tls extension list */
827 j = dtls_uint16_to_int(data);
828 data += sizeof(uint16);
829 data_length -= sizeof(uint16);
834 /* check for TLS extensions needed for this cipher */
835 while (data_length) {
836 if (data_length < sizeof(uint16) * 2)
839 /* get the tls extension type */
840 i = dtls_uint16_to_int(data);
841 data += sizeof(uint16);
842 data_length -= sizeof(uint16);
844 /* get the length of the tls extension */
845 j = dtls_uint16_to_int(data);
846 data += sizeof(uint16);
847 data_length -= sizeof(uint16);
853 case TLS_EXT_ELLIPTIC_CURVES:
854 ext_elliptic_curve = 1;
855 if (verify_ext_eliptic_curves(data, j))
858 case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
859 ext_client_cert_type = 1;
861 if (verify_ext_cert_type(data, j))
864 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
868 case TLS_EXT_SERVER_CERTIFICATE_TYPE:
869 ext_server_cert_type = 1;
871 if (verify_ext_cert_type(data, j))
874 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
878 case TLS_EXT_EC_POINT_FORMATS:
879 ext_ec_point_formats = 1;
880 if (verify_ext_ec_point_formats(data, j))
883 case TLS_EXT_ENCRYPT_THEN_MAC:
884 /* As only AEAD cipher suites are currently available, this
885 * extension can be skipped.
887 dtls_info("skipped encrypt-then-mac extension\n");
890 dtls_warn("unsupported tls extension: %i\n", i);
896 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
897 if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
898 || !ext_ec_point_formats) {
899 dtls_warn("not all required tls extensions found in client hello\n");
902 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
903 if (!ext_client_cert_type || !ext_server_cert_type) {
904 dtls_warn("not all required tls extensions found in server hello\n");
911 if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
912 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
914 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
919 * Parses the ClientHello from the client and updates the internal handshake
920 * parameters with the new data for the given \p peer. When the ClientHello
921 * handshake message in \p data does not contain a cipher suite or
922 * compression method, it is copied from the the current security parameters.
924 * \param ctx The current DTLS context.
925 * \param peer The remote peer whose security parameters are about to change.
926 * \param data The handshake message with a ClientHello.
927 * \param data_length The actual size of \p data.
928 * \return \c -Something if an error occurred, \c 0 on success.
931 dtls_update_parameters(dtls_context_t *ctx,
933 uint8 *data, size_t data_length) {
936 dtls_handshake_parameters_t *config = peer->handshake_params;
937 dtls_security_parameters_t *security = dtls_security_params(peer);
940 assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
942 /* skip the handshake header and client version information */
943 data += DTLS_HS_LENGTH + sizeof(uint16);
944 data_length -= DTLS_HS_LENGTH + sizeof(uint16);
946 /* store client random in config */
947 memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
948 data += DTLS_RANDOM_LENGTH;
949 data_length -= DTLS_RANDOM_LENGTH;
951 /* Caution: SKIP_VAR_FIELD may jump to error: */
952 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
953 SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
955 i = dtls_uint16_to_int(data);
956 if (data_length < i + sizeof(uint16)) {
957 /* Looks like we do not have a cipher nor compression. This is ok
958 * for renegotiation, but not for the initial handshake. */
960 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
963 config->cipher = security->cipher;
964 config->compression = security->compression;
969 data += sizeof(uint16);
970 data_length -= sizeof(uint16) + i;
974 config->cipher = dtls_uint16_to_int(data);
975 ok = known_cipher(ctx, config->cipher, 0);
977 data += sizeof(uint16);
980 /* skip remaining ciphers */
984 /* reset config cipher to a well-defined value */
985 config->cipher = TLS_NULL_WITH_NULL_NULL;
986 dtls_warn("No matching cipher found\n");
990 if (data_length < sizeof(uint8)) {
991 /* no compression specified, take the current compression method */
993 config->compression = security->compression;
995 config->compression = TLS_COMPRESSION_NULL;
999 i = dtls_uint8_to_int(data);
1000 if (data_length < i + sizeof(uint8))
1003 data += sizeof(uint8);
1004 data_length -= sizeof(uint8) + i;
1008 for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
1009 if (dtls_uint8_to_int(data) == compression_methods[j]) {
1010 config->compression = compression_methods[j];
1014 data += sizeof(uint8);
1018 /* reset config cipher to a well-defined value */
1022 return dtls_check_tls_extension(peer, data, data_length, 1);
1024 if (peer->state == DTLS_STATE_CONNECTED) {
1025 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1027 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1032 * Parse the ClientKeyExchange and update the internal handshake state with
1036 check_client_keyexchange(dtls_context_t *ctx,
1037 dtls_handshake_parameters_t *handshake,
1038 uint8 *data, size_t length) {
1041 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
1043 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
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 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1050 dtls_alert("expected 65 bytes long public point\n");
1051 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1053 data += sizeof(uint8);
1055 if (dtls_uint8_to_int(data) != 4) {
1056 dtls_alert("expected uncompressed public point\n");
1057 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1059 data += sizeof(uint8);
1061 memcpy(handshake->keyx.ecdsa.other_eph_pub_x, data,
1062 sizeof(handshake->keyx.ecdsa.other_eph_pub_x));
1063 data += sizeof(handshake->keyx.ecdsa.other_eph_pub_x);
1065 memcpy(handshake->keyx.ecdsa.other_eph_pub_y, data,
1066 sizeof(handshake->keyx.ecdsa.other_eph_pub_y));
1067 data += sizeof(handshake->keyx.ecdsa.other_eph_pub_y);
1069 #endif /* DTLS_ECC */
1071 if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1074 if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1075 dtls_debug("The client key exchange is too short\n");
1076 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1078 data += DTLS_HS_LENGTH;
1080 id_length = dtls_uint16_to_int(data);
1081 data += sizeof(uint16);
1083 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1084 dtls_debug("The identity has a wrong length\n");
1085 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1088 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1089 dtls_warn("please use a smaller client identity\n");
1090 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1093 handshake->keyx.psk.id_length = id_length;
1094 memcpy(handshake->keyx.psk.identity, data, id_length);
1096 #endif /* DTLS_PSK */
1101 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1102 dtls_debug_dump("add MAC data", data, length);
1103 dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1107 copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
1108 memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1109 sizeof(peer->handshake_params->hs_state.hs_hash));
1112 static inline size_t
1113 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
1114 return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1118 clear_hs_hash(dtls_peer_t *peer) {
1120 dtls_debug("clear MAC\n");
1121 dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
1125 * Checks if \p record + \p data contain a Finished message with valid
1128 * \param ctx The current DTLS context.
1129 * \param peer The remote peer of the security association.
1130 * \param data The cleartext payload of the message.
1131 * \param data_length Actual length of \p data.
1132 * \return \c 0 if the Finished message is valid, \c negative number otherwise.
1135 check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
1136 uint8 *data, size_t data_length) {
1137 size_t digest_length, label_size;
1138 const unsigned char *label;
1139 unsigned char buf[DTLS_HMAC_MAX];
1141 if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1142 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1144 /* Use a union here to ensure that sufficient stack space is
1145 * reserved. As statebuf and verify_data are not used at the same
1146 * time, we can re-use the storage safely.
1149 unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1150 unsigned char verify_data[DTLS_FIN_LENGTH];
1153 /* temporarily store hash status for roll-back after finalize */
1154 memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1156 digest_length = finalize_hs_hash(peer, buf);
1159 /* restore hash status */
1160 memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1162 if (peer->role == DTLS_CLIENT) {
1163 label = PRF_LABEL(server);
1164 label_size = PRF_LABEL_SIZE(server);
1165 } else { /* server */
1166 label = PRF_LABEL(client);
1167 label_size = PRF_LABEL_SIZE(client);
1170 dtls_prf(peer->handshake_params->tmp.master_secret,
1171 DTLS_MASTER_SECRET_LENGTH,
1173 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1175 b.verify_data, sizeof(b.verify_data));
1177 dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1178 dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1180 /* compare verify data and create DTLS alert code when they differ */
1181 return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1183 : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
1187 * Prepares the payload given in \p data for sending with
1188 * dtls_send(). The \p data is encrypted and compressed according to
1189 * the current security parameters of \p peer. The result of this
1190 * operation is put into \p sendbuf with a prepended record header of
1191 * type \p type ready for sending. As some cipher suites add a MAC
1192 * before encryption, \p data must be large enough to hold this data
1193 * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
1195 * \param peer The remote peer the packet will be sent to.
1196 * \param security The encryption paramater used to encrypt
1197 * \param type The content type of this record.
1198 * \param data_array Array with payloads in correct order.
1199 * \param data_len_array sizes of the payloads in correct order.
1200 * \param data_array_len The number of payloads given.
1201 * \param sendbuf The output buffer where the encrypted record
1203 * \param rlen This parameter must be initialized with the
1204 * maximum size of \p sendbuf and will be updated
1205 * to hold the actual size of the stored packet
1206 * on success. On error, the value of \p rlen is
1208 * \return Less than zero on error, or greater than zero success.
1211 dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
1213 uint8 *data_array[], size_t data_len_array[],
1214 size_t data_array_len,
1215 uint8 *sendbuf, size_t *rlen) {
1220 if (*rlen < DTLS_RH_LENGTH) {
1221 dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1222 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1225 p = dtls_set_record_header(type, security, sendbuf);
1228 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1229 /* no cipher suite */
1232 for (i = 0; i < data_array_len; i++) {
1233 /* check the minimum that we need for packets that are not encrypted */
1234 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1235 dtls_debug("dtls_prepare_record: send buffer too small\n");
1236 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1239 memcpy(p, data_array[i], data_len_array[i]);
1240 p += data_len_array[i];
1241 res += data_len_array[i];
1243 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1245 * length of additional_data for the AEAD cipher which consists of
1246 * seq_num(2+6) + type(1) + version(2) + length(2)
1248 #define A_DATA_LEN 13
1249 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1250 unsigned char A_DATA[A_DATA_LEN];
1252 if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1253 dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1254 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1255 dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1257 dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1262 The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1263 the "nonce" SHALL be 12 bytes long and is constructed as follows:
1264 (this is an example of a "partially explicit" nonce; see Section
1265 3.2.1 in [RFC5116]).
1269 opaque nonce_explicit[8];
1274 In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1277 When the nonce_explicit is equal to the sequence number, the CCMNonce
1278 will have the structure of the CCMNonceExample given below.
1281 uint32 client_write_IV; // low order 32-bits
1282 uint64 seq_num; // TLS sequence number
1287 uint32 server_write_IV; // low order 32-bits
1288 uint64 seq_num; // TLS sequence number
1300 memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1304 for (i = 0; i < data_array_len; i++) {
1305 /* check the minimum that we need for packets that are not encrypted */
1306 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1307 dtls_debug("dtls_prepare_record: send buffer too small\n");
1308 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1311 memcpy(p, data_array[i], data_len_array[i]);
1312 p += data_len_array[i];
1313 res += data_len_array[i];
1316 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1317 memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1318 dtls_kb_iv_size(security, peer->role));
1319 memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
1321 dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1322 dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1323 dtls_kb_key_size(security, peer->role));
1325 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1327 * additional_data = seq_num + TLSCompressed.type +
1328 * TLSCompressed.version + TLSCompressed.length;
1330 memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1331 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1332 dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1334 res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1335 dtls_kb_local_write_key(security, peer->role),
1336 dtls_kb_key_size(security, peer->role),
1337 A_DATA, A_DATA_LEN);
1342 res += 8; /* increment res by size of nonce_explicit */
1343 dtls_debug_dump("message:", start, res);
1346 /* fix length of fragment in sendbuf */
1347 dtls_int_to_uint16(sendbuf + 11, res);
1349 *rlen = DTLS_RH_LENGTH + res;
1354 dtls_send_handshake_msg_hash(dtls_context_t *ctx,
1358 uint8 *data, size_t data_length,
1361 uint8 buf[DTLS_HS_LENGTH];
1362 uint8 *data_array[2];
1363 size_t data_len_array[2];
1365 dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1367 dtls_set_handshake_header(header_type, peer, data_length, 0,
1371 update_hs_hash(peer, buf, sizeof(buf));
1373 data_array[i] = buf;
1374 data_len_array[i] = sizeof(buf);
1379 update_hs_hash(peer, data, data_length);
1381 data_array[i] = data;
1382 data_len_array[i] = data_length;
1385 dtls_debug("send handshake packet of type: %s (%i)\n",
1386 dtls_handshake_type_to_name(header_type), header_type);
1387 return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1388 data_array, data_len_array, i);
1392 dtls_send_handshake_msg(dtls_context_t *ctx,
1395 uint8 *data, size_t data_length)
1397 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1398 header_type, data, data_length, 1);
1402 * Returns true if the message @p Data is a handshake message that
1403 * must be included in the calculation of verify_data in the Finished
1406 * @param Type The message type. Only handshake messages but the initial
1407 * Client Hello and Hello Verify Request are included in the hash,
1408 * @param Data The PDU to examine.
1409 * @param Length The length of @p Data.
1411 * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
1415 #define MUST_HASH(Type, Data, Length) \
1416 ((Type) == DTLS_CT_HANDSHAKE && \
1417 ((Data) != NULL) && ((Length) > 0) && \
1418 ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) && \
1419 ((Data)[0] != DTLS_HT_CLIENT_HELLO || \
1420 ((Length) >= HS_HDR_LENGTH && \
1421 (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) || \
1422 (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1425 * Sends the data passed in @p buf as a DTLS record of type @p type to
1426 * the given peer. The data will be encrypted and compressed according
1427 * to the security parameters for @p peer.
1429 * @param ctx The DTLS context in effect.
1430 * @param peer The remote party where the packet is sent.
1431 * @param type The content type of this record.
1432 * @param buf The data to send.
1433 * @param buflen The number of bytes to send from @p buf.
1434 * @return Less than zero in case of an error or the number of
1435 * bytes that have been sent otherwise.
1438 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
1439 dtls_security_parameters_t *security , session_t *session,
1440 unsigned char type, uint8 *buf_array[],
1441 size_t buf_len_array[], size_t buf_array_len)
1443 /* We cannot use ctx->sendbuf here as it is reserved for collecting
1444 * the input for this function, i.e. buf == ctx->sendbuf.
1446 * TODO: check if we can use the receive buf here. This would mean
1447 * that we might not be able to handle multiple records stuffed in
1448 * one UDP datagram */
1449 unsigned char sendbuf[DTLS_MAX_BUF];
1450 size_t len = sizeof(sendbuf);
1453 size_t overall_len = 0;
1455 res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1460 /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1461 /* update_hs_hash(peer, buf, buflen); */
1463 dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1464 for (i = 0; i < buf_array_len; i++) {
1465 dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1466 overall_len += buf_len_array[i];
1469 if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1470 type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1471 /* copy handshake messages other than HelloVerify into retransmit buffer */
1472 netq_t *n = netq_node_new(overall_len);
1476 n->t = now + 2 * CLOCK_SECOND;
1477 n->retransmit_cnt = 0;
1478 n->timeout = 2 * CLOCK_SECOND;
1480 n->epoch = (security) ? security->epoch : 0;
1483 for (i = 0; i < buf_array_len; i++) {
1484 memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1485 n->length += buf_len_array[i];
1488 if (!netq_insert_node(ctx->sendqueue, n)) {
1489 dtls_warn("cannot add packet to retransmit buffer\n");
1493 /* must set timer within the context of the retransmit process */
1494 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1495 etimer_set(&ctx->retransmit_timer, n->timeout);
1496 PROCESS_CONTEXT_END(&dtls_retransmit_process);
1497 #else /* WITH_CONTIKI */
1498 dtls_debug("copied to sendqueue\n");
1499 #endif /* WITH_CONTIKI */
1502 dtls_warn("retransmit buffer full\n");
1505 /* FIXME: copy to peer's sendqueue (after fragmentation if
1506 * necessary) and initialize retransmit timer */
1507 res = CALL(ctx, write, session, sendbuf, len);
1509 /* Guess number of bytes application data actually sent:
1510 * dtls_prepare_record() tells us in len the number of bytes to
1511 * send, res will contain the bytes actually sent. */
1512 return res <= 0 ? res : overall_len - (len - res);
1516 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
1517 dtls_alert_t description) {
1518 uint8_t msg[] = { level, description };
1520 dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1525 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1529 peer = dtls_get_peer(ctx, remote);
1532 res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
1533 /* indicate tear down */
1534 peer->state = DTLS_STATE_CLOSING;
1539 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1541 if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1542 dtls_close(ctx, &peer->session);
1544 #ifndef WITH_CONTIKI
1545 HASH_DEL_PEER(ctx->peers, peer);
1546 #else /* WITH_CONTIKI */
1547 list_remove(ctx->peers, peer);
1548 #endif /* WITH_CONTIKI */
1550 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1552 dtls_free_peer(peer);
1556 * Checks a received Client Hello message for a valid cookie. When the
1557 * Client Hello contains no cookie, the function fails and a Hello
1558 * Verify Request is sent to the peer (using the write callback function
1559 * registered with \p ctx). The return value is \c -1 on error, \c 0 when
1560 * undecided, and \c 1 if the Client Hello was good.
1562 * \param ctx The DTLS context.
1563 * \param peer The remote party we are talking to, if any.
1564 * \param session Transport address of the remote peer.
1565 * \param state Current state of the connection.
1566 * \param msg The received datagram.
1567 * \param msglen Length of \p msg.
1568 * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
1572 dtls_verify_peer(dtls_context_t *ctx,
1575 const dtls_state_t state,
1576 uint8 *data, size_t data_length)
1578 uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
1580 int len = DTLS_COOKIE_LENGTH;
1581 uint8 *cookie = NULL;
1584 #define mycookie (buf + DTLS_HV_LENGTH)
1586 /* Store cookie where we can reuse it for the HelloVerify request. */
1587 err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1591 dtls_debug_dump("create cookie", mycookie, len);
1593 assert(len == DTLS_COOKIE_LENGTH);
1595 /* Perform cookie check. */
1596 len = dtls_get_cookie(data, data_length, &cookie);
1598 dtls_warn("error while fetching the cookie, err: %i\n", err);
1602 dtls_debug_dump("compare with cookie", cookie, len);
1604 /* check if cookies match */
1605 if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1606 dtls_debug("found matching cookie\n");
1611 dtls_debug_dump("invalid cookie", cookie, len);
1613 dtls_debug("cookie len is 0!\n");
1616 /* ClientHello did not contain any valid cookie, hence we send a
1617 * HelloVerify request. */
1619 dtls_int_to_uint16(p, DTLS_VERSION);
1620 p += sizeof(uint16);
1622 dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
1625 assert(p == mycookie);
1627 p += DTLS_COOKIE_LENGTH;
1629 /* TODO use the same record sequence number as in the ClientHello,
1630 see 4.2.1. Denial-of-Service Countermeasures */
1631 err = dtls_send_handshake_msg_hash(ctx,
1632 state == DTLS_STATE_CONNECTED ? peer : NULL,
1634 DTLS_HT_HELLO_VERIFY_REQUEST,
1637 dtls_warn("cannot send HelloVerify request\n");
1639 return err; /* HelloVerify is sent, now we cannot do anything but wait */
1646 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1647 unsigned char **result_r,
1648 unsigned char **result_s)
1651 uint8 *data_orig = data;
1653 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
1654 dtls_alert("only sha256 is supported in certificate verify\n");
1655 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1657 data += sizeof(uint8);
1658 data_length -= sizeof(uint8);
1660 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
1661 dtls_alert("only ecdsa signature is supported in client verify\n");
1662 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1664 data += sizeof(uint8);
1665 data_length -= sizeof(uint8);
1667 if (data_length < dtls_uint16_to_int(data)) {
1668 dtls_alert("signature length wrong\n");
1669 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1671 data += sizeof(uint16);
1672 data_length -= sizeof(uint16);
1674 if (dtls_uint8_to_int(data) != 0x30) {
1675 dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1676 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1678 data += sizeof(uint8);
1679 data_length -= sizeof(uint8);
1681 if (data_length < dtls_uint8_to_int(data)) {
1682 dtls_alert("signature length wrong\n");
1683 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1685 data += sizeof(uint8);
1686 data_length -= sizeof(uint8);
1688 if (dtls_uint8_to_int(data) != 0x02) {
1689 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1690 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1692 data += sizeof(uint8);
1693 data_length -= sizeof(uint8);
1695 i = dtls_uint8_to_int(data);
1696 data += sizeof(uint8);
1697 data_length -= sizeof(uint8);
1699 /* Sometimes these values have a leeding 0 byte */
1700 *result_r = data + i - DTLS_EC_KEY_SIZE;
1705 if (dtls_uint8_to_int(data) != 0x02) {
1706 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1707 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1709 data += sizeof(uint8);
1710 data_length -= sizeof(uint8);
1712 i = dtls_uint8_to_int(data);
1713 data += sizeof(uint8);
1714 data_length -= sizeof(uint8);
1716 /* Sometimes these values have a leeding 0 byte */
1717 *result_s = data + i - DTLS_EC_KEY_SIZE;
1722 return data - data_orig;
1726 check_client_certificate_verify(dtls_context_t *ctx,
1728 uint8 *data, size_t data_length)
1730 dtls_handshake_parameters_t *config = peer->handshake_params;
1732 unsigned char *result_r;
1733 unsigned char *result_s;
1734 dtls_hash_ctx hs_hash;
1735 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1737 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
1739 data += DTLS_HS_LENGTH;
1741 if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1742 dtls_alert("the packet length does not match the expected\n");
1743 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1746 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
1753 copy_hs_hash(peer, &hs_hash);
1755 dtls_hash_finalize(sha256hash, &hs_hash);
1757 ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecdsa.other_pub_x, config->keyx.ecdsa.other_pub_y,
1758 sizeof(config->keyx.ecdsa.other_pub_x),
1759 sha256hash, sizeof(sha256hash),
1760 result_r, result_s);
1763 dtls_alert("wrong signature err: %i\n", ret);
1764 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1768 #endif /* DTLS_ECC */
1771 dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
1773 /* Ensure that the largest message to create fits in our source
1774 * buffer. (The size of the destination buffer is checked by the
1775 * encoding function, so we do not need to guess.) */
1776 uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
1779 uint8 extension_size;
1780 dtls_handshake_parameters_t *handshake = peer->handshake_params;
1783 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
1785 extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
1787 /* Handshake header */
1791 dtls_int_to_uint16(p, DTLS_VERSION);
1792 p += sizeof(uint16);
1794 /* Set server random: First 4 bytes are the server's Unix timestamp,
1795 * followed by 28 bytes of generate random data. */
1797 dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
1798 dtls_prng(handshake->tmp.random.server + 4, 28);
1800 memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
1801 p += DTLS_RANDOM_LENGTH;
1803 *p++ = 0; /* no session id */
1805 if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
1806 /* selected cipher suite */
1807 dtls_int_to_uint16(p, handshake->cipher);
1808 p += sizeof(uint16);
1810 /* selected compression method */
1811 *p++ = compression_methods[handshake->compression];
1814 if (extension_size) {
1815 /* length of the extensions */
1816 dtls_int_to_uint16(p, extension_size - 2);
1817 p += sizeof(uint16);
1821 /* client certificate type extension */
1822 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
1823 p += sizeof(uint16);
1825 /* length of this extension type */
1826 dtls_int_to_uint16(p, 1);
1827 p += sizeof(uint16);
1829 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
1832 /* client certificate type extension */
1833 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
1834 p += sizeof(uint16);
1836 /* length of this extension type */
1837 dtls_int_to_uint16(p, 1);
1838 p += sizeof(uint16);
1840 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
1843 /* ec_point_formats */
1844 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
1845 p += sizeof(uint16);
1847 /* length of this extension type */
1848 dtls_int_to_uint16(p, 2);
1849 p += sizeof(uint16);
1851 /* number of supported formats */
1852 dtls_int_to_uint8(p, 1);
1855 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
1859 assert(p - buf <= sizeof(buf));
1861 /* TODO use the same record sequence number as in the ClientHello,
1862 see 4.2.1. Denial-of-Service Countermeasures */
1863 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
1869 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
1870 const dtls_ecdsa_key_t *key)
1872 uint8 buf[DTLS_CE_LENGTH];
1877 * Start message construction at beginning of buffer. */
1880 dtls_int_to_uint24(p, 94); /* certificates length */
1881 p += sizeof(uint24);
1883 dtls_int_to_uint24(p, 91); /* length of this certificate */
1884 p += sizeof(uint24);
1886 memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
1887 p += sizeof(cert_asn1_header);
1889 memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
1890 p += DTLS_EC_KEY_SIZE;
1892 memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
1893 p += DTLS_EC_KEY_SIZE;
1895 assert(p - buf <= sizeof(buf));
1897 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
1902 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
1907 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
1908 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
1909 /* store the pointer to the r component of the signature and make space */
1910 len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
1911 len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
1917 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
1921 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
1924 /* length of signature */
1925 dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
1926 p += sizeof(uint16);
1928 /* ASN.1 SEQUENCE */
1929 dtls_int_to_uint8(p, 0x30);
1932 dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
1935 /* ASN.1 Integer r */
1936 dtls_int_to_uint8(p, 0x02);
1939 dtls_int_to_uint8(p, len_r);
1942 /* the pint r was added here */
1945 /* ASN.1 Integer s */
1946 dtls_int_to_uint8(p, 0x02);
1949 dtls_int_to_uint8(p, len_s);
1952 /* the pint s was added here */
1959 dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
1960 const dtls_ecdsa_key_t *key)
1962 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
1963 * 33 bytes long add space for that */
1964 uint8 buf[DTLS_SKEXEC_LENGTH + 2];
1967 uint8 *ephemeral_pub_x;
1968 uint8 *ephemeral_pub_y;
1969 uint32_t point_r[9];
1970 uint32_t point_s[9];
1971 dtls_handshake_parameters_t *config = peer->handshake_params;
1973 /* ServerKeyExchange
1975 * Start message construction at beginning of buffer. */
1979 /* ECCurveType curve_type: named_curve */
1980 dtls_int_to_uint8(p, 3);
1983 /* NamedCurve namedcurve: secp256r1 */
1984 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
1985 p += sizeof(uint16);
1987 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
1990 /* This should be an uncompressed point, but I do not have access to the spec. */
1991 dtls_int_to_uint8(p, 4);
1994 /* store the pointer to the x component of the pub key and make space */
1995 ephemeral_pub_x = p;
1996 p += DTLS_EC_KEY_SIZE;
1998 /* store the pointer to the y component of the pub key and make space */
1999 ephemeral_pub_y = p;
2000 p += DTLS_EC_KEY_SIZE;
2002 dtls_ecdsa_generate_key(config->keyx.ecdsa.own_eph_priv,
2003 ephemeral_pub_x, ephemeral_pub_y,
2006 /* sign the ephemeral and its paramaters */
2007 dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
2008 config->tmp.random.client, DTLS_RANDOM_LENGTH,
2009 config->tmp.random.server, DTLS_RANDOM_LENGTH,
2010 key_params, p - key_params,
2013 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2015 assert(p - buf <= sizeof(buf));
2017 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2020 #endif /* DTLS_ECC */
2024 dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2025 const unsigned char *psk_hint, size_t len)
2027 uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
2032 assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2033 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2034 /* should never happen */
2035 dtls_warn("psk identity hint is too long\n");
2036 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2039 dtls_int_to_uint16(p, len);
2040 p += sizeof(uint16);
2042 memcpy(p, psk_hint, len);
2045 assert(p - buf <= sizeof(buf));
2047 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2050 #endif /* DTLS_PSK */
2054 dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
2061 * Start message construction at beginning of buffer. */
2064 /* certificate_types */
2065 dtls_int_to_uint8(p, 1);
2069 dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
2072 /* supported_signature_algorithms */
2073 dtls_int_to_uint16(p, 2);
2074 p += sizeof(uint16);
2077 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2081 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2084 /* certificate_authoritiess */
2085 dtls_int_to_uint16(p, 0);
2086 p += sizeof(uint16);
2088 assert(p - buf <= sizeof(buf));
2090 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
2093 #endif /* DTLS_ECC */
2096 dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
2101 * Start message construction at beginning of buffer. */
2103 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
2108 dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
2112 res = dtls_send_server_hello(ctx, peer);
2115 dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2120 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2121 const dtls_ecdsa_key_t *ecdsa_key;
2123 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2125 dtls_crit("no ecdsa certificate to send in certificate\n");
2129 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2132 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2136 res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2139 dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2143 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
2144 is_ecdsa_client_auth_supported(ctx)) {
2145 res = dtls_send_server_certificate_request(ctx, peer);
2148 dtls_debug("dtls_server_hello: cannot prepare certificate Request record\n");
2153 #endif /* DTLS_ECC */
2156 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2157 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2160 /* The identity hint is optional, therefore we ignore the result
2161 * and check psk only. */
2162 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2163 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2166 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2171 res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2174 dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2179 #endif /* DTLS_PSK */
2181 res = dtls_send_server_hello_done(ctx, peer);
2184 dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2191 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
2194 return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2199 dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
2201 uint8 buf[DTLS_CKXEC_LENGTH];
2202 uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2204 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2208 switch (handshake->cipher) {
2210 case TLS_PSK_WITH_AES_128_CCM_8: {
2213 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2218 dtls_crit("no psk identity set in kx\n");
2222 if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2223 dtls_warn("the psk identity is too long\n");
2224 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2227 dtls_int_to_uint16(p, len);
2228 p += sizeof(uint16);
2230 memcpy(p, client_id, len);
2235 #endif /* DTLS_PSK */
2237 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: {
2238 uint8 *ephemeral_pub_x;
2239 uint8 *ephemeral_pub_y;
2241 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2244 /* This should be an uncompressed point, but I do not have access to the spec. */
2245 dtls_int_to_uint8(p, 4);
2248 ephemeral_pub_x = p;
2249 p += DTLS_EC_KEY_SIZE;
2250 ephemeral_pub_y = p;
2251 p += DTLS_EC_KEY_SIZE;
2253 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecdsa.own_eph_priv,
2254 ephemeral_pub_x, ephemeral_pub_y,
2259 #endif /* DTLS_ECC */
2261 dtls_crit("cipher not supported\n");
2262 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2265 assert(p - buf <= sizeof(buf));
2267 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
2273 dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2274 const dtls_ecdsa_key_t *key)
2276 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2277 * 33 bytes long add space for that */
2278 uint8 buf[DTLS_CV_LENGTH + 2];
2280 uint32_t point_r[9];
2281 uint32_t point_s[9];
2282 dtls_hash_ctx hs_hash;
2283 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2285 /* ServerKeyExchange
2287 * Start message construction at beginning of buffer. */
2290 copy_hs_hash(peer, &hs_hash);
2292 dtls_hash_finalize(sha256hash, &hs_hash);
2294 /* sign the ephemeral and its paramaters */
2295 dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
2296 sha256hash, sizeof(sha256hash),
2299 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2301 assert(p - buf <= sizeof(buf));
2303 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
2306 #endif /* DTLS_ECC */
2309 dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
2310 const unsigned char *label, size_t labellen)
2313 uint8 hash[DTLS_HMAC_MAX];
2314 uint8 buf[DTLS_FIN_LENGTH];
2315 dtls_hash_ctx hs_hash;
2318 copy_hs_hash(peer, &hs_hash);
2320 length = dtls_hash_finalize(hash, &hs_hash);
2322 dtls_prf(peer->handshake_params->tmp.master_secret,
2323 DTLS_MASTER_SECRET_LENGTH,
2325 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2327 p, DTLS_FIN_LENGTH);
2329 dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2331 p += DTLS_FIN_LENGTH;
2333 assert(p - buf <= sizeof(buf));
2335 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2340 dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
2341 uint8 cookie[], size_t cookie_length) {
2342 uint8 buf[DTLS_CH_LENGTH_MAX];
2344 uint8_t cipher_size;
2345 uint8_t extension_size;
2348 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2351 psk = is_psk_supported(ctx);
2352 ecdsa = is_ecdsa_supported(ctx, 1);
2354 cipher_size = 2 + ((ecdsa) ? 2 : 0) + ((psk) ? 2 : 0);
2355 extension_size = (ecdsa) ? 2 + 6 + 6 + 8 + 6: 0;
2357 if (cipher_size == 0) {
2358 dtls_crit("no cipher callbacks implemented\n");
2361 dtls_int_to_uint16(p, DTLS_VERSION);
2362 p += sizeof(uint16);
2364 if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2365 dtls_warn("the cookie is too long\n");
2366 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2369 if (cookie_length == 0) {
2370 /* Set client random: First 4 bytes are the client's Unix timestamp,
2371 * followed by 28 bytes of generate random data. */
2373 dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2374 dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2375 DTLS_RANDOM_LENGTH - sizeof(uint32));
2377 /* we must use the same Client Random as for the previous request */
2378 memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2379 p += DTLS_RANDOM_LENGTH;
2381 /* session id (length 0) */
2382 dtls_int_to_uint8(p, 0);
2386 dtls_int_to_uint8(p, cookie_length);
2388 if (cookie_length != 0) {
2389 memcpy(p, cookie, cookie_length);
2393 /* add known cipher(s) */
2394 dtls_int_to_uint16(p, cipher_size - 2);
2395 p += sizeof(uint16);
2398 dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
2399 p += sizeof(uint16);
2402 dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
2403 p += sizeof(uint16);
2406 /* compression method */
2407 dtls_int_to_uint8(p, 1);
2410 dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
2413 if (extension_size) {
2414 /* length of the extensions */
2415 dtls_int_to_uint16(p, extension_size - 2);
2416 p += sizeof(uint16);
2420 /* client certificate type extension */
2421 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2422 p += sizeof(uint16);
2424 /* length of this extension type */
2425 dtls_int_to_uint16(p, 2);
2426 p += sizeof(uint16);
2428 /* length of the list */
2429 dtls_int_to_uint8(p, 1);
2432 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2435 /* client certificate type extension */
2436 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2437 p += sizeof(uint16);
2439 /* length of this extension type */
2440 dtls_int_to_uint16(p, 2);
2441 p += sizeof(uint16);
2443 /* length of the list */
2444 dtls_int_to_uint8(p, 1);
2447 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2450 /* elliptic_curves */
2451 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
2452 p += sizeof(uint16);
2454 /* length of this extension type */
2455 dtls_int_to_uint16(p, 4);
2456 p += sizeof(uint16);
2458 /* length of the list */
2459 dtls_int_to_uint16(p, 2);
2460 p += sizeof(uint16);
2462 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2463 p += sizeof(uint16);
2465 /* ec_point_formats */
2466 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2467 p += sizeof(uint16);
2469 /* length of this extension type */
2470 dtls_int_to_uint16(p, 2);
2471 p += sizeof(uint16);
2473 /* number of supported formats */
2474 dtls_int_to_uint8(p, 1);
2477 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2481 assert(p - buf <= sizeof(buf));
2483 if (cookie_length != 0)
2484 clear_hs_hash(peer);
2486 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2487 DTLS_HT_CLIENT_HELLO,
2488 buf, p - buf, cookie_length != 0);
2492 check_server_hello(dtls_context_t *ctx,
2494 uint8 *data, size_t data_length)
2496 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2498 /* This function is called when we expect a ServerHello (i.e. we
2499 * have sent a ClientHello). We might instead receive a HelloVerify
2500 * request containing a cookie. If so, we must repeat the
2501 * ClientHello with the given Cookie.
2503 if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
2504 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2506 update_hs_hash(peer, data, data_length);
2508 /* FIXME: check data_length before accessing fields */
2510 /* Get the server's random data and store selected cipher suite
2511 * and compression method (like dtls_update_parameters().
2512 * Then calculate master secret and wait for ServerHelloDone. When received,
2513 * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
2515 /* check server version */
2516 data += DTLS_HS_LENGTH;
2517 data_length -= DTLS_HS_LENGTH;
2519 if (dtls_uint16_to_int(data) != DTLS_VERSION) {
2520 dtls_alert("unknown DTLS version\n");
2521 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
2524 data += sizeof(uint16); /* skip version field */
2525 data_length -= sizeof(uint16);
2527 /* store server random data */
2528 memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
2529 /* skip server random */
2530 data += DTLS_RANDOM_LENGTH;
2531 data_length -= DTLS_RANDOM_LENGTH;
2533 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
2535 /* Check cipher suite. As we offer all we have, it is sufficient
2536 * to check if the cipher suite selected by the server is in our
2537 * list of known cipher suites. Subsets are not supported. */
2538 handshake->cipher = dtls_uint16_to_int(data);
2539 if (!known_cipher(ctx, handshake->cipher, 1)) {
2540 dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
2542 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
2544 data += sizeof(uint16);
2545 data_length -= sizeof(uint16);
2547 /* Check if NULL compression was selected. We do not know any other. */
2548 if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
2549 dtls_alert("unsupported compression method 0x%02x\n", data[0]);
2550 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
2552 data += sizeof(uint8);
2553 data_length -= sizeof(uint8);
2555 return dtls_check_tls_extension(peer, data, data_length, 0);
2558 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2562 check_server_hello_verify_request(dtls_context_t *ctx,
2564 uint8 *data, size_t data_length)
2566 dtls_hello_verify_t *hv;
2569 if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
2570 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2572 hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
2574 res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
2577 dtls_warn("cannot send ClientHello\n");
2584 check_server_certificate(dtls_context_t *ctx,
2586 uint8 *data, size_t data_length)
2589 dtls_handshake_parameters_t *config = peer->handshake_params;
2591 update_hs_hash(peer, data, data_length);
2593 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
2595 data += DTLS_HS_LENGTH;
2597 if (dtls_uint24_to_int(data) != 94) {
2598 dtls_alert("expect length of 94 bytes for server certificate message\n");
2599 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2601 data += sizeof(uint24);
2603 if (dtls_uint24_to_int(data) != 91) {
2604 dtls_alert("expect length of 91 bytes for certificate\n");
2605 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2607 data += sizeof(uint24);
2609 if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
2610 dtls_alert("got an unexpected Subject public key format\n");
2611 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2613 data += sizeof(cert_asn1_header);
2615 memcpy(config->keyx.ecdsa.other_pub_x, data,
2616 sizeof(config->keyx.ecdsa.other_pub_x));
2617 data += sizeof(config->keyx.ecdsa.other_pub_x);
2619 memcpy(config->keyx.ecdsa.other_pub_y, data,
2620 sizeof(config->keyx.ecdsa.other_pub_y));
2621 data += sizeof(config->keyx.ecdsa.other_pub_y);
2623 err = CALL(ctx, verify_ecdsa_key, &peer->session,
2624 config->keyx.ecdsa.other_pub_x,
2625 config->keyx.ecdsa.other_pub_y,
2626 sizeof(config->keyx.ecdsa.other_pub_x));
2628 dtls_warn("The certificate was not accepted\n");
2636 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
2638 uint8 *data, size_t data_length)
2640 dtls_handshake_parameters_t *config = peer->handshake_params;
2642 unsigned char *result_r;
2643 unsigned char *result_s;
2644 unsigned char *key_params;
2646 update_hs_hash(peer, data, data_length);
2648 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
2650 data += DTLS_HS_LENGTH;
2652 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
2653 dtls_alert("the packet length does not match the expected\n");
2654 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2658 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
2659 dtls_alert("Only named curves supported\n");
2660 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2662 data += sizeof(uint8);
2663 data_length -= sizeof(uint8);
2665 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
2666 dtls_alert("secp256r1 supported\n");
2667 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2669 data += sizeof(uint16);
2670 data_length -= sizeof(uint16);
2672 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
2673 dtls_alert("expected 65 bytes long public point\n");
2674 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2676 data += sizeof(uint8);
2677 data_length -= sizeof(uint8);
2679 if (dtls_uint8_to_int(data) != 4) {
2680 dtls_alert("expected uncompressed public point\n");
2681 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2683 data += sizeof(uint8);
2684 data_length -= sizeof(uint8);
2686 memcpy(config->keyx.ecdsa.other_eph_pub_x, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
2687 data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
2688 data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
2690 memcpy(config->keyx.ecdsa.other_eph_pub_y, data, sizeof(config->keyx.ecdsa.other_eph_pub_y));
2691 data += sizeof(config->keyx.ecdsa.other_eph_pub_y);
2692 data_length -= sizeof(config->keyx.ecdsa.other_eph_pub_y);
2694 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
2701 ret = dtls_ecdsa_verify_sig(config->keyx.ecdsa.other_pub_x, config->keyx.ecdsa.other_pub_y,
2702 sizeof(config->keyx.ecdsa.other_pub_x),
2703 config->tmp.random.client, DTLS_RANDOM_LENGTH,
2704 config->tmp.random.server, DTLS_RANDOM_LENGTH,
2706 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
2707 result_r, result_s);
2710 dtls_alert("wrong signature\n");
2711 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2715 #endif /* DTLS_ECC */
2719 check_server_key_exchange_psk(dtls_context_t *ctx,
2721 uint8 *data, size_t data_length)
2723 dtls_handshake_parameters_t *config = peer->handshake_params;
2726 update_hs_hash(peer, data, data_length);
2728 assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
2730 data += DTLS_HS_LENGTH;
2732 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
2733 dtls_alert("the packet length does not match the expected\n");
2734 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2737 len = dtls_uint16_to_int(data);
2738 data += sizeof(uint16);
2740 if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
2741 dtls_warn("the length of the server identity hint is worng\n");
2742 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2745 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2746 dtls_warn("please use a smaller server identity hint\n");
2747 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2750 /* store the psk_identity_hint in config->keyx.psk for later use */
2751 config->keyx.psk.id_length = len;
2752 memcpy(config->keyx.psk.identity, data, len);
2755 #endif /* DTLS_PSK */
2758 check_certificate_request(dtls_context_t *ctx,
2760 uint8 *data, size_t data_length)
2767 update_hs_hash(peer, data, data_length);
2769 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
2771 data += DTLS_HS_LENGTH;
2773 if (data_length < DTLS_HS_LENGTH + 5) {
2774 dtls_alert("the packet length does not match the expected\n");
2775 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2778 i = dtls_uint8_to_int(data);
2779 data += sizeof(uint8);
2780 if (i + 1 > data_length) {
2781 dtls_alert("the cerfificate types are too long\n");
2782 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2786 for (; i > 0 ; i -= sizeof(uint8)) {
2787 if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
2789 auth_alg = dtls_uint8_to_int(data);
2790 data += sizeof(uint8);
2793 if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
2794 dtls_alert("the request authentication algorithm is not supproted\n");
2795 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2798 i = dtls_uint16_to_int(data);
2799 data += sizeof(uint16);
2800 if (i + 1 > data_length) {
2801 dtls_alert("the signature and hash algorithm list is too long\n");
2802 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2807 for (; i > 0 ; i -= sizeof(uint16)) {
2808 int current_hash_alg;
2809 int current_sig_alg;
2811 current_hash_alg = dtls_uint8_to_int(data);
2812 data += sizeof(uint8);
2813 current_sig_alg = dtls_uint8_to_int(data);
2814 data += sizeof(uint8);
2816 if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 &&
2817 current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
2818 hash_alg = current_hash_alg;
2819 sig_alg = current_sig_alg;
2823 if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
2824 sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
2825 dtls_alert("no supported hash and signature algorithem\n");
2826 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2829 /* common names are ignored */
2831 peer->handshake_params->do_client_auth = 1;
2836 check_server_hellodone(dtls_context_t *ctx,
2838 uint8 *data, size_t data_length)
2842 const dtls_ecdsa_key_t *ecdsa_key;
2843 #endif /* DTLS_ECC */
2845 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2847 /* calculate master key, send CCS */
2849 update_hs_hash(peer, data, data_length);
2852 if (handshake->do_client_auth) {
2854 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2856 dtls_crit("no ecdsa certificate to send in certificate\n");
2860 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2863 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2867 #endif /* DTLS_ECC */
2869 /* send ClientKeyExchange */
2870 res = dtls_send_client_key_exchange(ctx, peer);
2873 dtls_debug("cannot send KeyExchange message\n");
2878 if (handshake->do_client_auth) {
2880 res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
2883 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2887 #endif /* DTLS_ECC */
2889 res = calculate_key_block(ctx, handshake, peer,
2890 &peer->session, peer->role);
2895 res = dtls_send_ccs(ctx, peer);
2897 dtls_debug("cannot send CCS message\n");
2901 /* and switch cipher suite */
2902 dtls_security_params_switch(peer);
2904 /* Client Finished */
2905 return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
2909 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
2912 dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
2913 dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
2916 *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
2917 clen = length - sizeof(dtls_record_header_t);
2920 dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
2924 if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
2925 /* no cipher suite selected */
2927 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
2929 * length of additional_data for the AEAD cipher which consists of
2930 * seq_num(2+6) + type(1) + version(2) + length(2)
2932 #define A_DATA_LEN 13
2933 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
2934 unsigned char A_DATA[A_DATA_LEN];
2936 if (clen < 16) /* need at least IV and MAC */
2939 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
2940 memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
2941 dtls_kb_iv_size(security, peer->role));
2943 /* read epoch and seq_num from message */
2944 memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
2948 dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
2949 dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
2950 dtls_kb_key_size(security, peer->role));
2951 dtls_debug_dump("ciphertext", *cleartext, clen);
2953 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
2955 * additional_data = seq_num + TLSCompressed.type +
2956 * TLSCompressed.version + TLSCompressed.length;
2958 memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
2959 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
2960 dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
2962 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
2963 dtls_kb_remote_write_key(security, peer->role),
2964 dtls_kb_key_size(security, peer->role),
2965 A_DATA, A_DATA_LEN);
2967 dtls_warn("decryption failed\n");
2970 printf("decrypt_verify(): found %i bytes cleartext\n", clen);
2972 dtls_security_params_free_other(peer);
2973 dtls_debug_dump("cleartext", *cleartext, clen);
2980 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
2982 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2983 DTLS_HT_HELLO_REQUEST,
2988 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
2990 dtls_peer_t *peer = NULL;
2993 peer = dtls_get_peer(ctx, dst);
2998 if (peer->state != DTLS_STATE_CONNECTED)
3001 peer->handshake_params = dtls_handshake_new();
3002 if (!peer->handshake_params)
3005 peer->handshake_params->hs_state.mseq_r = 0;
3006 peer->handshake_params->hs_state.mseq_s = 0;
3008 if (peer->role == DTLS_CLIENT) {
3009 /* send ClientHello with empty Cookie */
3010 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3012 dtls_warn("cannot send ClientHello\n");
3014 peer->state = DTLS_STATE_CLIENTHELLO;
3016 } else if (peer->role == DTLS_SERVER) {
3017 return dtls_send_hello_request(ctx, peer);
3024 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3025 const dtls_peer_type role, const dtls_state_t state,
3026 uint8 *data, size_t data_length) {
3030 /* This will clear the retransmission buffer if we get an expected
3031 * handshake message. We have to make sure that no handshake message
3032 * should get expected when we still should retransmit something, when
3033 * we do everything accordingly to the DTLS 1.2 standard this should
3034 * not be a problem. */
3036 dtls_stop_retransmission(ctx, peer);
3039 /* The following switch construct handles the given message with
3040 * respect to the current internal state for this peer. In case of
3041 * error, it is left with return 0. */
3043 dtls_debug("handle handshake packet of type: %s (%i)\n",
3044 dtls_handshake_type_to_name(data[0]), data[0]);
3047 /************************************************************************
3049 ************************************************************************/
3050 case DTLS_HT_HELLO_VERIFY_REQUEST:
3052 if (state != DTLS_STATE_CLIENTHELLO) {
3053 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3056 err = check_server_hello_verify_request(ctx, peer, data, data_length);
3058 dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3063 case DTLS_HT_SERVER_HELLO:
3065 if (state != DTLS_STATE_CLIENTHELLO) {
3066 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3069 err = check_server_hello(ctx, peer, data, data_length);
3071 dtls_warn("error in check_server_hello err: %i\n", err);
3074 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3075 peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE;
3077 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3078 /* update_hs_hash(peer, data, data_length); */
3083 case DTLS_HT_CERTIFICATE:
3085 if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3086 (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3087 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3089 err = check_server_certificate(ctx, peer, data, data_length);
3091 dtls_warn("error in check_server_certificate err: %i\n", err);
3094 if (role == DTLS_CLIENT) {
3095 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3096 } else if (role == DTLS_SERVER){
3097 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3099 /* update_hs_hash(peer, data, data_length); */
3102 #endif /* DTLS_ECC */
3104 case DTLS_HT_SERVER_KEY_EXCHANGE:
3107 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3108 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3109 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3111 err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3113 #endif /* DTLS_ECC */
3115 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3116 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3117 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3119 err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3121 #endif /* DTLS_PSK */
3124 dtls_warn("error in check_server_key_exchange err: %i\n", err);
3127 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3128 /* update_hs_hash(peer, data, data_length); */
3132 case DTLS_HT_SERVER_HELLO_DONE:
3134 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3135 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3138 err = check_server_hellodone(ctx, peer, data, data_length);
3140 dtls_warn("error in check_server_hellodone err: %i\n", err);
3143 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3144 /* update_hs_hash(peer, data, data_length); */
3148 case DTLS_HT_CERTIFICATE_REQUEST:
3150 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3151 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3154 err = check_certificate_request(ctx, peer, data, data_length);
3156 dtls_warn("error in check_certificate_request err: %i\n", err);
3162 case DTLS_HT_FINISHED:
3163 /* expect a Finished message from server */
3165 if (state != DTLS_STATE_WAIT_FINISHED) {
3166 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3169 err = check_finished(ctx, peer, data, data_length);
3171 dtls_warn("error in check_finished err: %i\n", err);
3174 if (role == DTLS_SERVER) {
3175 /* send ServerFinished */
3176 update_hs_hash(peer, data, data_length);
3178 /* send change cipher spec message and switch to new configuration */
3179 err = dtls_send_ccs(ctx, peer);
3181 dtls_warn("cannot send CCS message\n");
3185 dtls_security_params_switch(peer);
3187 err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3189 dtls_warn("sending server Finished failed\n");
3193 dtls_handshake_free(peer->handshake_params);
3194 peer->handshake_params = NULL;
3195 dtls_debug("Handshake complete\n");
3197 peer->state = DTLS_STATE_CONNECTED;
3199 /* return here to not increase the message receive counter */
3202 /************************************************************************
3204 ************************************************************************/
3206 case DTLS_HT_CLIENT_KEY_EXCHANGE:
3207 /* handle ClientHello, update msg and msglen and goto next if not finished */
3209 if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3210 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3213 err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3215 dtls_warn("error in check_client_keyexchange err: %i\n", err);
3218 update_hs_hash(peer, data, data_length);
3220 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3221 is_ecdsa_client_auth_supported(ctx))
3222 peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY;
3224 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3228 case DTLS_HT_CERTIFICATE_VERIFY:
3230 if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
3231 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3234 err = check_client_certificate_verify(ctx, peer, data, data_length);
3236 dtls_warn("error in check_client_certificate_verify err: %i\n", err);
3240 update_hs_hash(peer, data, data_length);
3241 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3243 #endif /* DTLS_ECC */
3245 case DTLS_HT_CLIENT_HELLO:
3247 if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
3248 (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
3249 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3252 /* When no DTLS state exists for this peer, we only allow a
3253 Client Hello message with
3255 a) a valid cookie, or
3258 Anything else will be rejected. Fragementation is not allowed
3259 here as it would require peer state as well.
3261 err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
3263 dtls_warn("error in dtls_verify_peer err: %i\n", err);
3268 dtls_debug("server hello verify was sent\n");
3272 /* At this point, we have a good relationship with this peer. This
3273 * state is left for re-negotiation of key material. */
3274 /* As per RFC 6347 - section 4.2.8 if this is an attempt to
3275 * rehandshake, we can delete the existing key material
3276 * as the client has demonstrated reachibility by completing
3277 * the cookie exchange */
3278 if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
3279 dtls_debug("removing the peer\n");
3280 #ifndef WITH_CONTIKI
3281 HASH_DEL_PEER(ctx->peers, peer);
3282 #else /* WITH_CONTIKI */
3283 list_remove(ctx->peers, peer);
3284 #endif /* WITH_CONTIKI */
3286 dtls_free_peer(peer);
3290 dtls_debug("creating new peer\n");
3291 dtls_security_parameters_t *security;
3293 /* msg contains a Client Hello with a valid cookie, so we can
3294 * safely create the server state machine and continue with
3296 peer = dtls_new_peer(session);
3298 dtls_alert("cannot create peer\n");
3299 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3301 peer->role = DTLS_SERVER;
3303 /* Initialize record sequence number to 1 for new peers. The first
3304 * record with sequence number 0 is a stateless Hello Verify Request.
3306 security = dtls_security_params(peer);
3308 dtls_add_peer(ctx, peer);
3310 if (peer && !peer->handshake_params) {
3311 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3313 peer->handshake_params = dtls_handshake_new();
3314 if (!peer->handshake_params)
3315 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3317 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3318 peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
3319 peer->handshake_params->hs_state.mseq_s = 1;
3322 clear_hs_hash(peer);
3324 /* First negotiation step: check for PSK
3326 * Note that we already have checked that msg is a Handshake
3327 * message containing a ClientHello. dtls_get_cipher() therefore
3328 * does not check again.
3330 err = dtls_update_parameters(ctx, peer, data, data_length);
3332 dtls_warn("error updating security parameters\n");
3336 /* update finish MAC */
3337 update_hs_hash(peer, data, data_length);
3339 err = dtls_send_server_hello_msgs(ctx, peer);
3343 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3344 is_ecdsa_client_auth_supported(ctx))
3345 peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE;
3347 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3349 /* after sending the ServerHelloDone, we expect the
3350 * ClientKeyExchange (possibly containing the PSK id),
3351 * followed by a ChangeCipherSpec and an encrypted Finished.
3356 case DTLS_HT_HELLO_REQUEST:
3358 if (state != DTLS_STATE_CONNECTED) {
3359 /* we should just ignore such packets when in handshake */
3363 if (peer && !peer->handshake_params) {
3364 peer->handshake_params = dtls_handshake_new();
3365 if (!peer->handshake_params)
3366 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3368 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3369 peer->handshake_params->hs_state.mseq_r = 0;
3370 peer->handshake_params->hs_state.mseq_s = 0;
3373 /* send ClientHello with empty Cookie */
3374 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3376 dtls_warn("cannot send ClientHello\n");
3379 peer->state = DTLS_STATE_CLIENTHELLO;
3383 dtls_crit("unhandled message %d\n", data[0]);
3384 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3387 if (peer && peer->handshake_params && err >= 0) {
3388 peer->handshake_params->hs_state.mseq_r++;
3395 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3396 const dtls_peer_type role, const dtls_state_t state,
3397 uint8 *data, size_t data_length)
3399 dtls_handshake_header_t *hs_header;
3402 if (data_length < DTLS_HS_LENGTH) {
3403 dtls_warn("handshake message too short\n");
3404 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3406 hs_header = DTLS_HANDSHAKE_HEADER(data);
3408 dtls_debug("received handshake packet of type: %s (%i)\n",
3409 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
3411 if (!peer || !peer->handshake_params) {
3412 /* This is the initial ClientHello */
3413 if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
3414 dtls_warn("If there is no peer only ClientHello is allowed\n");
3415 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3418 /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
3419 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
3420 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
3421 return handle_handshake_msg(ctx, peer, session, role, state, data,
3424 dtls_warn("ignore unexpected handshake message\n");
3429 if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
3430 dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
3431 peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
3433 } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
3434 /* A packet in between is missing, buffer this packet. */
3437 /* TODO: only add packet that are not too new. */
3438 if (data_length > DTLS_MAX_BUF) {
3439 dtls_warn("the packet is too big to buffer for reoder\n");
3443 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
3445 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
3446 if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
3447 dtls_warn("a packet with this sequence number is already stored\n");
3450 node = netq_next(node);
3453 n = netq_node_new(data_length);
3455 dtls_warn("no space in reoder buffer\n");
3460 n->length = data_length;
3461 memcpy(n->data, data, data_length);
3463 if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
3464 dtls_warn("cannot add packet to reoder buffer\n");
3467 dtls_info("Added packet for reordering\n");
3469 } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
3470 /* Found the expected packet, use this and all the buffered packet */
3473 res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
3477 /* We do not know in which order the packet are in the list just search the list for every packet. */
3478 while (next && peer->handshake_params) {
3480 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
3482 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
3484 if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
3485 netq_remove(peer->handshake_params->reorder_queue, node);
3487 res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
3494 node = netq_next(node);
3505 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
3506 uint8 *record_header, uint8 *data, size_t data_length)
3509 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3511 /* A CCS message is handled after a KeyExchange message was
3512 * received from the client. When security parameters have been
3513 * updated successfully and a ChangeCipherSpec message was sent
3514 * by ourself, the security context is switched and the record
3515 * sequence number is reset. */
3517 if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
3518 dtls_warn("expected ChangeCipherSpec during handshake\n");
3522 if (data_length < 1 || data[0] != 1)
3523 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3525 /* Just change the cipher when we are on the same epoch */
3526 if (peer->role == DTLS_SERVER) {
3527 err = calculate_key_block(ctx, handshake, peer,
3528 &peer->session, peer->role);
3534 peer->state = DTLS_STATE_WAIT_FINISHED;
3540 * Handles incoming Alert messages. This function returns \c 1 if the
3541 * connection should be closed and the peer is to be invalidated.
3544 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
3545 uint8 *record_header, uint8 *data, size_t data_length) {
3546 int free_peer = 0; /* indicates whether to free peer */
3548 if (data_length < 2)
3549 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3551 dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
3554 dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
3558 /* The peer object is invalidated for FATAL alerts and close
3559 * notifies. This is done in two steps.: First, remove the object
3560 * from our list of peers. After that, the event handler callback is
3561 * invoked with the still existing peer object. Finally, the storage
3562 * used by peer is released.
3564 if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
3565 dtls_alert("%d invalidate peer\n", data[1]);
3567 #ifndef WITH_CONTIKI
3568 HASH_DEL_PEER(ctx->peers, peer);
3569 #else /* WITH_CONTIKI */
3570 list_remove(ctx->peers, peer);
3573 PRINTF("removed peer [");
3574 PRINT6ADDR(&peer->session.addr);
3575 PRINTF("]:%d\n", uip_ntohs(peer->session.port));
3577 #endif /* WITH_CONTIKI */
3583 (void)CALL(ctx, event, &peer->session,
3584 (dtls_alert_level_t)data[0], (unsigned short)data[1]);
3586 case DTLS_ALERT_CLOSE_NOTIFY:
3587 /* If state is DTLS_STATE_CLOSING, we have already sent a
3588 * close_notify so, do not send that again. */
3589 if (peer->state != DTLS_STATE_CLOSING) {
3590 peer->state = DTLS_STATE_CLOSING;
3591 dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
3593 peer->state = DTLS_STATE_CLOSED;
3600 dtls_stop_retransmission(ctx, peer);
3601 dtls_destroy_peer(ctx, peer, 0);
3607 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
3608 session_t *session, int err)
3613 if (err < -(1 << 8) && err > -(3 << 8)) {
3614 level = ((-err) & 0xff00) >> 8;
3615 desc = (-err) & 0xff;
3617 peer = dtls_get_peer(ctx, session);
3620 peer->state = DTLS_STATE_CLOSING;
3621 return dtls_send_alert(ctx, peer, level, desc);
3623 } else if (err == -1) {
3625 peer = dtls_get_peer(ctx, session);
3628 peer->state = DTLS_STATE_CLOSING;
3629 return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
3636 * Handles incoming data as DTLS message from given peer.
3639 dtls_handle_message(dtls_context_t *ctx,
3641 uint8 *msg, int msglen) {
3642 dtls_peer_t *peer = NULL;
3643 unsigned int rlen; /* record length */
3644 uint8 *data; /* (decrypted) payload */
3645 int data_length; /* length of decrypted payload
3646 (without MAC and padding) */
3649 /* check if we have DTLS state for addr/port/ifindex */
3650 peer = dtls_get_peer(ctx, session);
3653 dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
3654 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
3656 dtls_debug("dtls_handle_message: FOUND PEER\n");
3659 while ((rlen = is_record(msg,msglen))) {
3660 dtls_peer_type role;
3663 dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
3665 data_length = decrypt_verify(peer, msg, rlen, &data);
3666 if (data_length < 0) {
3667 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
3668 data = msg + DTLS_RH_LENGTH;
3669 data_length = rlen - DTLS_RH_LENGTH;
3670 state = DTLS_STATE_WAIT_CLIENTHELLO;
3673 int err = dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
3674 dtls_info("decrypt_verify() failed\n");
3675 if (peer->state < DTLS_STATE_CONNECTED) {
3676 dtls_alert_send_from_err(ctx, peer, &peer->session, err);
3677 peer->state = DTLS_STATE_CLOSED;
3678 /* dtls_stop_retransmission(ctx, peer); */
3679 dtls_destroy_peer(ctx, peer, 1);
3685 state = peer->state;
3688 /* is_record() ensures that msg contains at least a record header */
3689 data = msg + DTLS_RH_LENGTH;
3690 data_length = rlen - DTLS_RH_LENGTH;
3691 state = DTLS_STATE_WAIT_CLIENTHELLO;
3695 dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
3696 dtls_debug_hexdump("receive unencrypted", data, data_length);
3698 /* Handle received record according to the first byte of the
3699 * message, i.e. the subprotocol. We currently do not support
3700 * combining multiple fragments of one type into a single
3705 case DTLS_CT_CHANGE_CIPHER_SPEC:
3707 dtls_stop_retransmission(ctx, peer);
3709 err = handle_ccs(ctx, peer, msg, data, data_length);
3711 dtls_warn("error while handling ChangeCipherSpec message\n");
3712 dtls_alert_send_from_err(ctx, peer, session, err);
3714 /* invalidate peer */
3715 dtls_destroy_peer(ctx, peer, 1);
3724 dtls_stop_retransmission(ctx, peer);
3726 err = handle_alert(ctx, peer, msg, data, data_length);
3727 if (err < 0 || err == 1) {
3728 dtls_warn("received alert, peer has been invalidated\n");
3729 /* handle alert has invalidated peer */
3731 return err < 0 ?err:-1;
3735 case DTLS_CT_HANDSHAKE:
3736 /* Handshake messages other than Finish must use the current
3737 * epoch, Finish has epoch + 1. */
3740 uint16_t expected_epoch = dtls_security_params(peer)->epoch;
3741 uint16_t msg_epoch =
3742 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
3744 /* The new security parameters must be used for all messages
3745 * that are sent after the ChangeCipherSpec message. This
3746 * means that the client's Finished message uses epoch + 1
3747 * while the server is still in the old epoch.
3749 if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
3753 if (expected_epoch != msg_epoch) {
3754 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
3755 state = DTLS_STATE_WAIT_CLIENTHELLO;
3758 dtls_warn("Wrong epoch, expected %i, got: %i\n",
3759 expected_epoch, msg_epoch);
3765 err = handle_handshake(ctx, peer, session, role, state, data, data_length);
3767 dtls_warn("error while handling handshake packet\n");
3768 dtls_alert_send_from_err(ctx, peer, session, err);
3771 if (peer && peer->state == DTLS_STATE_CONNECTED) {
3772 /* stop retransmissions */
3773 dtls_stop_retransmission(ctx, peer);
3774 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
3778 case DTLS_CT_APPLICATION_DATA:
3779 dtls_info("** application data:\n");
3781 dtls_warn("no peer available, send an alert\n");
3782 // TODO: should we send a alert here?
3785 dtls_stop_retransmission(ctx, peer);
3786 CALL(ctx, read, &peer->session, data, data_length);
3789 dtls_info("dropped unknown message of type %d\n",msg[0]);
3792 /* advance msg by length of ciphertext */
3801 dtls_new_context(void *app_data) {
3804 #ifndef WITH_CONTIKI
3805 FILE *urandom = fopen("/dev/urandom", "r");
3806 unsigned char buf[sizeof(unsigned long)];
3807 #endif /* WITH_CONTIKI */
3811 /* FIXME: need something better to init PRNG here */
3812 dtls_prng_init(now);
3813 #else /* WITH_CONTIKI */
3815 dtls_emerg("cannot initialize PRNG\n");
3819 if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
3820 dtls_emerg("cannot initialize PRNG\n");
3825 dtls_prng_init((unsigned long)*buf);
3826 #endif /* WITH_CONTIKI */
3828 c = malloc_context();
3832 memset(c, 0, sizeof(dtls_context_t));
3835 LIST_STRUCT_INIT(c, sendqueue);
3838 LIST_STRUCT_INIT(c, peers);
3839 /* LIST_STRUCT_INIT(c, key_store); */
3841 process_start(&dtls_retransmit_process, (char *)c);
3842 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
3843 /* the retransmit timer must be initialized to some large value */
3844 etimer_set(&c->retransmit_timer, 0xFFFF);
3845 PROCESS_CONTEXT_END(&coap_retransmit_process);
3846 #endif /* WITH_CONTIKI */
3848 if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
3849 c->cookie_secret_age = now;
3856 dtls_alert("cannot create DTLS context\n");
3858 dtls_free_context(c);
3863 dtls_free_context(dtls_context_t *ctx) {
3870 #ifndef WITH_CONTIKI
3874 HASH_ITER(hh, ctx->peers, p, tmp) {
3875 dtls_destroy_peer(ctx, p, 1);
3878 #else /* WITH_CONTIKI */
3879 for (p = list_head(ctx->peers); p; p = list_item_next(p))
3880 dtls_destroy_peer(ctx, p, 1);
3881 #endif /* WITH_CONTIKI */
3887 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
3894 /* check if the same peer is already in our list */
3895 if (peer == dtls_get_peer(ctx, &peer->session)) {
3896 dtls_debug("found peer, try to re-connect\n");
3897 return dtls_renegotiate(ctx, &peer->session);
3900 /* set local peer role to client, remote is server */
3901 peer->role = DTLS_CLIENT;
3903 dtls_add_peer(ctx, peer);
3905 /* send ClientHello with empty Cookie */
3906 peer->handshake_params = dtls_handshake_new();
3907 if (!peer->handshake_params)
3910 peer->handshake_params->hs_state.mseq_r = 0;
3911 peer->handshake_params->hs_state.mseq_s = 0;
3912 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3913 res = dtls_send_client_hello(ctx, peer, NULL, 0);
3915 dtls_warn("cannot send ClientHello\n");
3917 peer->state = DTLS_STATE_CLIENTHELLO;
3923 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
3927 peer = dtls_get_peer(ctx, dst);
3930 peer = dtls_new_peer(dst);
3933 dtls_crit("cannot create new peer\n");
3937 res = dtls_connect_peer(ctx, peer);
3939 /* Invoke event callback to indicate connection attempt or
3940 * re-negotiation. */
3942 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
3943 } else if (res == 0) {
3944 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
3951 dtls_retransmit(dtls_context_t *context, netq_t *node) {
3952 if (!context || !node)
3955 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
3956 if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
3957 unsigned char sendbuf[DTLS_MAX_BUF];
3958 size_t len = sizeof(sendbuf);
3960 unsigned char *data = node->data;
3961 size_t length = node->length;
3963 dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
3966 node->retransmit_cnt++;
3967 node->t = now + (node->timeout << node->retransmit_cnt);
3968 netq_insert_node(context->sendqueue, node);
3970 if (node->type == DTLS_CT_HANDSHAKE) {
3971 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3973 dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
3974 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
3976 dtls_debug("** retransmit packet\n");
3979 err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
3982 dtls_warn("can not retransmit packet, err: %i\n", err);
3985 dtls_debug_hexdump("retransmit header", sendbuf,
3986 sizeof(dtls_record_header_t));
3987 dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
3989 (void)CALL(context, write, &node->peer->session, sendbuf, len);
3993 /* no more retransmissions, remove node from system */
3995 dtls_debug("** removed transaction\n");
3997 /* And finally delete the node */
3998 netq_node_free(node);
4002 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4004 node = list_head(context->sendqueue);
4007 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4009 node = list_item_next(node);
4010 list_remove(context->sendqueue, tmp);
4011 netq_node_free(tmp);
4013 node = list_item_next(node);
4018 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
4020 netq_t *node = netq_head(context->sendqueue);
4023 while (node && node->t <= now) {
4024 netq_pop_first(context->sendqueue);
4025 dtls_retransmit(context, node);
4026 node = netq_head(context->sendqueue);
4034 /*---------------------------------------------------------------------------*/
4035 /* message retransmission */
4036 /*---------------------------------------------------------------------------*/
4037 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4044 dtls_debug("Started DTLS retransmit process\r\n");
4048 if (ev == PROCESS_EVENT_TIMER) {
4049 if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4051 node = list_head(the_dtls_context.sendqueue);
4054 if (node && node->t <= now) {
4055 dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
4056 node = list_head(the_dtls_context.sendqueue);
4059 /* need to set timer to some value even if no nextpdu is available */
4061 etimer_set(&the_dtls_context.retransmit_timer,
4062 node->t <= now ? 1 : node->t - now);
4064 etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4072 #endif /* WITH_CONTIKI */