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_SKEXEC_ECDH_ANON_LENGTH (1 + 2 + 1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
83 #define DTLS_SKEXECPSK_LENGTH_MIN 2
84 #define DTLS_SKEXECPSK_LENGTH_MAX 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN
85 #define DTLS_CKXPSK_LENGTH_MIN 2
86 #define DTLS_CKXEC_LENGTH (1 + 1 + DTLS_EC_KEY_SIZE + DTLS_EC_KEY_SIZE)
87 #define DTLS_CV_LENGTH (1 + 1 + 2 + 1 + 1 + 1 + 1 + DTLS_EC_KEY_SIZE + 1 + 1 + DTLS_EC_KEY_SIZE)
88 #define DTLS_FIN_LENGTH 12
90 #define HS_HDR_LENGTH DTLS_RH_LENGTH + DTLS_HS_LENGTH
91 #define HV_HDR_LENGTH HS_HDR_LENGTH + DTLS_HV_LENGTH
93 #define HIGH(V) (((V) >> 8) & 0xff)
94 #define LOW(V) ((V) & 0xff)
96 #define DTLS_RECORD_HEADER(M) ((dtls_record_header_t *)(M))
97 #define DTLS_HANDSHAKE_HEADER(M) ((dtls_handshake_header_t *)(M))
99 #define HANDSHAKE(M) ((dtls_handshake_header_t *)((M) + DTLS_RH_LENGTH))
100 #define CLIENTHELLO(M) ((dtls_client_hello_t *)((M) + HS_HDR_LENGTH))
102 /* The length check here should work because dtls_*_to_int() works on
103 * unsigned char. Otherwise, broken messages could cause severe
104 * trouble. Note that this macro jumps out of the current program flow
105 * when the message is too short. Beware!
107 #define SKIP_VAR_FIELD(P,L,T) { \
108 if (L < dtls_ ## T ## _to_int(P) + sizeof(T)) \
110 L -= dtls_ ## T ## _to_int(P) + sizeof(T); \
111 P += dtls_ ## T ## _to_int(P) + sizeof(T); \
114 /* some constants for the PRF */
115 #define PRF_LABEL(Label) prf_label_##Label
116 #define PRF_LABEL_SIZE(Label) (sizeof(PRF_LABEL(Label)) - 1)
118 static const unsigned char prf_label_master[] = "master secret";
119 static const unsigned char prf_label_key[] = "key expansion";
120 static const unsigned char prf_label_client[] = "client";
121 static const unsigned char prf_label_server[] = "server";
122 static const unsigned char prf_label_finished[] = " finished";
124 /* first part of Raw public key, the is the start of the Subject Public Key */
125 static const unsigned char cert_asn1_header[] = {
126 0x30, 0x59, /* SEQUENCE, length 89 bytes */
127 0x30, 0x13, /* SEQUENCE, length 19 bytes */
128 0x06, 0x07, /* OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1) */
129 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01,
130 0x06, 0x08, /* OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7) */
131 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07,
132 0x03, 0x42, 0x00, /* BIT STRING, length 66 bytes, 0 bits unused */
133 0x04 /* uncompressed, followed by the r und s values of the public key */
137 PROCESS(dtls_retransmit_process, "DTLS retransmit process");
139 static dtls_context_t the_dtls_context;
141 INLINE_API dtls_context_t *
143 return &the_dtls_context;
147 free_context(dtls_context_t *context) {
150 #else /* WITH_CONTIKI */
152 INLINE_API dtls_context_t *
154 return (dtls_context_t *)malloc(sizeof(dtls_context_t));
158 free_context(dtls_context_t *context) {
172 dtls_enables_anon_ecdh(dtls_context_t* ctx, dtls_cipher_enable_t is_enable)
176 ctx->is_anon_ecdh_eabled = is_enable;
181 dtls_select_cipher(dtls_context_t* ctx, const dtls_cipher_t cipher)
185 ctx->selected_cipher = cipher;
189 /* Calls cb_alert() with given arguments if defined, otherwise an
190 * error message is logged and the result is -1. This is just an
193 #define CALL(Context, which, ...) \
194 ((Context)->h && (Context)->h->which \
195 ? (Context)->h->which((Context), ##__VA_ARGS__) \
199 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
200 dtls_security_parameters_t *security , session_t *session,
201 unsigned char type, uint8 *buf_array[],
202 size_t buf_len_array[], size_t buf_array_len);
205 * Sends the fragment of length \p buflen given in \p buf to the
206 * specified \p peer. The data will be MAC-protected and encrypted
207 * according to the selected cipher and split into one or more DTLS
208 * records of the specified \p type. This function returns the number
209 * of bytes that were sent, or \c -1 if an error occurred.
211 * \param ctx The DTLS context to use.
212 * \param peer The remote peer.
213 * \param type The content type of the record.
214 * \param buf The data to send.
215 * \param buflen The actual length of \p buf.
216 * \return Less than zero on error, the number of bytes written otherwise.
219 dtls_send(dtls_context_t *ctx, dtls_peer_t *peer, unsigned char type,
220 uint8 *buf, size_t buflen) {
221 return dtls_send_multi(ctx, peer, dtls_security_params(peer), &peer->session,
222 type, &buf, &buflen, 1);
226 * Stops ongoing retransmissions of handshake messages for @p peer.
228 static void dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer);
231 * Starts retransmissions of handshake messages for @p peer.
233 static void dtls_start_retransmission(dtls_context_t *context, dtls_peer_t *peer);
236 * Clears retransmissions of handshake messages for @p peer.
238 static void dtls_clear_retransmission(dtls_context_t *context, dtls_peer_t *peer);
241 dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
242 dtls_peer_t *p = NULL;
245 HASH_FIND_PEER(ctx->peers, session, p);
246 #else /* WITH_CONTIKI */
247 for (p = list_head(ctx->peers); p; p = list_item_next(p))
248 if (dtls_session_equals(&p->session, session))
250 #endif /* WITH_CONTIKI */
256 dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
258 HASH_ADD_PEER(ctx->peers, session, peer);
259 #else /* WITH_CONTIKI */
260 list_add(ctx->peers, peer);
261 #endif /* WITH_CONTIKI */
265 dtls_write(struct dtls_context_t *ctx,
266 session_t *dst, uint8 *buf, size_t len) {
268 dtls_peer_t *peer = dtls_get_peer(ctx, dst);
270 /* Check if peer connection already exists */
271 if (!peer) { /* no ==> create one */
274 /* dtls_connect() returns a value greater than zero if a new
275 * connection attempt is made, 0 for session reuse. */
276 res = dtls_connect(ctx, dst);
278 return (res >= 0) ? 0 : res;
279 } else { /* a session exists, check if it is in state connected */
281 if (peer->state != DTLS_STATE_CONNECTED) {
284 return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
290 dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie) {
291 /* To access the cookie, we have to determine the session id's
292 * length and skip the whole thing. */
293 if (msglen < DTLS_HS_LENGTH + DTLS_CH_LENGTH + sizeof(uint8))
294 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
296 if (dtls_uint16_to_int(msg + DTLS_HS_LENGTH) != DTLS_VERSION)
297 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
299 msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
300 msg += DTLS_HS_LENGTH + DTLS_CH_LENGTH;
302 SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
304 if (msglen < (*msg & 0xff) + sizeof(uint8))
305 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
307 *cookie = msg + sizeof(uint8);
308 return dtls_uint8_to_int(msg);
311 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
315 dtls_create_cookie(dtls_context_t *ctx,
317 uint8 *msg, size_t msglen,
318 uint8 *cookie, int *clen) {
319 unsigned char buf[DTLS_HMAC_MAX];
323 /* create cookie with HMAC-SHA256 over:
325 * - session parameters (only IP address?)
327 * - random gmt and bytes
330 * - compression method
333 /* We use our own buffer as hmac_context instead of a dynamic buffer
334 * created by dtls_hmac_new() to separate storage space for cookie
335 * creation from storage that is used in real sessions. Note that
336 * the buffer size must fit with the default hash algorithm (see
337 * implementation of dtls_hmac_context_new()). */
339 dtls_hmac_context_t hmac_context;
340 dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
342 dtls_hmac_update(&hmac_context,
343 (unsigned char *)&session->addr, session->size);
345 /* feed in the beginning of the Client Hello up to and including the
347 e = sizeof(dtls_client_hello_t);
348 e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
349 if (e + DTLS_HS_LENGTH > msglen)
350 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
352 dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
354 /* skip cookie bytes and length byte */
355 e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
357 if (e + DTLS_HS_LENGTH > msglen)
358 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
360 dtls_hmac_update(&hmac_context,
361 msg + DTLS_HS_LENGTH + e,
362 dtls_get_fragment_length(DTLS_HANDSHAKE_HEADER(msg)) - e);
364 len = dtls_hmac_finalize(&hmac_context, buf);
367 memset(cookie + len, 0, *clen - len);
371 memcpy(cookie, buf, *clen);
375 #ifdef DTLS_CHECK_CONTENTTYPE
376 /* used to check if a received datagram contains a DTLS message */
377 static char const content_types[] = {
378 DTLS_CT_CHANGE_CIPHER_SPEC,
381 DTLS_CT_APPLICATION_DATA,
387 * Checks if \p msg points to a valid DTLS record. If
391 is_record(uint8 *msg, size_t msglen) {
392 unsigned int rlen = 0;
394 if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
395 #ifdef DTLS_CHECK_CONTENTTYPE
396 && strchr(content_types, msg[0])
398 && msg[1] == HIGH(DTLS_VERSION)
399 && msg[2] == LOW(DTLS_VERSION))
401 rlen = DTLS_RH_LENGTH +
402 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->length);
404 /* we do not accept wrong length field in record header */
413 * Initializes \p buf as record header. The caller must ensure that \p
414 * buf is capable of holding at least \c sizeof(dtls_record_header_t)
415 * bytes. Increments sequence number counter of \p security.
416 * \return pointer to the next byte after the written header.
417 * The length will be set to 0 and has to be changed before sending.
420 dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
423 dtls_int_to_uint8(buf, type);
424 buf += sizeof(uint8);
426 dtls_int_to_uint16(buf, DTLS_VERSION);
427 buf += sizeof(uint16);
430 dtls_int_to_uint16(buf, security->epoch);
431 buf += sizeof(uint16);
433 dtls_int_to_uint48(buf, security->rseq);
434 buf += sizeof(uint48);
436 /* increment record sequence counter by 1 */
439 memset(buf, 0, sizeof(uint16) + sizeof(uint48));
440 buf += sizeof(uint16) + sizeof(uint48);
443 memset(buf, 0, sizeof(uint16));
444 return buf + sizeof(uint16);
448 * Initializes \p buf as handshake header. The caller must ensure that \p
449 * buf is capable of holding at least \c sizeof(dtls_handshake_header_t)
450 * bytes. Increments message sequence number counter of \p peer.
451 * \return pointer to the next byte after \p buf
454 dtls_set_handshake_header(uint8 type, dtls_peer_t *peer,
456 int frag_offset, int frag_length,
459 dtls_int_to_uint8(buf, type);
460 buf += sizeof(uint8);
462 dtls_int_to_uint24(buf, length);
463 buf += sizeof(uint24);
465 if (peer && peer->handshake_params) {
466 /* and copy the result to buf */
467 dtls_int_to_uint16(buf, peer->handshake_params->hs_state.mseq_s);
469 /* increment handshake message sequence counter by 1 */
470 peer->handshake_params->hs_state.mseq_s++;
472 memset(buf, 0, sizeof(uint16));
474 buf += sizeof(uint16);
476 dtls_int_to_uint24(buf, frag_offset);
477 buf += sizeof(uint24);
479 dtls_int_to_uint24(buf, frag_length);
480 buf += sizeof(uint24);
485 /** only one compression method is currently defined */
486 static uint8 compression_methods[] = {
490 /** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
491 INLINE_API int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
493 #if defined(DTLS_ECC) || defined(DTLS_X509)
494 return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
497 #endif /* DTLS_ECC */
500 /** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
501 INLINE_API int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
504 return cipher == TLS_PSK_WITH_AES_128_CCM_8;
507 #endif /* DTLS_PSK */
510 /** returns true if the cipher matches TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
511 INLINE_API int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
514 return cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256;
520 /** returns true if the cipher matches TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 */
521 INLINE_API int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
523 #if defined(DTLS_ECC) && defined(DTLS_PSK)
524 return cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256;
527 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
532 /** returns true if the application is configured for psk */
533 INLINE_API int is_psk_supported(dtls_context_t *ctx)
536 return ctx && ctx->h && ctx->h->get_psk_info;
539 #endif /* DTLS_PSK */
542 /** returns true if the application is configured for ecdhe_ecdsa */
543 INLINE_API int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
546 return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
547 (is_client && ctx->h->verify_ecdsa_key));
550 #endif /* DTLS_ECC */
553 /** returns true if the application is configured for x509 */
554 INLINE_API int is_x509_supported(dtls_context_t *ctx, int is_client)
557 return ctx && ctx->h && ((!is_client && ctx->h->get_x509_cert) ||
558 (is_client && ctx->h->verify_x509_cert));
561 #endif /* DTLS_X509 */
564 /** Returns true if the application is configured for ecdhe_ecdsa with
565 * client authentication */
566 INLINE_API int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
569 return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
572 #endif /* DTLS_ECC */
575 /** Returns true if the application is configured for x509 with
576 * client authentication */
577 INLINE_API int is_x509_client_auth_supported(dtls_context_t *ctx)
580 return ctx && ctx->h && ctx->h->get_x509_cert && ctx->h->verify_x509_cert;
583 #endif /* DTLS_X509 */
586 /** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
587 INLINE_API int is_ecdh_anon_supported(dtls_context_t *ctx)
590 return ctx && (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
596 /** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
597 INLINE_API int is_ecdhe_psk_supported(dtls_context_t *ctx)
599 #if defined(DTLS_ECC) && defined(DTLS_PSK)
600 return is_psk_supported(ctx);
603 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
608 * Returns @c 1 if @p code is a cipher suite other than @c
609 * TLS_NULL_WITH_NULL_NULL that we recognize.
611 * @param ctx The current DTLS context
612 * @param code The cipher suite identifier to check
613 * @param is_client 1 for a dtls client, 0 for server
614 * @return @c 1 iff @p code is recognized,
617 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
624 psk = is_psk_supported(ctx);
625 ecdsa = is_ecdsa_supported(ctx, is_client);
626 ecdh_anon = is_ecdh_anon_supported(ctx);
627 ecdhe_psk = is_ecdhe_psk_supported(ctx);
628 x509 = is_x509_supported(ctx, is_client);
630 return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
631 (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code)) ||
632 (ecdh_anon && is_tls_ecdh_anon_with_aes_128_cbc_sha_256(code)) ||
633 (ecdhe_psk && is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(code)) ||
634 (x509 && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
638 * This method detects if we already have a established DTLS session with
639 * peer and the peer is attempting to perform a fresh handshake by sending
640 * messages with epoch = 0. This is to handle situations mentioned in
641 * RFC 6347 - section 4.2.8.
643 * @param msg The packet received from Client
644 * @param msglen Packet length
645 * @param peer peer who is the sender for this packet
646 * @return @c 1 if this is a rehandshake attempt by
650 hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
653 if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
654 if (msg[0] == DTLS_CT_HANDSHAKE) {
655 uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
656 if (msg_epoch == 0) {
657 dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
658 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
659 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
668 /** Dump out the cipher keys and IVs used for the symetric cipher. */
669 static void dtls_debug_keyblock(dtls_security_parameters_t *config)
671 dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
672 dtls_debug_dump(" client_MAC_secret",
673 dtls_kb_client_mac_secret(config, peer->role),
674 dtls_kb_mac_secret_size(config->cipher));
676 dtls_debug_dump(" server_MAC_secret",
677 dtls_kb_server_mac_secret(config, peer->role),
678 dtls_kb_mac_secret_size(config->cipher));
680 dtls_debug_dump(" client_write_key",
681 dtls_kb_client_write_key(config, peer->role),
682 dtls_kb_key_size(config, peer->role));
684 dtls_debug_dump(" server_write_key",
685 dtls_kb_server_write_key(config, peer->role),
686 dtls_kb_key_size(config, peer->role));
688 dtls_debug_dump(" client_IV",
689 dtls_kb_client_iv(config, peer->role),
690 dtls_kb_iv_size(config->cipher));
692 dtls_debug_dump(" server_IV",
693 dtls_kb_server_iv(config, peer->role),
694 dtls_kb_iv_size(config->cipher));
697 /** returns the name of the goven handshake type number.
698 * see IANA for a full list of types:
699 * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
701 static char *dtls_handshake_type_to_name(int type)
704 case DTLS_HT_HELLO_REQUEST:
705 return "hello_request";
706 case DTLS_HT_CLIENT_HELLO:
707 return "client_hello";
708 case DTLS_HT_SERVER_HELLO:
709 return "server_hello";
710 case DTLS_HT_HELLO_VERIFY_REQUEST:
711 return "hello_verify_request";
712 case DTLS_HT_CERTIFICATE:
713 return "certificate";
714 case DTLS_HT_SERVER_KEY_EXCHANGE:
715 return "server_key_exchange";
716 case DTLS_HT_CERTIFICATE_REQUEST:
717 return "certificate_request";
718 case DTLS_HT_SERVER_HELLO_DONE:
719 return "server_hello_done";
720 case DTLS_HT_CERTIFICATE_VERIFY:
721 return "certificate_verify";
722 case DTLS_HT_CLIENT_KEY_EXCHANGE:
723 return "client_key_exchange";
724 case DTLS_HT_FINISHED:
732 * Calculate the pre master secret and after that calculate the master-secret.
735 calculate_key_block(dtls_context_t *ctx,
736 dtls_handshake_parameters_t *handshake,
739 dtls_peer_type role) {
740 #if defined(DTLS_PSK) && defined(DTLS_ECC)
741 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH + uECC_BYTES];
743 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH];
744 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
745 int pre_master_len = 0;
746 dtls_security_parameters_t *security = dtls_security_params_next(peer);
747 uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
750 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
753 switch (handshake->cipher) {
755 case TLS_PSK_WITH_AES_128_CCM_8: {
756 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
759 len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
760 handshake->keyx.psk.identity,
761 handshake->keyx.psk.id_length,
762 psk, DTLS_PSK_MAX_KEY_LEN);
764 dtls_crit("no psk key for session available\n");
767 /* Temporarily use the key_block storage space for the pre master secret. */
768 pre_master_len = dtls_psk_pre_master_secret(psk, len,
770 MAX_KEYBLOCK_LENGTH);
772 dtls_debug_hexdump("psk", psk, len);
774 memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
775 if (pre_master_len < 0) {
776 dtls_crit("the psk was too long, for the pre master secret\n");
777 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
782 #endif /* DTLS_PSK */
783 #if defined(DTLS_ECC) || defined(DTLS_X509)
784 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
785 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
786 pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecc.own_eph_priv,
787 handshake->keyx.ecc.other_eph_pub_x,
788 handshake->keyx.ecc.other_eph_pub_y,
789 sizeof(handshake->keyx.ecc.own_eph_priv),
791 MAX_KEYBLOCK_LENGTH);
792 if (pre_master_len < 0) {
793 dtls_crit("the curve was too long, for the pre master secret\n");
794 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
798 #endif /* DTLS_ECC */
799 #if defined(DTLS_PSK) && defined(DTLS_ECC)
800 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
801 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
804 psklen = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
805 handshake->keyx.psk.identity,
806 handshake->keyx.psk.id_length,
807 psk, DTLS_PSK_MAX_KEY_LEN);
809 dtls_crit("no psk key for session available\n");
813 pre_master_len = dtls_ecdhe_psk_pre_master_secret(psk, psklen,
814 handshake->keyx.ecc.own_eph_priv,
815 handshake->keyx.ecc.other_eph_pub_x,
816 handshake->keyx.ecc.other_eph_pub_y,
817 sizeof(handshake->keyx.ecc.own_eph_priv),
819 MAX_KEYBLOCK_LENGTH + uECC_BYTES);
821 if (pre_master_len < 0) {
822 dtls_crit("the curve was too long, for the pre master secret\n");
823 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
827 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
829 dtls_crit("calculate_key_block: unknown cipher\n");
830 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
833 dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
834 dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
835 dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
837 dtls_prf(pre_master_secret, pre_master_len,
838 PRF_LABEL(master), PRF_LABEL_SIZE(master),
839 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
840 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
842 DTLS_MASTER_SECRET_LENGTH);
844 dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
846 /* create key_block from master_secret
847 * key_block = PRF(master_secret,
848 "key expansion" + tmp.random.server + tmp.random.client) */
849 security->cipher = handshake->cipher;
850 security->compression = handshake->compression;
853 dtls_prf(master_secret,
854 DTLS_MASTER_SECRET_LENGTH,
855 PRF_LABEL(key), PRF_LABEL_SIZE(key),
856 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
857 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
859 dtls_kb_size(security, role));
861 memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
862 dtls_debug_keyblock(security);
868 /* TODO: add a generic method which iterates over a list and searches for a specific key */
869 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
872 /* length of curve list */
873 i = dtls_uint16_to_int(data);
874 data += sizeof(uint16);
875 if (i + sizeof(uint16) != data_length) {
876 dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
877 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
880 for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
881 /* check if this curve is supported */
882 curve_name = dtls_uint16_to_int(data);
883 data += sizeof(uint16);
885 if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
889 dtls_warn("no supported elliptic curve found\n");
890 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
893 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
896 /* length of cert type list */
897 i = dtls_uint8_to_int(data);
898 data += sizeof(uint8);
899 if (i + sizeof(uint8) != data_length) {
900 dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
901 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
904 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
905 /* check if this cert type is supported */
906 cert_type = dtls_uint8_to_int(data);
907 data += sizeof(uint8);
910 if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
913 if (cert_type == TLS_CERT_TYPE_X509)
918 dtls_warn("no supported certificate type found\n");
919 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
922 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
925 /* length of ec_point_formats list */
926 i = dtls_uint8_to_int(data);
927 data += sizeof(uint8);
928 if (i + sizeof(uint8) != data_length) {
929 dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
930 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
933 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
934 /* check if this ec_point_format is supported */
935 cert_type = dtls_uint8_to_int(data);
936 data += sizeof(uint8);
938 if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
942 dtls_warn("no supported ec_point_format found\n");
943 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
947 * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
950 dtls_check_tls_extension(dtls_peer_t *peer,
951 uint8 *data, size_t data_length, int client_hello)
954 int ext_elliptic_curve = 0;
955 int ext_client_cert_type = 0;
956 int ext_server_cert_type = 0;
957 int ext_ec_point_formats = 0;
958 dtls_handshake_parameters_t *handshake = peer->handshake_params;
960 if (data_length < sizeof(uint16)) {
961 /* no tls extensions specified */
962 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
968 /* get the length of the tls extension list */
969 j = dtls_uint16_to_int(data);
970 data += sizeof(uint16);
971 data_length -= sizeof(uint16);
976 /* check for TLS extensions needed for this cipher */
977 while (data_length) {
978 if (data_length < sizeof(uint16) * 2)
981 /* get the tls extension type */
982 i = dtls_uint16_to_int(data);
983 data += sizeof(uint16);
984 data_length -= sizeof(uint16);
986 /* get the length of the tls extension */
987 j = dtls_uint16_to_int(data);
988 data += sizeof(uint16);
989 data_length -= sizeof(uint16);
995 case TLS_EXT_ELLIPTIC_CURVES:
996 ext_elliptic_curve = 1;
997 if (verify_ext_eliptic_curves(data, j))
1000 case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
1001 ext_client_cert_type = 1;
1003 if (verify_ext_cert_type(data, j))
1007 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
1009 if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
1010 (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1015 case TLS_EXT_SERVER_CERTIFICATE_TYPE:
1016 ext_server_cert_type = 1;
1018 if (verify_ext_cert_type(data, j))
1022 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
1024 if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
1025 (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1030 case TLS_EXT_EC_POINT_FORMATS:
1031 ext_ec_point_formats = 1;
1032 if (verify_ext_ec_point_formats(data, j))
1035 case TLS_EXT_ENCRYPT_THEN_MAC:
1036 /* As only AEAD cipher suites are currently available, this
1037 * extension can be skipped.
1039 dtls_info("skipped encrypt-then-mac extension\n");
1042 dtls_warn("unsupported tls extension: %i\n", i);
1048 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
1049 if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
1050 || !ext_ec_point_formats) {
1051 dtls_warn("not all required tls extensions found in client hello\n");
1054 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
1055 if (!ext_client_cert_type || !ext_server_cert_type) {
1056 dtls_warn("not all required tls extensions found in server hello\n");
1063 if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
1064 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1066 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1071 * Parses the ClientHello from the client and updates the internal handshake
1072 * parameters with the new data for the given \p peer. When the ClientHello
1073 * handshake message in \p data does not contain a cipher suite or
1074 * compression method, it is copied from the the current security parameters.
1076 * \param ctx The current DTLS context.
1077 * \param peer The remote peer whose security parameters are about to change.
1078 * \param data The handshake message with a ClientHello.
1079 * \param data_length The actual size of \p data.
1080 * \return \c -Something if an error occurred, \c 0 on success.
1083 dtls_update_parameters(dtls_context_t *ctx,
1085 uint8 *data, size_t data_length) {
1089 dtls_handshake_parameters_t *config = peer->handshake_params;
1090 dtls_security_parameters_t *security = dtls_security_params(peer);
1093 assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
1095 /* skip the handshake header and client version information */
1096 data += DTLS_HS_LENGTH + sizeof(uint16);
1097 data_length -= DTLS_HS_LENGTH + sizeof(uint16);
1099 /* store client random in config */
1100 memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
1101 data += DTLS_RANDOM_LENGTH;
1102 data_length -= DTLS_RANDOM_LENGTH;
1104 /* Caution: SKIP_VAR_FIELD may jump to error: */
1105 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
1106 SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
1108 i = dtls_uint16_to_int(data);
1109 if (data_length < i + sizeof(uint16)) {
1110 /* Looks like we do not have a cipher nor compression. This is ok
1111 * for renegotiation, but not for the initial handshake. */
1113 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
1116 config->cipher = security->cipher;
1117 config->compression = security->compression;
1122 data += sizeof(uint16);
1123 data_length -= sizeof(uint16) + i;
1127 config->cipher = dtls_uint16_to_int(data);
1128 ok = known_cipher(ctx, config->cipher, 0);
1129 i -= sizeof(uint16);
1130 data += sizeof(uint16);
1133 /* skip remaining ciphers */
1137 /* reset config cipher to a well-defined value */
1138 config->cipher = TLS_NULL_WITH_NULL_NULL;
1139 dtls_warn("No matching cipher found\n");
1143 if (data_length < sizeof(uint8)) {
1144 /* no compression specified, take the current compression method */
1146 config->compression = security->compression;
1148 config->compression = TLS_COMPRESSION_NULL;
1152 i = dtls_uint8_to_int(data);
1153 if (data_length < i + sizeof(uint8))
1156 data += sizeof(uint8);
1157 data_length -= sizeof(uint8) + i;
1161 for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
1162 if (dtls_uint8_to_int(data) == compression_methods[j]) {
1163 config->compression = compression_methods[j];
1167 data += sizeof(uint8);
1171 /* reset config cipher to a well-defined value */
1175 return dtls_check_tls_extension(peer, data, data_length, 1);
1177 if (peer->state == DTLS_STATE_CONNECTED) {
1178 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1180 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1185 * Parse the ClientKeyExchange and update the internal handshake state with
1189 check_client_keyexchange(dtls_context_t *ctx,
1190 dtls_handshake_parameters_t *handshake,
1191 uint8 *data, size_t length) {
1193 #if defined(DTLS_ECC) || defined(DTLS_X509)
1194 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) ||
1195 is_tls_ecdh_anon_with_aes_128_cbc_sha_256(handshake->cipher) ) {
1197 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1198 dtls_debug("The client key exchange is too short\n");
1199 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1201 data += DTLS_HS_LENGTH;
1203 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1204 dtls_alert("expected 65 bytes long public point\n");
1205 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1207 data += sizeof(uint8);
1209 if (dtls_uint8_to_int(data) != 4) {
1210 dtls_alert("expected uncompressed public point\n");
1211 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1213 data += sizeof(uint8);
1215 memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1216 sizeof(handshake->keyx.ecc.other_eph_pub_x));
1217 data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1219 memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1220 sizeof(handshake->keyx.ecc.other_eph_pub_y));
1221 data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1223 #endif /* DTLS_ECC */
1224 #if defined(DTLS_PSK) && defined(DTLS_ECC)
1225 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(handshake->cipher)) {
1228 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1229 dtls_debug("The client key exchange is too short\n");
1230 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1232 data += DTLS_HS_LENGTH;
1235 id_length = dtls_uint16_to_int(data);
1236 data += sizeof(uint16);
1238 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + DTLS_CKXEC_LENGTH + id_length != length) {
1239 dtls_debug("The identity has a wrong length\n");
1240 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1243 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1244 dtls_warn("please use a smaller client identity\n");
1245 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1248 handshake->keyx.psk.id_length = id_length;
1249 memcpy(handshake->keyx.psk.identity, data, id_length);
1253 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1254 dtls_alert("expected 65 bytes long public point\n");
1255 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1257 data += sizeof(uint8);
1259 if (dtls_uint8_to_int(data) != 4) {
1260 dtls_alert("expected uncompressed public point\n");
1261 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1263 data += sizeof(uint8);
1265 memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1266 sizeof(handshake->keyx.ecc.other_eph_pub_x));
1267 data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1269 memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1270 sizeof(handshake->keyx.ecc.other_eph_pub_y));
1271 data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1273 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
1275 if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1278 if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1279 dtls_debug("The client key exchange is too short\n");
1280 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1282 data += DTLS_HS_LENGTH;
1284 id_length = dtls_uint16_to_int(data);
1285 data += sizeof(uint16);
1287 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1288 dtls_debug("The identity has a wrong length\n");
1289 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1292 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1293 dtls_warn("please use a smaller client identity\n");
1294 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1297 handshake->keyx.psk.id_length = id_length;
1298 memcpy(handshake->keyx.psk.identity, data, id_length);
1300 #endif /* DTLS_PSK */
1305 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1306 dtls_debug_dump("add MAC data", data, length);
1307 dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1311 copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
1312 memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1313 sizeof(peer->handshake_params->hs_state.hs_hash));
1317 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
1318 return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1322 clear_hs_hash(dtls_peer_t *peer) {
1324 dtls_debug("clear MAC\n");
1325 dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
1329 * Checks if \p record + \p data contain a Finished message with valid
1332 * \param ctx The current DTLS context.
1333 * \param peer The remote peer of the security association.
1334 * \param data The cleartext payload of the message.
1335 * \param data_length Actual length of \p data.
1336 * \return \c 0 if the Finished message is valid, \c negative number otherwise.
1339 check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
1340 uint8 *data, size_t data_length) {
1341 size_t digest_length, label_size;
1342 const unsigned char *label;
1343 unsigned char buf[DTLS_HMAC_MAX];
1345 if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1346 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1348 /* Use a union here to ensure that sufficient stack space is
1349 * reserved. As statebuf and verify_data are not used at the same
1350 * time, we can re-use the storage safely.
1353 unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1354 unsigned char verify_data[DTLS_FIN_LENGTH];
1357 /* temporarily store hash status for roll-back after finalize */
1358 memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1360 digest_length = finalize_hs_hash(peer, buf);
1363 /* restore hash status */
1364 memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1366 if (peer->role == DTLS_CLIENT) {
1367 label = PRF_LABEL(server);
1368 label_size = PRF_LABEL_SIZE(server);
1369 } else { /* server */
1370 label = PRF_LABEL(client);
1371 label_size = PRF_LABEL_SIZE(client);
1374 dtls_prf(peer->handshake_params->tmp.master_secret,
1375 DTLS_MASTER_SECRET_LENGTH,
1377 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1379 b.verify_data, sizeof(b.verify_data));
1381 dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1382 dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1384 /* compare verify data and create DTLS alert code when they differ */
1385 return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1387 : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
1391 * Prepares the payload given in \p data for sending with
1392 * dtls_send(). The \p data is encrypted and compressed according to
1393 * the current security parameters of \p peer. The result of this
1394 * operation is put into \p sendbuf with a prepended record header of
1395 * type \p type ready for sending. As some cipher suites add a MAC
1396 * before encryption, \p data must be large enough to hold this data
1397 * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
1399 * \param peer The remote peer the packet will be sent to.
1400 * \param security The encryption paramater used to encrypt
1401 * \param type The content type of this record.
1402 * \param data_array Array with payloads in correct order.
1403 * \param data_len_array sizes of the payloads in correct order.
1404 * \param data_array_len The number of payloads given.
1405 * \param sendbuf The output buffer where the encrypted record
1407 * \param rlen This parameter must be initialized with the
1408 * maximum size of \p sendbuf and will be updated
1409 * to hold the actual size of the stored packet
1410 * on success. On error, the value of \p rlen is
1412 * \return Less than zero on error, or greater than zero success.
1415 dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
1417 uint8 *data_array[], size_t data_len_array[],
1418 size_t data_array_len,
1419 uint8 *sendbuf, size_t *rlen) {
1424 if (*rlen < DTLS_RH_LENGTH) {
1425 dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1426 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1429 p = dtls_set_record_header(type, security, sendbuf);
1432 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1433 /* no cipher suite */
1436 for (i = 0; i < data_array_len; i++) {
1437 /* check the minimum that we need for packets that are not encrypted */
1438 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1439 dtls_debug("dtls_prepare_record: send buffer too small\n");
1440 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1443 memcpy(p, data_array[i], data_len_array[i]);
1444 p += data_len_array[i];
1445 res += data_len_array[i];
1447 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
1448 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
1450 unsigned char nonce[DTLS_CBC_IV_LENGTH];
1452 /** Add IV into body of packet in case of AES CBC mode according to RFC 5246, Section 6.2.3.2
1454 * opaque IV[SecurityParameters.record_iv_length];
1455 * block-ciphered struct {
1456 * opaque content[TLSCompressed.length];
1457 * opaque MAC[SecurityParameters.mac_length];
1458 * uint8 padding[GenericBlockCipher.padding_length];
1459 * uint8 padding_length;
1465 dtls_prng(nonce, DTLS_CBC_IV_LENGTH);
1466 memcpy(p , nonce, DTLS_CBC_IV_LENGTH);
1467 p += DTLS_CBC_IV_LENGTH;
1468 res += DTLS_CBC_IV_LENGTH;
1470 for (i = 0; i < data_array_len; i++) {
1471 /* check the minimum that we need for packets that are not encrypted */
1472 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1473 dtls_debug("dtls_prepare_record: send buffer too small\n");
1474 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1477 memcpy(p, data_array[i], data_len_array[i]);
1478 p += data_len_array[i];
1479 res += data_len_array[i];
1482 res = dtls_encrypt(start + DTLS_CBC_IV_LENGTH, res - DTLS_CBC_IV_LENGTH,
1483 start + DTLS_CBC_IV_LENGTH, nonce,
1484 dtls_kb_local_write_key(security, peer->role),
1485 dtls_kb_key_size(security, peer->role),
1486 dtls_kb_local_mac_secret(security, peer->role),
1487 dtls_kb_mac_secret_size(security->cipher),
1493 res += DTLS_CBC_IV_LENGTH;
1495 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1497 * length of additional_data for the AEAD cipher which consists of
1498 * seq_num(2+6) + type(1) + version(2) + length(2)
1500 #define A_DATA_LEN 13
1501 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1502 unsigned char A_DATA[A_DATA_LEN];
1504 if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1505 dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1506 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1507 dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1509 dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1514 The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1515 the "nonce" SHALL be 12 bytes long and is constructed as follows:
1516 (this is an example of a "partially explicit" nonce; see Section
1517 3.2.1 in [RFC5116]).
1521 opaque nonce_explicit[8];
1526 In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1529 When the nonce_explicit is equal to the sequence number, the CCMNonce
1530 will have the structure of the CCMNonceExample given below.
1533 uint32 client_write_IV; // low order 32-bits
1534 uint64 seq_num; // TLS sequence number
1539 uint32 server_write_IV; // low order 32-bits
1540 uint64 seq_num; // TLS sequence number
1552 memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1556 for (i = 0; i < data_array_len; i++) {
1557 /* check the minimum that we need for packets that are not encrypted */
1558 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1559 dtls_debug("dtls_prepare_record: send buffer too small\n");
1560 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1563 memcpy(p, data_array[i], data_len_array[i]);
1564 p += data_len_array[i];
1565 res += data_len_array[i];
1568 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1569 memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1570 dtls_kb_iv_size(security->cipher));
1571 memcpy(nonce + dtls_kb_iv_size(security->cipher), start, 8); /* epoch + seq_num */
1573 dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1574 dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1575 dtls_kb_key_size(security, peer->role));
1577 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1579 * additional_data = seq_num + TLSCompressed.type +
1580 * TLSCompressed.version + TLSCompressed.length;
1582 memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1583 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1584 dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1586 res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1587 dtls_kb_local_write_key(security, peer->role),
1588 dtls_kb_key_size(security, peer->role),
1589 dtls_kb_local_mac_secret(security, peer->role),
1590 dtls_kb_mac_secret_size(security->cipher),
1597 res += 8; /* increment res by size of nonce_explicit */
1598 dtls_debug_dump("message:", start, res);
1601 /* fix length of fragment in sendbuf */
1602 dtls_int_to_uint16(sendbuf + 11, res);
1604 *rlen = DTLS_RH_LENGTH + res;
1609 dtls_send_handshake_msg_hash(dtls_context_t *ctx,
1613 uint8 *data, size_t data_length,
1616 uint8 buf[DTLS_HS_LENGTH];
1617 uint8 *data_array[2];
1618 size_t data_len_array[2];
1620 dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1622 dtls_set_handshake_header(header_type, peer, data_length, 0,
1626 update_hs_hash(peer, buf, sizeof(buf));
1628 data_array[i] = buf;
1629 data_len_array[i] = sizeof(buf);
1634 update_hs_hash(peer, data, data_length);
1636 data_array[i] = data;
1637 data_len_array[i] = data_length;
1640 dtls_debug("send handshake packet of type: %s (%i)\n",
1641 dtls_handshake_type_to_name(header_type), header_type);
1642 return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1643 data_array, data_len_array, i);
1647 dtls_send_handshake_msg(dtls_context_t *ctx,
1650 uint8 *data, size_t data_length)
1652 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1653 header_type, data, data_length, 1);
1657 * Returns true if the message @p Data is a handshake message that
1658 * must be included in the calculation of verify_data in the Finished
1661 * @param Type The message type. Only handshake messages but the initial
1662 * Client Hello and Hello Verify Request are included in the hash,
1663 * @param Data The PDU to examine.
1664 * @param Length The length of @p Data.
1666 * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
1670 #define MUST_HASH(Type, Data, Length) \
1671 ((Type) == DTLS_CT_HANDSHAKE && \
1672 ((Data) != NULL) && ((Length) > 0) && \
1673 ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) && \
1674 ((Data)[0] != DTLS_HT_CLIENT_HELLO || \
1675 ((Length) >= HS_HDR_LENGTH && \
1676 (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) || \
1677 (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1680 * Sends the data passed in @p buf as a DTLS record of type @p type to
1681 * the given peer. The data will be encrypted and compressed according
1682 * to the security parameters for @p peer.
1684 * @param ctx The DTLS context in effect.
1685 * @param peer The remote party where the packet is sent.
1686 * @param type The content type of this record.
1687 * @param buf The data to send.
1688 * @param buflen The number of bytes to send from @p buf.
1689 * @return Less than zero in case of an error or the number of
1690 * bytes that have been sent otherwise.
1693 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
1694 dtls_security_parameters_t *security , session_t *session,
1695 unsigned char type, uint8 *buf_array[],
1696 size_t buf_len_array[], size_t buf_array_len)
1698 /* We cannot use ctx->sendbuf here as it is reserved for collecting
1699 * the input for this function, i.e. buf == ctx->sendbuf.
1701 * TODO: check if we can use the receive buf here. This would mean
1702 * that we might not be able to handle multiple records stuffed in
1703 * one UDP datagram */
1704 unsigned char sendbuf[DTLS_MAX_BUF];
1705 size_t len = sizeof(sendbuf);
1708 size_t overall_len = 0;
1710 res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1715 /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1716 /* update_hs_hash(peer, buf, buflen); */
1718 dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1719 for (i = 0; i < buf_array_len; i++) {
1720 dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1721 overall_len += buf_len_array[i];
1724 if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1725 type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1726 /* copy handshake messages other than HelloVerify into retransmit buffer */
1727 netq_t *n = netq_node_new(overall_len);
1731 n->t = now + 2 * CLOCK_SECOND;
1732 n->retransmit_cnt = 0;
1733 n->timeout = 2 * CLOCK_SECOND;
1735 n->epoch = (security) ? security->epoch : 0;
1738 for (i = 0; i < buf_array_len; i++) {
1739 memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1740 n->length += buf_len_array[i];
1743 if (!netq_insert_node(ctx->sendqueue, n)) {
1744 dtls_warn("cannot add packet to retransmit buffer\n");
1748 /* must set timer within the context of the retransmit process */
1749 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1750 etimer_set(&ctx->retransmit_timer, n->timeout);
1751 PROCESS_CONTEXT_END(&dtls_retransmit_process);
1752 #else /* WITH_CONTIKI */
1753 dtls_debug("copied to sendqueue\n");
1754 #endif /* WITH_CONTIKI */
1757 dtls_warn("retransmit buffer full\n");
1760 /* FIXME: copy to peer's sendqueue (after fragmentation if
1761 * necessary) and initialize retransmit timer */
1762 res = CALL(ctx, write, session, sendbuf, len);
1764 /* Guess number of bytes application data actually sent:
1765 * dtls_prepare_record() tells us in len the number of bytes to
1766 * send, res will contain the bytes actually sent. */
1767 return res <= 0 ? res : overall_len - (len - res);
1771 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
1772 dtls_alert_t description) {
1773 uint8_t msg[] = { level, description };
1775 dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1780 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1784 peer = dtls_get_peer(ctx, remote);
1787 res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
1788 /* indicate tear down */
1789 peer->state = DTLS_STATE_CLOSING;
1794 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1796 if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1797 dtls_close(ctx, &peer->session);
1799 #ifndef WITH_CONTIKI
1800 HASH_DEL_PEER(ctx->peers, peer);
1801 #else /* WITH_CONTIKI */
1802 list_remove(ctx->peers, peer);
1803 #endif /* WITH_CONTIKI */
1805 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1807 dtls_free_peer(peer);
1811 * Checks a received Client Hello message for a valid cookie. When the
1812 * Client Hello contains no cookie, the function fails and a Hello
1813 * Verify Request is sent to the peer (using the write callback function
1814 * registered with \p ctx). The return value is \c -1 on error, \c 0 when
1815 * undecided, and \c 1 if the Client Hello was good.
1817 * \param ctx The DTLS context.
1818 * \param peer The remote party we are talking to, if any.
1819 * \param session Transport address of the remote peer.
1820 * \param state Current state of the connection.
1821 * \param msg The received datagram.
1822 * \param msglen Length of \p msg.
1823 * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
1827 dtls_verify_peer(dtls_context_t *ctx,
1830 const dtls_state_t state,
1831 uint8 *data, size_t data_length)
1833 uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
1835 int len = DTLS_COOKIE_LENGTH;
1836 uint8 *cookie = NULL;
1839 #define mycookie (buf + DTLS_HV_LENGTH)
1841 /* Store cookie where we can reuse it for the HelloVerify request. */
1842 err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1846 dtls_debug_dump("create cookie", mycookie, len);
1848 assert(len == DTLS_COOKIE_LENGTH);
1850 /* Perform cookie check. */
1851 len = dtls_get_cookie(data, data_length, &cookie);
1853 dtls_warn("error while fetching the cookie, err: %i\n", err);
1857 dtls_debug_dump("compare with cookie", cookie, len);
1859 /* check if cookies match */
1860 if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1861 dtls_debug("found matching cookie\n");
1866 dtls_debug_dump("invalid cookie", cookie, len);
1868 dtls_debug("cookie len is 0!\n");
1871 /* ClientHello did not contain any valid cookie, hence we send a
1872 * HelloVerify request. */
1874 dtls_int_to_uint16(p, DTLS_VERSION);
1875 p += sizeof(uint16);
1877 dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
1880 assert(p == mycookie);
1882 p += DTLS_COOKIE_LENGTH;
1884 /* TODO use the same record sequence number as in the ClientHello,
1885 see 4.2.1. Denial-of-Service Countermeasures */
1886 err = dtls_send_handshake_msg_hash(ctx,
1887 state == DTLS_STATE_CONNECTED ? peer : NULL,
1889 DTLS_HT_HELLO_VERIFY_REQUEST,
1892 dtls_warn("cannot send HelloVerify request\n");
1894 return err; /* HelloVerify is sent, now we cannot do anything but wait */
1899 #if defined(DTLS_ECC) || defined(DTLS_X509)
1901 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1902 unsigned char **result_r,
1903 unsigned char **result_s)
1906 uint8 *data_orig = data;
1908 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
1909 dtls_alert("only sha256 is supported in certificate verify\n");
1910 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1912 data += sizeof(uint8);
1913 data_length -= sizeof(uint8);
1915 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
1916 dtls_alert("only ecdsa signature is supported in client verify\n");
1917 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1919 data += sizeof(uint8);
1920 data_length -= sizeof(uint8);
1922 if (data_length < dtls_uint16_to_int(data)) {
1923 dtls_alert("signature length wrong\n");
1924 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1926 data += sizeof(uint16);
1927 data_length -= sizeof(uint16);
1929 if (dtls_uint8_to_int(data) != 0x30) {
1930 dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1931 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1933 data += sizeof(uint8);
1934 data_length -= sizeof(uint8);
1936 if (data_length < dtls_uint8_to_int(data)) {
1937 dtls_alert("signature length wrong\n");
1938 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1940 data += sizeof(uint8);
1941 data_length -= sizeof(uint8);
1943 if (dtls_uint8_to_int(data) != 0x02) {
1944 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1945 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1947 data += sizeof(uint8);
1948 data_length -= sizeof(uint8);
1950 i = dtls_uint8_to_int(data);
1951 data += sizeof(uint8);
1952 data_length -= sizeof(uint8);
1954 /* Sometimes these values have a leeding 0 byte */
1955 *result_r = data + i - DTLS_EC_KEY_SIZE;
1960 if (dtls_uint8_to_int(data) != 0x02) {
1961 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1962 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1964 data += sizeof(uint8);
1965 data_length -= sizeof(uint8);
1967 i = dtls_uint8_to_int(data);
1968 data += sizeof(uint8);
1969 data_length -= sizeof(uint8);
1971 /* Sometimes these values have a leeding 0 byte */
1972 *result_s = data + i - DTLS_EC_KEY_SIZE;
1977 return data - data_orig;
1981 check_client_certificate_verify(dtls_context_t *ctx,
1983 uint8 *data, size_t data_length)
1985 dtls_handshake_parameters_t *config = peer->handshake_params;
1987 unsigned char *result_r;
1988 unsigned char *result_s;
1989 dtls_hash_ctx hs_hash;
1990 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1992 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
1994 data += DTLS_HS_LENGTH;
1996 if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1997 dtls_alert("the packet length does not match the expected\n");
1998 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2001 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
2008 copy_hs_hash(peer, &hs_hash);
2010 dtls_hash_finalize(sha256hash, &hs_hash);
2012 ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
2013 sizeof(config->keyx.ecc.other_pub_x),
2014 sha256hash, sizeof(sha256hash),
2015 result_r, result_s);
2018 dtls_alert("wrong signature err: %i\n", ret);
2019 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2023 #endif /* DTLS_ECC */
2026 dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
2028 /* Ensure that the largest message to create fits in our source
2029 * buffer. (The size of the destination buffer is checked by the
2030 * encoding function, so we do not need to guess.) */
2031 uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
2034 uint8 extension_size;
2035 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2038 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
2040 extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
2042 /* Handshake header */
2046 dtls_int_to_uint16(p, DTLS_VERSION);
2047 p += sizeof(uint16);
2049 /* Set server random: First 4 bytes are the server's Unix timestamp,
2050 * followed by 28 bytes of generate random data. */
2052 dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
2053 dtls_prng(handshake->tmp.random.server + 4, 28);
2055 memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
2056 p += DTLS_RANDOM_LENGTH;
2058 *p++ = 0; /* no session id */
2060 if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
2061 /* selected cipher suite */
2062 dtls_int_to_uint16(p, handshake->cipher);
2063 p += sizeof(uint16);
2065 /* selected compression method */
2066 *p++ = compression_methods[handshake->compression];
2069 if (extension_size) {
2070 /* length of the extensions */
2071 dtls_int_to_uint16(p, extension_size - 2);
2072 p += sizeof(uint16);
2076 /* client certificate type extension */
2077 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2078 p += sizeof(uint16);
2080 /* length of this extension type */
2081 dtls_int_to_uint16(p, 1);
2082 p += sizeof(uint16);
2084 if (CALL(ctx, is_x509_active) == 0)
2085 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2087 #endif /* DTLS_X509 */
2088 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2092 /* client certificate type extension */
2093 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2094 p += sizeof(uint16);
2096 /* length of this extension type */
2097 dtls_int_to_uint16(p, 1);
2098 p += sizeof(uint16);
2101 if (CALL(ctx, is_x509_active) == 0)
2102 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2104 #endif /* DTLS_X509 */
2105 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2109 /* ec_point_formats */
2110 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2111 p += sizeof(uint16);
2113 /* length of this extension type */
2114 dtls_int_to_uint16(p, 2);
2115 p += sizeof(uint16);
2117 /* number of supported formats */
2118 dtls_int_to_uint8(p, 1);
2121 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2125 assert(p - buf <= sizeof(buf));
2127 /* TODO use the same record sequence number as in the ClientHello,
2128 see 4.2.1. Denial-of-Service Countermeasures */
2129 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
2134 #define DTLS_EC_SUBJECTPUBLICKEY_SIZE (2 * DTLS_EC_KEY_SIZE + sizeof(cert_asn1_header))
2137 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
2138 const dtls_ecc_key_t *key)
2140 uint8 buf[DTLS_CE_LENGTH];
2145 * Start message construction at beginning of buffer. */
2148 /* length of this certificate */
2149 dtls_int_to_uint24(p, DTLS_EC_SUBJECTPUBLICKEY_SIZE);
2150 p += sizeof(uint24);
2152 memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
2153 p += sizeof(cert_asn1_header);
2155 memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
2156 p += DTLS_EC_KEY_SIZE;
2158 memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
2159 p += DTLS_EC_KEY_SIZE;
2161 assert(p - buf <= sizeof(buf));
2163 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2166 #endif /* DTLS_ECC */
2170 dtls_send_certificate_x509(dtls_context_t *ctx, dtls_peer_t *peer)
2172 uint8 buf[DTLS_MAX_CERT_SIZE];
2175 unsigned char *cert;
2178 dtls_info("\n dtls_send_certificate_ecdsa\n");
2179 ret = CALL(ctx, get_x509_cert, &peer->session,
2180 (const unsigned char **)&cert, &cert_size);
2183 dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2189 * Start message construction at beginning of buffer. */
2192 dtls_int_to_uint24(p, cert_size); /* certificates length */
2193 p += sizeof(uint24);
2195 memcpy(p, cert, cert_size);
2198 assert(p - buf <= sizeof(buf));
2200 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2203 #endif /* DTLS_X509 */
2205 #if defined(DTLS_X509) || defined(DTLS_ECC)
2207 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
2212 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
2213 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
2214 /* store the pointer to the r component of the signature and make space */
2215 len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
2216 len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
2222 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2226 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2229 /* length of signature */
2230 dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
2231 p += sizeof(uint16);
2233 /* ASN.1 SEQUENCE */
2234 dtls_int_to_uint8(p, 0x30);
2237 dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
2240 /* ASN.1 Integer r */
2241 dtls_int_to_uint8(p, 0x02);
2244 dtls_int_to_uint8(p, len_r);
2247 /* the pint r was added here */
2250 /* ASN.1 Integer s */
2251 dtls_int_to_uint8(p, 0x02);
2254 dtls_int_to_uint8(p, len_s);
2257 /* the pint s was added here */
2264 dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2265 const dtls_ecc_key_t *key)
2267 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2268 * 33 bytes long add space for that */
2269 uint8 buf[DTLS_SKEXEC_LENGTH + 2];
2272 uint8 *ephemeral_pub_x;
2273 uint8 *ephemeral_pub_y;
2274 uint32_t point_r[9];
2275 uint32_t point_s[9];
2277 dtls_handshake_parameters_t *config = peer->handshake_params;
2279 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2280 /* ServerKeyExchange
2282 * Start message construction at beginning of buffer. */
2286 /* ECCurveType curve_type: named_curve */
2287 dtls_int_to_uint8(p, 3);
2290 /* NamedCurve namedcurve: secp256r1 */
2291 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2292 p += sizeof(uint16);
2294 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2297 /* This should be an uncompressed point, but I do not have access to the spec. */
2298 dtls_int_to_uint8(p, 4);
2301 /* store the pointer to the x component of the pub key and make space */
2302 ephemeral_pub_x = p;
2303 p += DTLS_EC_KEY_SIZE;
2305 /* store the pointer to the y component of the pub key and make space */
2306 ephemeral_pub_y = p;
2307 p += DTLS_EC_KEY_SIZE;
2309 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2310 ephemeral_pub_x, ephemeral_pub_y,
2313 /* sign the ephemeral and its paramaters */
2314 dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
2315 config->tmp.random.client, DTLS_RANDOM_LENGTH,
2316 config->tmp.random.server, DTLS_RANDOM_LENGTH,
2317 key_params, p - key_params,
2320 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2323 assert(p - buf <= sizeof(buf));
2325 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2328 #endif /* defined(DTLS_X509) || defined(DTLS_ECC) */
2330 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2331 static int dtls_send_server_key_exchange_ecdhe_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2332 const unsigned char *psk_hint, size_t psk_hint_len)
2334 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2335 * 33 bytes long add space for that */
2336 uint8 buf[DTLS_SKEXEC_LENGTH + DTLS_SKEXECPSK_LENGTH_MAX + 2];
2338 uint8 *ephemeral_pub_x;
2339 uint8 *ephemeral_pub_y;
2340 dtls_handshake_parameters_t *config = peer->handshake_params;
2342 /* ServerKeyExchange
2343 * Please see Session 2, RFC 5489.
2346 select (KeyExchangeAlgorithm) {
2347 //other cases for rsa, diffie_hellman, etc.
2348 case ec_diffie_hellman_psk: // NEW
2349 opaque psk_identity_hint<0..2^16-1>;
2350 ServerECDHParams params;
2352 } ServerKeyExchange; */
2355 assert(psk_hint_len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2356 if (psk_hint_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2357 // should never happen
2358 dtls_warn("psk identity hint is too long\n");
2359 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2362 // psk_identity_hint
2363 dtls_int_to_uint16(p, psk_hint_len);
2364 p += sizeof(uint16);
2366 memcpy(p, psk_hint, psk_hint_len);
2369 /* ServerECDHParams. */
2370 /* ECCurveType curve_type: named_curve */
2371 dtls_int_to_uint8(p, TLS_EC_CURVE_TYPE_NAMED_CURVE);
2374 /* NamedCurve namedcurve: secp256r1 */
2375 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2376 p += sizeof(uint16);
2378 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2381 /* This should be an uncompressed point, but I do not have access to the spec. */
2382 dtls_int_to_uint8(p, 4);
2385 /* store the pointer to the x component of the pub key and make space */
2386 ephemeral_pub_x = p;
2387 p += DTLS_EC_KEY_SIZE;
2389 /* store the pointer to the y component of the pub key and make space */
2390 ephemeral_pub_y = p;
2391 p += DTLS_EC_KEY_SIZE;
2393 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2394 ephemeral_pub_x, ephemeral_pub_y,
2397 assert(p - buf <= sizeof(buf));
2399 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2402 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2406 dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2407 const unsigned char *psk_hint, size_t len)
2409 uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
2414 assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2415 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2416 /* should never happen */
2417 dtls_warn("psk identity hint is too long\n");
2418 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2421 dtls_int_to_uint16(p, len);
2422 p += sizeof(uint16);
2424 memcpy(p, psk_hint, len);
2427 assert(p - buf <= sizeof(buf));
2429 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2432 #endif /* DTLS_PSK */
2434 #if defined(DTLS_ECC) || defined(DTLS_X509)
2436 dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
2443 * Start message construction at beginning of buffer. */
2446 /* certificate_types */
2447 dtls_int_to_uint8(p, 1);
2451 dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
2454 /* supported_signature_algorithms */
2455 dtls_int_to_uint16(p, 2);
2456 p += sizeof(uint16);
2459 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2463 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2466 /* certificate_authoritiess */
2467 dtls_int_to_uint16(p, 0);
2468 p += sizeof(uint16);
2470 assert(p - buf <= sizeof(buf));
2472 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
2475 #endif /* DTLS_ECC */
2478 dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
2483 * Start message construction at beginning of buffer. */
2485 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
2490 dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
2497 res = dtls_send_server_hello(ctx, peer);
2500 dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2504 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2505 ecdh_anon = is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2506 ecdhe_psk = is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2508 #if defined(DTLS_ECC) || defined(DTLS_X509)
2510 res = dtls_send_server_key_exchange_ecdh(ctx, peer, NULL);
2513 dtls_debug("dtls_server_hello(with ECDH): cannot prepare Server Key Exchange record\n");
2518 const dtls_ecc_key_t *ecdsa_key;
2521 if (CALL(ctx, is_x509_active) == 0)
2522 res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
2524 #endif /* DTLS_X509 */
2525 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2528 dtls_debug("no ecdsa key to send\n");
2533 if (CALL(ctx, is_x509_active) == 0)
2534 res = dtls_send_certificate_x509(ctx, peer);
2536 #endif /* DTLS_X509 */
2537 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2540 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2544 res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2547 dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2551 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
2552 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx)))) {
2553 res = dtls_send_server_certificate_request(ctx, peer);
2555 dtls_debug("dtls_server_hello(with ECDSA): cannot prepare certificate Request record\n");
2560 #endif /* DTLS_ECC */
2561 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2562 else if(ecdhe_psk) {
2563 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2566 /* The identity hint is optional, therefore we ignore the result
2567 * and check psk only. */
2568 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2569 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2572 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2577 res = dtls_send_server_key_exchange_ecdhe_psk(ctx, peer, psk_hint, (size_t)psk_len);
2580 dtls_debug("dtls_server_hello(with ECDHE): cannot prepare Server Key Exchange record\n");
2585 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2587 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2588 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2591 /* The identity hint is optional, therefore we ignore the result
2592 * and check psk only. */
2593 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2594 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2597 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2602 res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2605 dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2610 #endif /* DTLS_PSK */
2612 res = dtls_send_server_hello_done(ctx, peer);
2615 dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2622 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
2625 return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2630 dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
2632 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2633 uint8 buf[DTLS_CKXEC_LENGTH + 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2635 uint8 buf[DTLS_CKXEC_LENGTH];
2636 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2637 uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2639 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2643 switch (handshake->cipher) {
2645 case TLS_PSK_WITH_AES_128_CCM_8: {
2648 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2653 dtls_crit("no psk identity set in kx\n");
2657 if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2658 dtls_warn("the psk identity is too long\n");
2659 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2662 dtls_int_to_uint16(p, len);
2663 p += sizeof(uint16);
2665 memcpy(p, client_id, len);
2670 #endif /* DTLS_PSK */
2671 #if defined(DTLS_ECC) || defined(DTLS_X509)
2672 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2673 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
2674 uint8 *ephemeral_pub_x;
2675 uint8 *ephemeral_pub_y;
2677 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2680 /* This should be an uncompressed point, but I do not have access to the spec. */
2681 dtls_int_to_uint8(p, 4);
2684 ephemeral_pub_x = p;
2685 p += DTLS_EC_KEY_SIZE;
2686 ephemeral_pub_y = p;
2687 p += DTLS_EC_KEY_SIZE;
2689 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2690 ephemeral_pub_x, ephemeral_pub_y,
2695 #endif /* DTLS_ECC */
2696 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2697 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
2699 uint8 *ephemeral_pub_x;
2700 uint8 *ephemeral_pub_y;
2702 /* Please see Session 2, RFC 5489.
2704 select (KeyExchangeAlgorithm) {
2705 // other cases for rsa, diffie_hellman, etc.
2706 case ec_diffie_hellman_psk:
2707 opaque psk_identity<0..2^16-1>;
2708 ClientECDiffieHellmanPublic public;
2710 } ClientKeyExchange;
2713 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2718 dtls_crit("no psk identity set in kx\n");
2722 if (psk_len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2723 dtls_warn("the psk identity is too long\n");
2724 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2727 dtls_int_to_uint16(p, psk_len);
2728 p += sizeof(uint16);
2730 memcpy(p, client_id, psk_len);
2733 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2736 dtls_int_to_uint8(p, 4);
2739 ephemeral_pub_x = p;
2740 p += DTLS_EC_KEY_SIZE;
2741 ephemeral_pub_y = p;
2742 p += DTLS_EC_KEY_SIZE;
2744 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2745 ephemeral_pub_x, ephemeral_pub_y,
2749 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2751 dtls_crit("cipher not supported\n");
2752 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2755 assert(p - buf <= sizeof(buf));
2757 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
2761 #if defined(DTLS_ECC) || defined(DTLS_X509)
2763 dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2764 const dtls_ecc_key_t *key)
2766 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2767 * 33 bytes long add space for that */
2768 uint8 buf[DTLS_CV_LENGTH + 2];
2770 uint32_t point_r[9];
2771 uint32_t point_s[9];
2772 dtls_hash_ctx hs_hash;
2773 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2775 /* ServerKeyExchange
2777 * Start message construction at beginning of buffer. */
2780 copy_hs_hash(peer, &hs_hash);
2782 dtls_hash_finalize(sha256hash, &hs_hash);
2784 /* sign the ephemeral and its paramaters */
2785 dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
2786 sha256hash, sizeof(sha256hash),
2789 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2791 assert(p - buf <= sizeof(buf));
2793 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
2796 #endif /* DTLS_ECC */
2799 dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
2800 const unsigned char *label, size_t labellen)
2803 uint8 hash[DTLS_HMAC_MAX];
2804 uint8 buf[DTLS_FIN_LENGTH];
2805 dtls_hash_ctx hs_hash;
2808 copy_hs_hash(peer, &hs_hash);
2810 length = dtls_hash_finalize(hash, &hs_hash);
2812 dtls_prf(peer->handshake_params->tmp.master_secret,
2813 DTLS_MASTER_SECRET_LENGTH,
2815 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2817 p, DTLS_FIN_LENGTH);
2819 dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2821 p += DTLS_FIN_LENGTH;
2823 assert(p - buf <= sizeof(buf));
2825 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2830 dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
2831 uint8 cookie[], size_t cookie_length) {
2832 uint8 buf[DTLS_CH_LENGTH_MAX];
2834 uint8_t cipher_size = 0;
2835 uint8_t extension_size = 0;
2841 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2844 switch(ctx->selected_cipher)
2846 case TLS_PSK_WITH_AES_128_CCM_8:
2847 psk = is_psk_supported(ctx);
2849 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2850 ecdsa = is_ecdsa_supported(ctx, 1);
2851 x509 = is_x509_supported(ctx, 1);
2853 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
2854 ecdh_anon = is_ecdh_anon_supported(ctx);
2856 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
2857 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2860 psk = is_psk_supported(ctx);
2861 ecdsa = is_ecdsa_supported(ctx, 1);
2862 ecdh_anon = is_ecdh_anon_supported(ctx);
2863 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2864 x509 = is_x509_supported(ctx, 1);
2868 cipher_size = 2 + ((ecdsa || x509) ? 2 : 0) + (psk ? 2 : 0) + (ecdh_anon ? 2 : 0) + (ecdhe_psk ? 2 : 0);
2870 /* Is extension needed? */
2871 extension_size = (ecdsa || x509 || ecdhe_psk || ecdh_anon) ? 2 : 0;
2872 /* Supported EC and Supported Point Formats */
2873 extension_size += (ecdsa || x509 || ecdhe_psk | ecdh_anon) ? ( 8 + 6) : 0;
2874 /* Supported Client and Server Cert Types */
2875 extension_size += (ecdsa || x509) ? ( 6 + 6) : 0;
2877 if (cipher_size == 0) {
2878 dtls_crit("no cipher callbacks implemented\n");
2881 dtls_int_to_uint16(p, DTLS_VERSION);
2882 p += sizeof(uint16);
2884 if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2885 dtls_warn("the cookie is too long\n");
2886 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2889 if (cookie_length == 0) {
2890 /* Set client random: First 4 bytes are the client's Unix timestamp,
2891 * followed by 28 bytes of generate random data. */
2893 dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2894 dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2895 DTLS_RANDOM_LENGTH - sizeof(uint32));
2897 /* we must use the same Client Random as for the previous request */
2898 memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2899 p += DTLS_RANDOM_LENGTH;
2901 /* session id (length 0) */
2902 dtls_int_to_uint8(p, 0);
2906 dtls_int_to_uint8(p, cookie_length);
2908 if (cookie_length != 0) {
2909 memcpy(p, cookie, cookie_length);
2913 /* add known cipher(s) */
2914 dtls_int_to_uint16(p, cipher_size - 2);
2915 p += sizeof(uint16);
2918 dtls_int_to_uint16(p, TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256);
2919 p += sizeof(uint16);
2922 dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
2923 p += sizeof(uint16);
2925 if (ecdsa || x509) {
2926 dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
2927 p += sizeof(uint16);
2930 dtls_int_to_uint16(p, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
2931 p += sizeof(uint16);
2934 /* compression method */
2935 dtls_int_to_uint8(p, 1);
2938 dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
2941 if (extension_size) {
2942 /* length of the extensions */
2943 dtls_int_to_uint16(p, extension_size - 2);
2944 p += sizeof(uint16);
2947 if (ecdsa || x509) {
2948 /* client certificate type extension */
2949 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2950 p += sizeof(uint16);
2952 /* length of this extension type */
2953 dtls_int_to_uint16(p, 2);
2954 p += sizeof(uint16);
2956 /* length of the list */
2957 dtls_int_to_uint8(p, 1);
2961 if (CALL(ctx, is_x509_active) == 0)
2962 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2964 #endif /* DTLS_X509 */
2965 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2969 /* server certificate type extension */
2970 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2971 p += sizeof(uint16);
2973 /* length of this extension type */
2974 dtls_int_to_uint16(p, 2);
2975 p += sizeof(uint16);
2977 /* length of the list */
2978 dtls_int_to_uint8(p, 1);
2982 if (CALL(ctx, is_x509_active) == 0)
2983 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2985 #endif /* DTLS_X509 */
2986 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2991 if (ecdsa || x509 || ecdhe_psk || ecdh_anon ) {
2992 /* elliptic_curves */
2993 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
2994 p += sizeof(uint16);
2996 /* length of this extension type */
2997 dtls_int_to_uint16(p, 4);
2998 p += sizeof(uint16);
3000 /* length of the list */
3001 dtls_int_to_uint16(p, 2);
3002 p += sizeof(uint16);
3004 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
3005 p += sizeof(uint16);
3007 /* ec_point_formats */
3008 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
3009 p += sizeof(uint16);
3011 /* length of this extension type */
3012 dtls_int_to_uint16(p, 2);
3013 p += sizeof(uint16);
3015 /* number of supported formats */
3016 dtls_int_to_uint8(p, 1);
3019 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
3023 assert(p - buf <= sizeof(buf));
3025 if (cookie_length != 0)
3026 clear_hs_hash(peer);
3028 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3029 DTLS_HT_CLIENT_HELLO,
3030 buf, p - buf, cookie_length != 0);
3034 check_server_hello(dtls_context_t *ctx,
3036 uint8 *data, size_t data_length)
3038 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3040 /* This function is called when we expect a ServerHello (i.e. we
3041 * have sent a ClientHello). We might instead receive a HelloVerify
3042 * request containing a cookie. If so, we must repeat the
3043 * ClientHello with the given Cookie.
3045 if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
3046 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3048 update_hs_hash(peer, data, data_length);
3050 /* FIXME: check data_length before accessing fields */
3052 /* Get the server's random data and store selected cipher suite
3053 * and compression method (like dtls_update_parameters().
3054 * Then calculate master secret and wait for ServerHelloDone. When received,
3055 * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
3057 /* check server version */
3058 data += DTLS_HS_LENGTH;
3059 data_length -= DTLS_HS_LENGTH;
3061 if (dtls_uint16_to_int(data) != DTLS_VERSION) {
3062 dtls_alert("unknown DTLS version\n");
3063 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
3066 data += sizeof(uint16); /* skip version field */
3067 data_length -= sizeof(uint16);
3069 /* store server random data */
3070 memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
3071 /* skip server random */
3072 data += DTLS_RANDOM_LENGTH;
3073 data_length -= DTLS_RANDOM_LENGTH;
3075 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
3077 /* Check cipher suite. As we offer all we have, it is sufficient
3078 * to check if the cipher suite selected by the server is in our
3079 * list of known cipher suites. Subsets are not supported. */
3080 handshake->cipher = dtls_uint16_to_int(data);
3081 if (!known_cipher(ctx, handshake->cipher, 1)) {
3082 dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
3084 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3086 data += sizeof(uint16);
3087 data_length -= sizeof(uint16);
3089 /* Check if NULL compression was selected. We do not know any other. */
3090 if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
3091 dtls_alert("unsupported compression method 0x%02x\n", data[0]);
3092 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3094 data += sizeof(uint8);
3095 data_length -= sizeof(uint8);
3097 return dtls_check_tls_extension(peer, data, data_length, 0);
3100 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3104 check_server_hello_verify_request(dtls_context_t *ctx,
3106 uint8 *data, size_t data_length)
3108 dtls_hello_verify_t *hv;
3111 if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
3112 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3114 hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
3116 res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
3119 dtls_warn("cannot send ClientHello\n");
3127 check_peer_certificate(dtls_context_t *ctx,
3129 uint8 *data, size_t data_length)
3132 dtls_handshake_parameters_t *config = peer->handshake_params;
3134 update_hs_hash(peer, data, data_length);
3136 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3138 data += DTLS_HS_LENGTH;
3140 if (dtls_uint24_to_int(data) != DTLS_EC_SUBJECTPUBLICKEY_SIZE) {
3141 dtls_alert("expect length of %d bytes for certificate\n",
3142 DTLS_EC_SUBJECTPUBLICKEY_SIZE);
3143 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3145 data += sizeof(uint24);
3147 if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
3148 dtls_alert("got an unexpected Subject public key format\n");
3149 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3151 data += sizeof(cert_asn1_header);
3153 memcpy(config->keyx.ecc.other_pub_x, data,
3154 sizeof(config->keyx.ecc.other_pub_x));
3155 data += sizeof(config->keyx.ecc.other_pub_x);
3157 memcpy(config->keyx.ecc.other_pub_y, data,
3158 sizeof(config->keyx.ecc.other_pub_y));
3159 data += sizeof(config->keyx.ecc.other_pub_y);
3161 err = CALL(ctx, verify_ecdsa_key, &peer->session,
3162 config->keyx.ecc.other_pub_x,
3163 config->keyx.ecc.other_pub_y,
3164 sizeof(config->keyx.ecc.other_pub_x));
3166 dtls_warn("The certificate was not accepted\n");
3172 #endif /* DTLS_ECC */
3176 check_peer_certificate_x509(dtls_context_t *ctx,
3178 uint8 *data, size_t data_length)
3181 dtls_handshake_parameters_t *config = peer->handshake_params;
3184 dtls_info("\n check_peer_certificate_x509\n");
3185 update_hs_hash(peer, data, data_length);
3187 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3189 data += DTLS_HS_LENGTH;
3191 cert_length = dtls_uint24_to_int(data);
3192 data += sizeof(uint24);
3194 ret = CALL(ctx, verify_x509_cert, &peer->session, data, cert_length,
3195 config->keyx.ecc.other_pub_x, sizeof(config->keyx.ecc.other_pub_x),
3196 config->keyx.ecc.other_pub_y, sizeof(config->keyx.ecc.other_pub_y));
3198 dtls_warn("The certificate was not accepted\n");
3204 #endif /* DTLS_X509 */
3206 #if defined(DTLS_X509) || defined(DTLS_ECC)
3208 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
3210 uint8 *data, size_t data_length)
3212 dtls_handshake_parameters_t *config = peer->handshake_params;
3214 unsigned char *result_r;
3215 unsigned char *result_s;
3216 unsigned char *key_params;
3218 update_hs_hash(peer, data, data_length);
3220 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3222 data += DTLS_HS_LENGTH;
3224 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
3225 dtls_alert("the packet length does not match the expected\n");
3226 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3230 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3231 dtls_alert("Only named curves supported\n");
3232 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3234 data += sizeof(uint8);
3235 data_length -= sizeof(uint8);
3237 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3238 dtls_alert("secp256r1 supported\n");
3239 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3241 data += sizeof(uint16);
3242 data_length -= sizeof(uint16);
3244 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3245 dtls_alert("expected 65 bytes long public point\n");
3246 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3248 data += sizeof(uint8);
3249 data_length -= sizeof(uint8);
3251 if (dtls_uint8_to_int(data) != 4) {
3252 dtls_alert("expected uncompressed public point\n");
3253 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3255 data += sizeof(uint8);
3256 data_length -= sizeof(uint8);
3258 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3259 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3260 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3262 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3263 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3264 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3266 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
3273 ret = dtls_ecdsa_verify_sig(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
3274 sizeof(config->keyx.ecc.other_pub_x),
3275 config->tmp.random.client, DTLS_RANDOM_LENGTH,
3276 config->tmp.random.server, DTLS_RANDOM_LENGTH,
3278 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
3279 result_r, result_s);
3282 dtls_alert("wrong signature\n");
3283 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3289 check_server_key_exchange_ecdh(dtls_context_t *ctx,
3291 uint8 *data, size_t data_length)
3293 dtls_handshake_parameters_t *config = peer->handshake_params;
3295 update_hs_hash(peer, data, data_length);
3297 assert(is_tls_ecdh_anon_with_aes_128_cbc_sha_256(config->cipher));
3299 data += DTLS_HS_LENGTH;
3301 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3302 dtls_alert("the packet length does not match the expected\n");
3303 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3306 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3307 dtls_alert("Only named curves supported\n");
3308 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3310 data += sizeof(uint8);
3311 data_length -= sizeof(uint8);
3313 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3314 dtls_alert("secp256r1 supported\n");
3315 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3317 data += sizeof(uint16);
3318 data_length -= sizeof(uint16);
3320 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3321 dtls_alert("expected 65 bytes long public point\n");
3322 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3324 data += sizeof(uint8);
3325 data_length -= sizeof(uint8);
3327 if (dtls_uint8_to_int(data) != 4) {
3328 dtls_alert("expected uncompressed public point\n");
3329 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3331 data += sizeof(uint8);
3332 data_length -= sizeof(uint8);
3334 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3335 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3336 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3338 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3339 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3340 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3344 #endif /* DTLS_ECC */
3345 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3346 check_server_key_exchange_ecdhe_psk(dtls_context_t *ctx,
3348 uint8 *data, size_t data_length)
3350 dtls_handshake_parameters_t *config = peer->handshake_params;
3351 uint16_t psk_len = 0;
3353 /* ServerKeyExchange
3354 * Please see Session 2, RFC 5489.
3357 select (KeyExchangeAlgorithm) {
3358 //other cases for rsa, diffie_hellman, etc.
3359 case ec_diffie_hellman_psk: // NEW
3360 opaque psk_identity_hint<0..2^16-1>;
3361 ServerECDHParams params;
3363 } ServerKeyExchange; */
3365 update_hs_hash(peer, data, data_length);
3367 assert(is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(config->cipher));
3369 data += DTLS_HS_LENGTH;
3371 psk_len = dtls_uint16_to_int(data);
3372 data += sizeof(uint16);
3374 if (psk_len != data_length - DTLS_HS_LENGTH - DTLS_SKEXEC_ECDH_ANON_LENGTH - sizeof(uint16)) {
3375 dtls_warn("the length of the server identity hint is worng\n");
3376 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3379 if (psk_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3380 dtls_warn("please use a smaller server identity hint\n");
3381 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3384 // store the psk_identity_hint in config->keyx.psk for later use
3385 config->keyx.psk.id_length = psk_len;
3386 memcpy(config->keyx.psk.identity, data, psk_len);
3389 data_length -= psk_len;
3391 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3392 dtls_alert("the packet length does not match the expected\n");
3393 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3396 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3397 dtls_alert("Only named curves supported\n");
3398 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3400 data += sizeof(uint8);
3401 data_length -= sizeof(uint8);
3403 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3404 dtls_alert("secp256r1 supported\n");
3405 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3407 data += sizeof(uint16);
3408 data_length -= sizeof(uint16);
3410 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3411 dtls_alert("expected 65 bytes long public point\n");
3412 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3414 data += sizeof(uint8);
3415 data_length -= sizeof(uint8);
3417 if (dtls_uint8_to_int(data) != 4) {
3418 dtls_alert("expected uncompressed public point\n");
3419 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3421 data += sizeof(uint8);
3422 data_length -= sizeof(uint8);
3424 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3425 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3426 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3428 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3429 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3430 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3434 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
3438 check_server_key_exchange_psk(dtls_context_t *ctx,
3440 uint8 *data, size_t data_length)
3442 dtls_handshake_parameters_t *config = peer->handshake_params;
3445 update_hs_hash(peer, data, data_length);
3447 assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
3449 data += DTLS_HS_LENGTH;
3451 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
3452 dtls_alert("the packet length does not match the expected\n");
3453 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3456 len = dtls_uint16_to_int(data);
3457 data += sizeof(uint16);
3459 if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
3460 dtls_warn("the length of the server identity hint is worng\n");
3461 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3464 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3465 dtls_warn("please use a smaller server identity hint\n");
3466 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3469 /* store the psk_identity_hint in config->keyx.psk for later use */
3470 config->keyx.psk.id_length = len;
3471 memcpy(config->keyx.psk.identity, data, len);
3474 #endif /* DTLS_PSK */
3477 check_certificate_request(dtls_context_t *ctx,
3479 uint8 *data, size_t data_length)
3486 update_hs_hash(peer, data, data_length);
3488 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
3490 data += DTLS_HS_LENGTH;
3492 if (data_length < DTLS_HS_LENGTH + 5) {
3493 dtls_alert("the packet length does not match the expected\n");
3494 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3497 i = dtls_uint8_to_int(data);
3498 data += sizeof(uint8);
3499 if (i + 1 > data_length) {
3500 dtls_alert("the cerfificate types are too long\n");
3501 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3505 for (; i > 0 ; i -= sizeof(uint8)) {
3506 if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
3508 auth_alg = dtls_uint8_to_int(data);
3509 data += sizeof(uint8);
3512 if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
3513 dtls_alert("the request authentication algorithm is not supproted\n");
3514 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3517 i = dtls_uint16_to_int(data);
3518 data += sizeof(uint16);
3519 if (i + 1 > data_length) {
3520 dtls_alert("the signature and hash algorithm list is too long\n");
3521 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3526 for (; i > 0 ; i -= sizeof(uint16)) {
3527 int current_hash_alg;
3528 int current_sig_alg;
3530 current_hash_alg = dtls_uint8_to_int(data);
3531 data += sizeof(uint8);
3532 current_sig_alg = dtls_uint8_to_int(data);
3533 data += sizeof(uint8);
3535 if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 &&
3536 current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
3537 hash_alg = current_hash_alg;
3538 sig_alg = current_sig_alg;
3542 if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
3543 sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
3544 dtls_alert("no supported hash and signature algorithem\n");
3545 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3548 /* common names are ignored */
3550 peer->handshake_params->do_client_auth = 1;
3555 check_server_hellodone(dtls_context_t *ctx,
3557 uint8 *data, size_t data_length)
3561 const dtls_ecc_key_t *ecdsa_key;
3563 unsigned char *cert;
3565 #endif /* DTLS_X509 */
3566 #endif /* DTLS_ECC */
3568 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3570 /* calculate master key, send CCS */
3572 update_hs_hash(peer, data, data_length);
3574 #if defined(DTLS_ECC) || defined(DTLS_X509)
3575 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3577 if (CALL(ctx, is_x509_active) == 0)
3578 res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
3580 #endif /* DTLS_X509 */
3581 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
3583 dtls_crit("no ecdsa key to use\n");
3588 if (CALL(ctx, is_x509_active) == 0)
3589 res = dtls_send_certificate_x509(ctx, peer);
3591 #endif /* DTLS_X509 */
3592 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
3595 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3599 #endif /* DTLS_ECC */
3601 /* send ClientKeyExchange */
3602 res = dtls_send_client_key_exchange(ctx, peer);
3605 dtls_debug("cannot send KeyExchange message\n");
3610 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3611 res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
3614 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3618 #endif /* DTLS_ECC */
3620 res = calculate_key_block(ctx, handshake, peer,
3621 &peer->session, peer->role);
3626 res = dtls_send_ccs(ctx, peer);
3628 dtls_debug("cannot send CCS message\n");
3632 /* and switch cipher suite */
3633 dtls_security_params_switch(peer);
3635 /* Client Finished */
3636 return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
3640 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
3643 dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
3644 dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
3647 *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
3648 clen = length - sizeof(dtls_record_header_t);
3651 dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
3655 if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
3656 /* no cipher suite selected */
3658 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
3659 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
3661 unsigned char nonce[DTLS_CBC_IV_LENGTH];
3663 if (clen < (DTLS_CBC_IV_LENGTH + DTLS_HMAC_DIGEST_SIZE)) /* need at least IV and MAC */
3666 memcpy(nonce, *cleartext , DTLS_CBC_IV_LENGTH);
3667 clen -= DTLS_CBC_IV_LENGTH;
3668 *cleartext += DTLS_CBC_IV_LENGTH ;
3670 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3671 dtls_kb_remote_write_key(security, peer->role),
3672 dtls_kb_key_size(security, peer->role),
3673 dtls_kb_remote_mac_secret(security, peer->role),
3674 dtls_kb_mac_secret_size(security->cipher),
3678 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
3680 * length of additional_data for the AEAD cipher which consists of
3681 * seq_num(2+6) + type(1) + version(2) + length(2)
3683 #define A_DATA_LEN 13
3684 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
3685 unsigned char A_DATA[A_DATA_LEN];
3687 if (clen < 16) /* need at least IV and MAC */
3690 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
3691 memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
3692 dtls_kb_iv_size(security->cipher));
3694 /* read epoch and seq_num from message */
3695 memcpy(nonce + dtls_kb_iv_size(security->cipher), *cleartext, 8);
3699 dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
3700 dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
3701 dtls_kb_key_size(security, peer->role));
3702 dtls_debug_dump("ciphertext", *cleartext, clen);
3704 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
3706 * additional_data = seq_num + TLSCompressed.type +
3707 * TLSCompressed.version + TLSCompressed.length;
3709 memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
3710 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
3711 dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
3713 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3714 dtls_kb_remote_write_key(security, peer->role),
3715 dtls_kb_key_size(security, peer->role),
3716 dtls_kb_remote_mac_secret(security, peer->role),
3717 dtls_kb_mac_secret_size(security->cipher),
3723 dtls_warn("decryption failed\n");
3726 dtls_debug("decrypt_verify(): found %i bytes cleartext\n", clen);
3728 dtls_security_params_free_other(peer);
3729 dtls_debug_dump("cleartext", *cleartext, clen);
3736 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
3738 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3739 DTLS_HT_HELLO_REQUEST,
3744 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
3746 dtls_peer_t *peer = NULL;
3749 peer = dtls_get_peer(ctx, dst);
3754 if (peer->state != DTLS_STATE_CONNECTED)
3757 peer->handshake_params = dtls_handshake_new();
3758 if (!peer->handshake_params)
3761 peer->handshake_params->hs_state.mseq_r = 0;
3762 peer->handshake_params->hs_state.mseq_s = 0;
3764 if (peer->role == DTLS_CLIENT) {
3765 /* send ClientHello with empty Cookie */
3766 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3768 dtls_warn("cannot send ClientHello\n");
3770 peer->state = DTLS_STATE_CLIENTHELLO;
3772 } else if (peer->role == DTLS_SERVER) {
3773 return dtls_send_hello_request(ctx, peer);
3780 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3781 const dtls_peer_type role, const dtls_state_t state,
3782 uint8 *data, size_t data_length) {
3786 /* This will clear the retransmission buffer if we get an expected
3787 * handshake message. We have to make sure that no handshake message
3788 * should get expected when we still should retransmit something, when
3789 * we do everything accordingly to the DTLS 1.2 standard this should
3790 * not be a problem. */
3792 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3793 if (state == DTLS_STATE_WAIT_CHANGECIPHERSPEC && hs_header->msg_type == DTLS_HT_FINISHED) {
3796 dtls_clear_retransmission(ctx, peer);
3799 /* The following switch construct handles the given message with
3800 * respect to the current internal state for this peer. In case of
3801 * error, it is left with return 0. */
3803 dtls_debug("handle handshake packet of type: %s (%i)\n",
3804 dtls_handshake_type_to_name(data[0]), data[0]);
3807 /************************************************************************
3809 ************************************************************************/
3810 case DTLS_HT_HELLO_VERIFY_REQUEST:
3812 if (state != DTLS_STATE_CLIENTHELLO) {
3813 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3816 err = check_server_hello_verify_request(ctx, peer, data, data_length);
3818 dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3823 case DTLS_HT_SERVER_HELLO:
3825 if (state != DTLS_STATE_CLIENTHELLO) {
3826 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3829 err = check_server_hello(ctx, peer, data, data_length);
3831 dtls_warn("error in check_server_hello err: %i\n", err);
3834 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3835 peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE; //ecdsa
3836 else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher) ||
3837 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher))
3838 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE; //ecdh
3840 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE; //psk
3841 /* update_hs_hash(peer, data, data_length); */
3845 #if defined(DTLS_ECC) || defined(DTLS_X509)
3846 case DTLS_HT_CERTIFICATE:
3848 if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3849 (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3850 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3853 if (CALL(ctx, is_x509_active) == 0)
3854 err = check_peer_certificate_x509(ctx, peer, data, data_length);
3856 #endif /* DTLS_X509 */
3857 err = check_peer_certificate(ctx, peer, data, data_length);
3859 dtls_warn("error in check_peer_certificate err: %i\n", err);
3862 if (role == DTLS_CLIENT) {
3863 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3864 } else if (role == DTLS_SERVER){
3865 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3867 /* update_hs_hash(peer, data, data_length); */
3870 #endif /* DTLS_ECC */
3872 case DTLS_HT_SERVER_KEY_EXCHANGE:
3874 #if defined(DTLS_ECC) || defined(DTLS_X509)
3875 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3876 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3877 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3879 err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3882 if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3883 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3884 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3886 err = check_server_key_exchange_ecdh(ctx, peer, data, data_length);
3888 #endif /* DTLS_ECC */
3890 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3891 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3892 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3893 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3895 err = check_server_key_exchange_ecdhe_psk(ctx, peer, data, data_length);
3897 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
3900 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3901 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3902 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3904 err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3906 #endif /* DTLS_PSK */
3909 dtls_warn("error in check_server_key_exchange err: %i\n", err);
3912 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3913 /* update_hs_hash(peer, data, data_length); */
3917 case DTLS_HT_SERVER_HELLO_DONE:
3919 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3920 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3923 err = check_server_hellodone(ctx, peer, data, data_length);
3925 dtls_warn("error in check_server_hellodone err: %i\n", err);
3928 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3929 /* update_hs_hash(peer, data, data_length); */
3933 case DTLS_HT_CERTIFICATE_REQUEST:
3935 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3936 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3939 err = check_certificate_request(ctx, peer, data, data_length);
3941 dtls_warn("error in check_certificate_request err: %i\n", err);
3947 case DTLS_HT_FINISHED:
3948 /* expect a Finished message from server */
3950 if (state != DTLS_STATE_WAIT_FINISHED) {
3951 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3954 err = check_finished(ctx, peer, data, data_length);
3956 dtls_warn("error in check_finished err: %i\n", err);
3959 if (role == DTLS_SERVER) {
3960 /* send ServerFinished */
3961 update_hs_hash(peer, data, data_length);
3963 /* send change cipher spec message and switch to new configuration */
3964 err = dtls_send_ccs(ctx, peer);
3966 dtls_warn("cannot send CCS message\n");
3970 dtls_security_params_switch(peer);
3972 err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3974 dtls_warn("sending server Finished failed\n");
3978 dtls_handshake_free(peer->handshake_params);
3979 peer->handshake_params = NULL;
3980 dtls_debug("Handshake complete\n");
3982 peer->state = DTLS_STATE_CONNECTED;
3984 /* return here to not increase the message receive counter */
3987 /************************************************************************
3989 ************************************************************************/
3991 case DTLS_HT_CLIENT_KEY_EXCHANGE:
3992 /* handle ClientHello, update msg and msglen and goto next if not finished */
3994 if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3995 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3998 err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
4000 dtls_warn("error in check_client_keyexchange err: %i\n", err);
4003 update_hs_hash(peer, data, data_length);
4005 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
4006 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
4007 peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY; //ecdsa
4009 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC; //psk || ecdh_anon
4012 #if defined(DTLS_ECC) || defined(DTLS_X509)
4013 case DTLS_HT_CERTIFICATE_VERIFY:
4015 if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
4016 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4019 err = check_client_certificate_verify(ctx, peer, data, data_length);
4021 dtls_warn("error in check_client_certificate_verify err: %i\n", err);
4025 update_hs_hash(peer, data, data_length);
4026 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
4028 #endif /* DTLS_ECC */
4030 case DTLS_HT_CLIENT_HELLO:
4032 if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
4033 (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
4034 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4037 /* When no DTLS state exists for this peer, we only allow a
4038 Client Hello message with
4040 a) a valid cookie, or
4043 Anything else will be rejected. Fragementation is not allowed
4044 here as it would require peer state as well.
4046 err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
4048 dtls_warn("error in dtls_verify_peer err: %i\n", err);
4053 dtls_debug("server hello verify was sent\n");
4057 /* At this point, we have a good relationship with this peer. This
4058 * state is left for re-negotiation of key material. */
4059 /* As per RFC 6347 - section 4.2.8 if this is an attempt to
4060 * rehandshake, we can delete the existing key material
4061 * as the client has demonstrated reachibility by completing
4062 * the cookie exchange */
4063 if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
4064 dtls_debug("removing the peer\n");
4065 #ifndef WITH_CONTIKI
4066 HASH_DEL_PEER(ctx->peers, peer);
4067 #else /* WITH_CONTIKI */
4068 list_remove(ctx->peers, peer);
4069 #endif /* WITH_CONTIKI */
4071 dtls_free_peer(peer);
4075 dtls_debug("creating new peer\n");
4076 dtls_security_parameters_t *security;
4078 /* msg contains a Client Hello with a valid cookie, so we can
4079 * safely create the server state machine and continue with
4081 peer = dtls_new_peer(session);
4083 dtls_alert("cannot create peer\n");
4084 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4086 peer->role = DTLS_SERVER;
4088 /* Initialize record sequence number to 1 for new peers. The first
4089 * record with sequence number 0 is a stateless Hello Verify Request.
4091 security = dtls_security_params(peer);
4093 dtls_add_peer(ctx, peer);
4095 if (peer && !peer->handshake_params) {
4096 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4098 peer->handshake_params = dtls_handshake_new();
4099 if (!peer->handshake_params)
4100 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4102 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4103 peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
4104 peer->handshake_params->hs_state.mseq_s = 1;
4107 clear_hs_hash(peer);
4109 /* First negotiation step: check for PSK
4111 * Note that we already have checked that msg is a Handshake
4112 * message containing a ClientHello. dtls_get_cipher() therefore
4113 * does not check again.
4115 err = dtls_update_parameters(ctx, peer, data, data_length);
4117 dtls_warn("error updating security parameters\n");
4121 /* update finish MAC */
4122 update_hs_hash(peer, data, data_length);
4124 err = dtls_send_server_hello_msgs(ctx, peer);
4128 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
4129 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
4130 peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE; //ecdhe
4132 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE; //psk, ecdh_anon
4134 /* after sending the ServerHelloDone, we expect the
4135 * ClientKeyExchange (possibly containing the PSK id),
4136 * followed by a ChangeCipherSpec and an encrypted Finished.
4141 case DTLS_HT_HELLO_REQUEST:
4143 if (state != DTLS_STATE_CONNECTED) {
4144 /* we should just ignore such packets when in handshake */
4148 if (peer && !peer->handshake_params) {
4149 peer->handshake_params = dtls_handshake_new();
4150 if (!peer->handshake_params)
4151 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4153 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4154 peer->handshake_params->hs_state.mseq_r = 0;
4155 peer->handshake_params->hs_state.mseq_s = 0;
4158 /* send ClientHello with empty Cookie */
4159 err = dtls_send_client_hello(ctx, peer, NULL, 0);
4161 dtls_warn("cannot send ClientHello\n");
4164 peer->state = DTLS_STATE_CLIENTHELLO;
4168 dtls_crit("unhandled message %d\n", data[0]);
4169 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4172 if (peer && peer->handshake_params && err >= 0) {
4173 peer->handshake_params->hs_state.mseq_r++;
4180 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
4181 const dtls_peer_type role, const dtls_state_t state,
4182 uint8 *data, size_t data_length)
4184 dtls_handshake_header_t *hs_header;
4187 if (data_length < DTLS_HS_LENGTH) {
4188 dtls_warn("handshake message too short\n");
4189 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4191 hs_header = DTLS_HANDSHAKE_HEADER(data);
4193 dtls_debug("received handshake packet of type: %s (%i)\n",
4194 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4196 if (!peer || !peer->handshake_params) {
4197 /* This is the initial ClientHello */
4198 if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
4199 dtls_warn("If there is no peer only ClientHello is allowed\n");
4200 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
4203 /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
4204 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
4205 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
4206 return handle_handshake_msg(ctx, peer, session, role, state, data,
4209 dtls_warn("ignore unexpected handshake message\n");
4213 /* This is a ClientHello send when doing retransmission */
4214 if (peer && hs_header->msg_type == DTLS_HT_CLIENT_HELLO &&
4215 dtls_uint16_to_int(hs_header->message_seq) == 0) {
4216 res = dtls_verify_peer(ctx, peer, session, state, data, data_length);
4218 dtls_warn("error in dtls_verify_peer err: %i\n", res);
4221 dtls_debug("server hello verify was sent\n");
4226 if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
4227 dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
4228 peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
4230 } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
4231 /* A packet in between is missing, buffer this packet. */
4234 /* TODO: only add packet that are not too new. */
4235 if (data_length > DTLS_MAX_BUF) {
4236 dtls_warn("the packet is too big to buffer for reoder\n");
4240 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4242 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4243 if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
4244 dtls_warn("a packet with this sequence number is already stored\n");
4247 node = netq_next(node);
4250 n = netq_node_new(data_length);
4252 dtls_warn("no space in reoder buffer\n");
4257 n->length = data_length;
4258 memcpy(n->data, data, data_length);
4260 if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
4261 dtls_warn("cannot add packet to reoder buffer\n");
4264 dtls_info("Added packet for reordering\n");
4266 } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4267 /* Found the expected packet, use this and all the buffered packet */
4270 res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
4274 /* We do not know in which order the packet are in the list just search the list for every packet. */
4275 while (next && peer->handshake_params) {
4277 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4279 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4281 if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4282 netq_remove(peer->handshake_params->reorder_queue, node);
4284 res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
4291 node = netq_next(node);
4302 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
4303 uint8 *record_header, uint8 *data, size_t data_length)
4306 dtls_handshake_parameters_t *handshake;
4308 /* A CCS message is handled after a KeyExchange message was
4309 * received from the client. When security parameters have been
4310 * updated successfully and a ChangeCipherSpec message was sent
4311 * by ourself, the security context is switched and the record
4312 * sequence number is reset. */
4314 if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
4315 dtls_warn("expected ChangeCipherSpec during handshake\n");
4319 if (data_length < 1 || data[0] != 1)
4320 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4322 handshake = peer->handshake_params;
4323 /* Just change the cipher when we are on the same epoch */
4324 if (peer->role == DTLS_SERVER) {
4325 err = calculate_key_block(ctx, handshake, peer,
4326 &peer->session, peer->role);
4332 peer->state = DTLS_STATE_WAIT_FINISHED;
4338 * Handles incoming Alert messages. This function returns \c 1 if the
4339 * connection should be closed and the peer is to be invalidated.
4342 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
4343 uint8 *record_header, uint8 *data, size_t data_length) {
4344 int free_peer = 0; /* indicates whether to free peer */
4346 if (data_length < 2)
4347 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4349 dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
4352 dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
4356 /* The peer object is invalidated for FATAL alerts and close
4357 * notifies. This is done in two steps.: First, remove the object
4358 * from our list of peers. After that, the event handler callback is
4359 * invoked with the still existing peer object. Finally, the storage
4360 * used by peer is released.
4362 if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
4363 dtls_alert("%d invalidate peer\n", data[1]);
4365 #ifndef WITH_CONTIKI
4366 HASH_DEL_PEER(ctx->peers, peer);
4367 #else /* WITH_CONTIKI */
4368 list_remove(ctx->peers, peer);
4371 PRINTF("removed peer [");
4372 PRINT6ADDR(&peer->session.addr);
4373 PRINTF("]:%d\n", uip_ntohs(peer->session.port));
4375 #endif /* WITH_CONTIKI */
4381 (void)CALL(ctx, event, &peer->session,
4382 (dtls_alert_level_t)data[0], (unsigned short)data[1]);
4384 case DTLS_ALERT_CLOSE_NOTIFY:
4385 /* If state is DTLS_STATE_CLOSING, we have already sent a
4386 * close_notify so, do not send that again. */
4387 if (peer->state != DTLS_STATE_CLOSING) {
4388 peer->state = DTLS_STATE_CLOSING;
4389 dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
4391 peer->state = DTLS_STATE_CLOSED;
4398 dtls_clear_retransmission(ctx, peer);
4399 dtls_destroy_peer(ctx, peer, 0);
4405 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
4406 session_t *session, int err)
4411 if (err < -(1 << 8) && err > -(3 << 8)) {
4412 level = ((-err) & 0xff00) >> 8;
4413 desc = (-err) & 0xff;
4415 peer = dtls_get_peer(ctx, session);
4418 peer->state = DTLS_STATE_CLOSING;
4419 return dtls_send_alert(ctx, peer, level, desc);
4421 } else if (err == -1) {
4423 peer = dtls_get_peer(ctx, session);
4426 peer->state = DTLS_STATE_CLOSING;
4427 return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
4434 * Handles incoming data as DTLS message from given peer.
4437 dtls_handle_message(dtls_context_t *ctx,
4439 uint8 *msg, int msglen) {
4440 dtls_peer_t *peer = NULL;
4441 unsigned int rlen; /* record length */
4442 uint8 *data; /* (decrypted) payload */
4443 int data_length; /* length of decrypted payload
4444 (without MAC and padding) */
4447 /* check if we have DTLS state for addr/port/ifindex */
4448 peer = dtls_get_peer(ctx, session);
4451 dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
4452 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
4454 dtls_debug("dtls_handle_message: FOUND PEER\n");
4457 while ((rlen = is_record(msg,msglen))) {
4458 dtls_peer_type role;
4461 dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
4463 data_length = decrypt_verify(peer, msg, rlen, &data);
4464 if (data_length < 0) {
4465 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4466 data = msg + DTLS_RH_LENGTH;
4467 data_length = rlen - DTLS_RH_LENGTH;
4468 state = DTLS_STATE_WAIT_CLIENTHELLO;
4471 if (DTLS_CT_HANDSHAKE == msg[0] && DTLS_STATE_WAIT_FINISHED == peer->state) {
4472 int err = dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
4473 dtls_info("decrypt_verify() failed\n");
4475 dtls_alert_send_from_err(ctx, peer, &peer->session, err);
4477 (void)CALL(ctx, event, &peer->session,
4478 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4479 peer->state = DTLS_STATE_CLOSED;
4480 /* dtls_clear_retransmission(ctx, peer); */
4481 dtls_destroy_peer(ctx, peer, 1);
4484 data = msg + DTLS_RH_LENGTH;
4485 data_length = rlen - DTLS_RH_LENGTH;
4487 state = peer->state;
4492 state = peer->state;
4495 /* is_record() ensures that msg contains at least a record header */
4496 data = msg + DTLS_RH_LENGTH;
4497 data_length = rlen - DTLS_RH_LENGTH;
4498 state = DTLS_STATE_WAIT_CLIENTHELLO;
4502 dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
4503 dtls_debug_hexdump("receive unencrypted", data, data_length);
4505 /* Handle received record according to the first byte of the
4506 * message, i.e. the subprotocol. We currently do not support
4507 * combining multiple fragments of one type into a single
4512 case DTLS_CT_CHANGE_CIPHER_SPEC:
4513 err = handle_ccs(ctx, peer, msg, data, data_length);
4515 dtls_warn("error while handling ChangeCipherSpec message\n");
4516 dtls_alert_send_from_err(ctx, peer, session, err);
4518 (void)CALL(ctx, event, &peer->session,
4519 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4521 /* invalidate peer */
4522 dtls_clear_retransmission(ctx, peer);
4523 dtls_destroy_peer(ctx, peer, 1);
4532 dtls_clear_retransmission(ctx, peer);
4534 err = handle_alert(ctx, peer, msg, data, data_length);
4535 if (err < 0 || err == 1) {
4536 dtls_warn("received alert, peer has been invalidated\n");
4537 /* handle alert has invalidated peer */
4539 return err < 0 ?err:-1;
4543 case DTLS_CT_HANDSHAKE:
4545 /* Handshake messages other than Finish must use the current
4546 * epoch, Finish has epoch + 1. */
4550 /* Handle the client's last flight retransmission when the server's
4551 * Finished message is lost. This avoids deadlock. */
4552 if (DTLS_SERVER == role && DTLS_STATE_CONNECTED == state) {
4553 dtls_start_retransmission(ctx, peer);
4556 uint16_t expected_epoch = dtls_security_params(peer)->epoch;
4557 uint16_t msg_epoch =
4558 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
4560 /* The new security parameters must be used for all messages
4561 * that are sent after the ChangeCipherSpec message. This
4562 * means that the client's Finished message uses epoch + 1
4563 * while the server is still in the old epoch.
4565 if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
4569 if (expected_epoch != msg_epoch) {
4570 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4571 state = DTLS_STATE_WAIT_CLIENTHELLO;
4574 dtls_warn("Wrong epoch, expected %i, got: %i\n",
4575 expected_epoch, msg_epoch);
4581 err = handle_handshake(ctx, peer, session, role, state, data, data_length);
4583 dtls_warn("error while handling handshake packet\n");
4584 dtls_alert_send_from_err(ctx, peer, session, err);
4587 (void)CALL(ctx, event, &peer->session,
4588 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4589 dtls_clear_retransmission(ctx, peer);
4590 dtls_destroy_peer(ctx, peer, 1);
4595 if (peer && peer->state == DTLS_STATE_CONNECTED) {
4596 /* stop retransmissions */
4597 dtls_stop_retransmission(ctx, peer);
4598 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
4602 case DTLS_CT_APPLICATION_DATA:
4603 dtls_info("** application data:\n");
4605 dtls_warn("no peer available, send an alert\n");
4606 // TODO: should we send a alert here?
4609 dtls_clear_retransmission(ctx, peer);
4610 CALL(ctx, read, &peer->session, data, data_length);
4613 dtls_info("dropped unknown message of type %d\n",msg[0]);
4616 /* advance msg by length of ciphertext */
4625 dtls_new_context(void *app_data) {
4629 unsigned int randValue;
4632 #if !defined(WITH_CONTIKI) && !defined(_WIN32)
4633 FILE *urandom = fopen("/dev/urandom", "r");
4634 unsigned char buf[sizeof(unsigned long)];
4635 #endif /* WITH_CONTIKI */
4639 /* FIXME: need something better to init PRNG here */
4640 dtls_prng_init(now);
4641 #elif defined(_WIN32)
4642 err = rand_s(&randValue);
4645 dtls_emerg("cannot initialize PRNG\n");
4648 dtls_prng_init(randValue);
4649 #else /* WITH_CONTIKI */
4651 dtls_emerg("cannot initialize PRNG\n");
4655 if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
4656 dtls_emerg("cannot initialize PRNG\n");
4662 dtls_prng_init((unsigned long)*buf);
4663 #endif /* WITH_CONTIKI */
4665 c = malloc_context();
4669 memset(c, 0, sizeof(dtls_context_t));
4672 LIST_STRUCT_INIT(c, sendqueue);
4675 LIST_STRUCT_INIT(c, peers);
4676 /* LIST_STRUCT_INIT(c, key_store); */
4678 process_start(&dtls_retransmit_process, (char *)c);
4679 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
4680 /* the retransmit timer must be initialized to some large value */
4681 etimer_set(&c->retransmit_timer, 0xFFFF);
4682 PROCESS_CONTEXT_END(&coap_retransmit_process);
4683 #endif /* WITH_CONTIKI */
4685 if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
4686 c->cookie_secret_age = now;
4693 dtls_alert("cannot create DTLS context\n");
4695 dtls_free_context(c);
4700 dtls_free_context(dtls_context_t *ctx) {
4707 #ifndef WITH_CONTIKI
4711 HASH_ITER(hh, ctx->peers, p, tmp) {
4712 dtls_clear_retransmission(ctx, p);
4713 dtls_destroy_peer(ctx, p, 1);
4716 #else /* WITH_CONTIKI */
4717 for (p = list_head(ctx->peers); p; p = list_item_next(p))
4718 dtls_destroy_peer(ctx, p, 1);
4719 #endif /* WITH_CONTIKI */
4725 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
4732 /* check if the same peer is already in our list */
4733 if (peer == dtls_get_peer(ctx, &peer->session)) {
4734 dtls_debug("found peer, try to re-connect\n");
4735 return dtls_renegotiate(ctx, &peer->session);
4738 /* set local peer role to client, remote is server */
4739 peer->role = DTLS_CLIENT;
4741 dtls_add_peer(ctx, peer);
4743 /* send ClientHello with empty Cookie */
4744 peer->handshake_params = dtls_handshake_new();
4745 if (!peer->handshake_params)
4748 peer->handshake_params->hs_state.mseq_r = 0;
4749 peer->handshake_params->hs_state.mseq_s = 0;
4750 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4751 res = dtls_send_client_hello(ctx, peer, NULL, 0);
4753 dtls_warn("cannot send ClientHello\n");
4755 peer->state = DTLS_STATE_CLIENTHELLO;
4761 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
4765 peer = dtls_get_peer(ctx, dst);
4768 peer = dtls_new_peer(dst);
4771 dtls_crit("cannot create new peer\n");
4775 res = dtls_connect_peer(ctx, peer);
4777 /* Invoke event callback to indicate connection attempt or
4778 * re-negotiation. */
4780 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
4781 } else if (res == 0) {
4782 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
4789 dtls_retransmit(dtls_context_t *context, netq_t *node) {
4790 if (!context || !node)
4793 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
4794 if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
4795 unsigned char sendbuf[DTLS_MAX_BUF];
4796 size_t len = sizeof(sendbuf);
4798 unsigned char *data = node->data;
4799 size_t length = node->length;
4801 dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
4804 node->retransmit_cnt++;
4808 node->t = now + (node->timeout << node->retransmit_cnt);
4810 netq_insert_node(context->sendqueue, node);
4812 if (node->type == DTLS_CT_HANDSHAKE) {
4813 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4815 dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
4816 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4818 dtls_debug("** retransmit packet\n");
4821 err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
4824 dtls_warn("can not retransmit packet, err: %i\n", err);
4827 dtls_debug_hexdump("retransmit header", sendbuf,
4828 sizeof(dtls_record_header_t));
4829 dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
4831 (void)CALL(context, write, &node->peer->session, sendbuf, len);
4835 /* no more retransmissions, remove node from system */
4837 dtls_debug("** removed transaction\n");
4839 /* And finally delete the node */
4840 netq_node_free(node);
4844 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4846 node = list_head(context->sendqueue);
4849 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4852 node = list_item_next(node);
4857 dtls_start_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4859 node = list_head(context->sendqueue);
4862 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4863 node->retransmit_cnt = 0;
4866 node = list_item_next(node);
4871 dtls_clear_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4873 node = list_head(context->sendqueue);
4876 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4878 node = list_item_next(node);
4879 list_remove(context->sendqueue, tmp);
4880 netq_node_free(tmp);
4882 node = list_item_next(node);
4888 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
4890 netq_t *node = netq_head(context->sendqueue);
4895 if (node->t && node->t <= now){
4896 netq_pop_first(context->sendqueue);
4897 dtls_retransmit(context, node);
4898 node = netq_head(context->sendqueue);
4900 node = list_item_next(node);
4906 dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
4907 const uint8_t* label, const uint32_t labellen,
4908 const uint8_t* random1, const uint32_t random1len,
4909 const uint8_t* random2, const uint32_t random2len,
4910 uint8_t* buf, const uint32_t buflen) {
4911 dtls_peer_t *peer = NULL;
4912 dtls_security_parameters_t *security = NULL;
4915 if(!ctx || !session || !label || !buf || labellen == 0 || buflen == 0) {
4916 dtls_warn("dtls_prf_with_current_keyblock(): invalid parameter\n");
4920 peer = dtls_get_peer(ctx, session);
4922 dtls_warn("dtls_prf_with_current_keyblock(): cannot find peer\n");
4926 security = dtls_security_params(peer);
4928 dtls_crit("dtls_prf_with_current_keyblock(): peer has empty security parameters\n");
4932 /* note that keysize should never be zero as bad things will happen */
4933 keysize = dtls_kb_size(security, peer->role);
4934 assert(keysize > 0);
4936 return dtls_prf(security->key_block, keysize,
4938 random1, random1len,
4939 random2, random2len,
4944 /*---------------------------------------------------------------------------*/
4945 /* message retransmission */
4946 /*---------------------------------------------------------------------------*/
4947 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4954 dtls_debug("Started DTLS retransmit process\r\n");
4958 if (ev == PROCESS_EVENT_TIMER) {
4959 if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4961 node = list_head(the_dtls_context.sendqueue);
4964 if (node && node->t <= now) {
4965 dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
4966 node = list_head(the_dtls_context.sendqueue);
4969 /* need to set timer to some value even if no nextpdu is available */
4971 etimer_set(&the_dtls_context.retransmit_timer,
4972 node->t <= now ? 1 : node->t - now);
4974 etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4982 #endif /* WITH_CONTIKI */