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 static inline dtls_context_t *
143 return &the_dtls_context;
147 free_context(dtls_context_t *context) {
150 #else /* WITH_CONTIKI */
152 static inline 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];
322 /* create cookie with HMAC-SHA256 over:
324 * - session parameters (only IP address?)
326 * - random gmt and bytes
329 * - compression method
332 /* We use our own buffer as hmac_context instead of a dynamic buffer
333 * created by dtls_hmac_new() to separate storage space for cookie
334 * creation from storage that is used in real sessions. Note that
335 * the buffer size must fit with the default hash algorithm (see
336 * implementation of dtls_hmac_context_new()). */
338 dtls_hmac_context_t hmac_context;
339 dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
341 dtls_hmac_update(&hmac_context,
342 (unsigned char *)&session->addr, session->size);
344 /* feed in the beginning of the Client Hello up to and including the
346 e = sizeof(dtls_client_hello_t);
347 e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
348 if (e + DTLS_HS_LENGTH > msglen)
349 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
351 dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
353 /* skip cookie bytes and length byte */
354 e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
356 if (e + DTLS_HS_LENGTH > msglen)
357 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
359 dtls_hmac_update(&hmac_context,
360 msg + DTLS_HS_LENGTH + e,
361 dtls_get_fragment_length(DTLS_HANDSHAKE_HEADER(msg)) - e);
363 len = dtls_hmac_finalize(&hmac_context, buf);
366 memset(cookie + len, 0, *clen - len);
370 memcpy(cookie, buf, *clen);
374 #ifdef DTLS_CHECK_CONTENTTYPE
375 /* used to check if a received datagram contains a DTLS message */
376 static char const content_types[] = {
377 DTLS_CT_CHANGE_CIPHER_SPEC,
380 DTLS_CT_APPLICATION_DATA,
386 * Checks if \p msg points to a valid DTLS record. If
390 is_record(uint8 *msg, size_t msglen) {
391 unsigned int rlen = 0;
393 if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
394 #ifdef DTLS_CHECK_CONTENTTYPE
395 && strchr(content_types, msg[0])
397 && msg[1] == HIGH(DTLS_VERSION)
398 && msg[2] == LOW(DTLS_VERSION))
400 rlen = DTLS_RH_LENGTH +
401 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->length);
403 /* we do not accept wrong length field in record header */
412 * Initializes \p buf as record header. The caller must ensure that \p
413 * buf is capable of holding at least \c sizeof(dtls_record_header_t)
414 * bytes. Increments sequence number counter of \p security.
415 * \return pointer to the next byte after the written header.
416 * The length will be set to 0 and has to be changed before sending.
418 static inline uint8 *
419 dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
422 dtls_int_to_uint8(buf, type);
423 buf += sizeof(uint8);
425 dtls_int_to_uint16(buf, DTLS_VERSION);
426 buf += sizeof(uint16);
429 dtls_int_to_uint16(buf, security->epoch);
430 buf += sizeof(uint16);
432 dtls_int_to_uint48(buf, security->rseq);
433 buf += sizeof(uint48);
435 /* increment record sequence counter by 1 */
438 memset(buf, 0, sizeof(uint16) + sizeof(uint48));
439 buf += sizeof(uint16) + sizeof(uint48);
442 memset(buf, 0, sizeof(uint16));
443 return buf + sizeof(uint16);
447 * Initializes \p buf as handshake header. The caller must ensure that \p
448 * buf is capable of holding at least \c sizeof(dtls_handshake_header_t)
449 * bytes. Increments message sequence number counter of \p peer.
450 * \return pointer to the next byte after \p buf
452 static inline uint8 *
453 dtls_set_handshake_header(uint8 type, dtls_peer_t *peer,
455 int frag_offset, int frag_length,
458 dtls_int_to_uint8(buf, type);
459 buf += sizeof(uint8);
461 dtls_int_to_uint24(buf, length);
462 buf += sizeof(uint24);
464 if (peer && peer->handshake_params) {
465 /* and copy the result to buf */
466 dtls_int_to_uint16(buf, peer->handshake_params->hs_state.mseq_s);
468 /* increment handshake message sequence counter by 1 */
469 peer->handshake_params->hs_state.mseq_s++;
471 memset(buf, 0, sizeof(uint16));
473 buf += sizeof(uint16);
475 dtls_int_to_uint24(buf, frag_offset);
476 buf += sizeof(uint24);
478 dtls_int_to_uint24(buf, frag_length);
479 buf += sizeof(uint24);
484 /** only one compression method is currently defined */
485 static uint8 compression_methods[] = {
489 /** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
490 static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
492 #if defined(DTLS_ECC) || defined(DTLS_X509)
493 return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
496 #endif /* DTLS_ECC */
499 /** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
500 static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
503 return cipher == TLS_PSK_WITH_AES_128_CCM_8;
506 #endif /* DTLS_PSK */
509 /** returns true if the cipher matches TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
510 static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
513 return cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256;
519 /** returns true if the cipher matches TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 */
520 static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
522 #if defined(DTLS_ECC) && defined(DTLS_PSK)
523 return cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256;
526 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
531 /** returns true if the application is configured for psk */
532 static inline int is_psk_supported(dtls_context_t *ctx)
535 return ctx && ctx->h && ctx->h->get_psk_info;
538 #endif /* DTLS_PSK */
541 /** returns true if the application is configured for ecdhe_ecdsa */
542 static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
545 return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
546 (is_client && ctx->h->verify_ecdsa_key));
549 #endif /* DTLS_ECC */
552 /** returns true if the application is configured for x509 */
553 static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
556 return ctx && ctx->h && ((!is_client && ctx->h->get_x509_cert) ||
557 (is_client && ctx->h->verify_x509_cert));
560 #endif /* DTLS_X509 */
563 /** Returns true if the application is configured for ecdhe_ecdsa with
564 * client authentication */
565 static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
568 return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
571 #endif /* DTLS_ECC */
574 /** Returns true if the application is configured for x509 with
575 * client authentication */
576 static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
579 return ctx && ctx->h && ctx->h->get_x509_cert && ctx->h->verify_x509_cert;
582 #endif /* DTLS_X509 */
585 /** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
586 static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
589 return ctx && (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
595 /** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
596 static inline int is_ecdhe_psk_supported(dtls_context_t *ctx)
598 #if defined(DTLS_ECC) && defined(DTLS_PSK)
599 return is_psk_supported(ctx);
602 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
607 * Returns @c 1 if @p code is a cipher suite other than @c
608 * TLS_NULL_WITH_NULL_NULL that we recognize.
610 * @param ctx The current DTLS context
611 * @param code The cipher suite identifier to check
612 * @param is_client 1 for a dtls client, 0 for server
613 * @return @c 1 iff @p code is recognized,
616 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
623 psk = is_psk_supported(ctx);
624 ecdsa = is_ecdsa_supported(ctx, is_client);
625 ecdh_anon = is_ecdh_anon_supported(ctx);
626 ecdhe_psk = is_ecdhe_psk_supported(ctx);
627 x509 = is_x509_supported(ctx, is_client);
629 return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
630 (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code)) ||
631 (ecdh_anon && is_tls_ecdh_anon_with_aes_128_cbc_sha_256(code)) ||
632 (ecdhe_psk && is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(code)) ||
633 (x509 && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
637 * This method detects if we already have a established DTLS session with
638 * peer and the peer is attempting to perform a fresh handshake by sending
639 * messages with epoch = 0. This is to handle situations mentioned in
640 * RFC 6347 - section 4.2.8.
642 * @param msg The packet received from Client
643 * @param msglen Packet length
644 * @param peer peer who is the sender for this packet
645 * @return @c 1 if this is a rehandshake attempt by
649 hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
652 if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
653 if (msg[0] == DTLS_CT_HANDSHAKE) {
654 uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
655 if (msg_epoch == 0) {
656 dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
657 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
658 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
667 /** Dump out the cipher keys and IVs used for the symetric cipher. */
668 static void dtls_debug_keyblock(dtls_security_parameters_t *config)
670 dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
671 dtls_debug_dump(" client_MAC_secret",
672 dtls_kb_client_mac_secret(config, peer->role),
673 dtls_kb_mac_secret_size(config->cipher));
675 dtls_debug_dump(" server_MAC_secret",
676 dtls_kb_server_mac_secret(config, peer->role),
677 dtls_kb_mac_secret_size(config->cipher));
679 dtls_debug_dump(" client_write_key",
680 dtls_kb_client_write_key(config, peer->role),
681 dtls_kb_key_size(config, peer->role));
683 dtls_debug_dump(" server_write_key",
684 dtls_kb_server_write_key(config, peer->role),
685 dtls_kb_key_size(config, peer->role));
687 dtls_debug_dump(" client_IV",
688 dtls_kb_client_iv(config, peer->role),
689 dtls_kb_iv_size(config->cipher));
691 dtls_debug_dump(" server_IV",
692 dtls_kb_server_iv(config, peer->role),
693 dtls_kb_iv_size(config->cipher));
696 /** returns the name of the goven handshake type number.
697 * see IANA for a full list of types:
698 * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
700 static char *dtls_handshake_type_to_name(int type)
703 case DTLS_HT_HELLO_REQUEST:
704 return "hello_request";
705 case DTLS_HT_CLIENT_HELLO:
706 return "client_hello";
707 case DTLS_HT_SERVER_HELLO:
708 return "server_hello";
709 case DTLS_HT_HELLO_VERIFY_REQUEST:
710 return "hello_verify_request";
711 case DTLS_HT_CERTIFICATE:
712 return "certificate";
713 case DTLS_HT_SERVER_KEY_EXCHANGE:
714 return "server_key_exchange";
715 case DTLS_HT_CERTIFICATE_REQUEST:
716 return "certificate_request";
717 case DTLS_HT_SERVER_HELLO_DONE:
718 return "server_hello_done";
719 case DTLS_HT_CERTIFICATE_VERIFY:
720 return "certificate_verify";
721 case DTLS_HT_CLIENT_KEY_EXCHANGE:
722 return "client_key_exchange";
723 case DTLS_HT_FINISHED:
731 * Calculate the pre master secret and after that calculate the master-secret.
734 calculate_key_block(dtls_context_t *ctx,
735 dtls_handshake_parameters_t *handshake,
738 dtls_peer_type role) {
739 #if defined(DTLS_PSK) && defined(DTLS_ECC)
740 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH + uECC_BYTES];
742 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH];
743 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
744 int pre_master_len = 0;
745 dtls_security_parameters_t *security = dtls_security_params_next(peer);
746 uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
749 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
752 switch (handshake->cipher) {
754 case TLS_PSK_WITH_AES_128_CCM_8: {
755 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
758 len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
759 handshake->keyx.psk.identity,
760 handshake->keyx.psk.id_length,
761 psk, DTLS_PSK_MAX_KEY_LEN);
763 dtls_crit("no psk key for session available\n");
766 /* Temporarily use the key_block storage space for the pre master secret. */
767 pre_master_len = dtls_psk_pre_master_secret(psk, len,
769 MAX_KEYBLOCK_LENGTH);
771 dtls_debug_hexdump("psk", psk, len);
773 memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
774 if (pre_master_len < 0) {
775 dtls_crit("the psk was too long, for the pre master secret\n");
776 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
781 #endif /* DTLS_PSK */
782 #if defined(DTLS_ECC) || defined(DTLS_X509)
783 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
784 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
785 pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecc.own_eph_priv,
786 handshake->keyx.ecc.other_eph_pub_x,
787 handshake->keyx.ecc.other_eph_pub_y,
788 sizeof(handshake->keyx.ecc.own_eph_priv),
790 MAX_KEYBLOCK_LENGTH);
791 if (pre_master_len < 0) {
792 dtls_crit("the curve was too long, for the pre master secret\n");
793 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
797 #endif /* DTLS_ECC */
798 #if defined(DTLS_PSK) && defined(DTLS_ECC)
799 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
800 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
803 psklen = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
804 handshake->keyx.psk.identity,
805 handshake->keyx.psk.id_length,
806 psk, DTLS_PSK_MAX_KEY_LEN);
808 dtls_crit("no psk key for session available\n");
812 pre_master_len = dtls_ecdhe_psk_pre_master_secret(psk, psklen,
813 handshake->keyx.ecc.own_eph_priv,
814 handshake->keyx.ecc.other_eph_pub_x,
815 handshake->keyx.ecc.other_eph_pub_y,
816 sizeof(handshake->keyx.ecc.own_eph_priv),
818 MAX_KEYBLOCK_LENGTH + uECC_BYTES);
820 if (pre_master_len < 0) {
821 dtls_crit("the curve was too long, for the pre master secret\n");
822 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
826 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
828 dtls_crit("calculate_key_block: unknown cipher\n");
829 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
832 dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
833 dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
834 dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
836 dtls_prf(pre_master_secret, pre_master_len,
837 PRF_LABEL(master), PRF_LABEL_SIZE(master),
838 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
839 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
841 DTLS_MASTER_SECRET_LENGTH);
843 dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
845 /* create key_block from master_secret
846 * key_block = PRF(master_secret,
847 "key expansion" + tmp.random.server + tmp.random.client) */
848 security->cipher = handshake->cipher;
849 security->compression = handshake->compression;
852 dtls_prf(master_secret,
853 DTLS_MASTER_SECRET_LENGTH,
854 PRF_LABEL(key), PRF_LABEL_SIZE(key),
855 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
856 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
858 dtls_kb_size(security, role));
860 memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
861 dtls_debug_keyblock(security);
867 /* TODO: add a generic method which iterates over a list and searches for a specific key */
868 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
871 /* length of curve list */
872 i = dtls_uint16_to_int(data);
873 data += sizeof(uint16);
874 if (i + sizeof(uint16) != data_length) {
875 dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
876 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
879 for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
880 /* check if this curve is supported */
881 curve_name = dtls_uint16_to_int(data);
882 data += sizeof(uint16);
884 if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
888 dtls_warn("no supported elliptic curve found\n");
889 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
892 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
895 /* length of cert type list */
896 i = dtls_uint8_to_int(data);
897 data += sizeof(uint8);
898 if (i + sizeof(uint8) != data_length) {
899 dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
900 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
903 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
904 /* check if this cert type is supported */
905 cert_type = dtls_uint8_to_int(data);
906 data += sizeof(uint8);
909 if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
912 if (cert_type == TLS_CERT_TYPE_X509)
917 dtls_warn("no supported certificate type found\n");
918 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
921 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
924 /* length of ec_point_formats list */
925 i = dtls_uint8_to_int(data);
926 data += sizeof(uint8);
927 if (i + sizeof(uint8) != data_length) {
928 dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
929 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
932 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
933 /* check if this ec_point_format is supported */
934 cert_type = dtls_uint8_to_int(data);
935 data += sizeof(uint8);
937 if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
941 dtls_warn("no supported ec_point_format found\n");
942 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
946 * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
949 dtls_check_tls_extension(dtls_peer_t *peer,
950 uint8 *data, size_t data_length, int client_hello)
953 int ext_elliptic_curve = 0;
954 int ext_client_cert_type = 0;
955 int ext_server_cert_type = 0;
956 int ext_ec_point_formats = 0;
957 dtls_handshake_parameters_t *handshake = peer->handshake_params;
959 if (data_length < sizeof(uint16)) {
960 /* no tls extensions specified */
961 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
967 /* get the length of the tls extension list */
968 j = dtls_uint16_to_int(data);
969 data += sizeof(uint16);
970 data_length -= sizeof(uint16);
975 /* check for TLS extensions needed for this cipher */
976 while (data_length) {
977 if (data_length < sizeof(uint16) * 2)
980 /* get the tls extension type */
981 i = dtls_uint16_to_int(data);
982 data += sizeof(uint16);
983 data_length -= sizeof(uint16);
985 /* get the length of the tls extension */
986 j = dtls_uint16_to_int(data);
987 data += sizeof(uint16);
988 data_length -= sizeof(uint16);
994 case TLS_EXT_ELLIPTIC_CURVES:
995 ext_elliptic_curve = 1;
996 if (verify_ext_eliptic_curves(data, j))
999 case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
1000 ext_client_cert_type = 1;
1002 if (verify_ext_cert_type(data, j))
1006 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
1008 if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
1009 (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1014 case TLS_EXT_SERVER_CERTIFICATE_TYPE:
1015 ext_server_cert_type = 1;
1017 if (verify_ext_cert_type(data, j))
1021 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
1023 if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
1024 (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1029 case TLS_EXT_EC_POINT_FORMATS:
1030 ext_ec_point_formats = 1;
1031 if (verify_ext_ec_point_formats(data, j))
1034 case TLS_EXT_ENCRYPT_THEN_MAC:
1035 /* As only AEAD cipher suites are currently available, this
1036 * extension can be skipped.
1038 dtls_info("skipped encrypt-then-mac extension\n");
1041 dtls_warn("unsupported tls extension: %i\n", i);
1047 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
1048 if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
1049 || !ext_ec_point_formats) {
1050 dtls_warn("not all required tls extensions found in client hello\n");
1053 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
1054 if (!ext_client_cert_type || !ext_server_cert_type) {
1055 dtls_warn("not all required tls extensions found in server hello\n");
1062 if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
1063 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1065 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1070 * Parses the ClientHello from the client and updates the internal handshake
1071 * parameters with the new data for the given \p peer. When the ClientHello
1072 * handshake message in \p data does not contain a cipher suite or
1073 * compression method, it is copied from the the current security parameters.
1075 * \param ctx The current DTLS context.
1076 * \param peer The remote peer whose security parameters are about to change.
1077 * \param data The handshake message with a ClientHello.
1078 * \param data_length The actual size of \p data.
1079 * \return \c -Something if an error occurred, \c 0 on success.
1082 dtls_update_parameters(dtls_context_t *ctx,
1084 uint8 *data, size_t data_length) {
1087 dtls_handshake_parameters_t *config = peer->handshake_params;
1088 dtls_security_parameters_t *security = dtls_security_params(peer);
1091 assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
1093 /* skip the handshake header and client version information */
1094 data += DTLS_HS_LENGTH + sizeof(uint16);
1095 data_length -= DTLS_HS_LENGTH + sizeof(uint16);
1097 /* store client random in config */
1098 memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
1099 data += DTLS_RANDOM_LENGTH;
1100 data_length -= DTLS_RANDOM_LENGTH;
1102 /* Caution: SKIP_VAR_FIELD may jump to error: */
1103 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
1104 SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
1106 i = dtls_uint16_to_int(data);
1107 if (data_length < i + sizeof(uint16)) {
1108 /* Looks like we do not have a cipher nor compression. This is ok
1109 * for renegotiation, but not for the initial handshake. */
1111 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
1114 config->cipher = security->cipher;
1115 config->compression = security->compression;
1120 data += sizeof(uint16);
1121 data_length -= sizeof(uint16) + i;
1125 config->cipher = dtls_uint16_to_int(data);
1126 ok = known_cipher(ctx, config->cipher, 0);
1127 i -= sizeof(uint16);
1128 data += sizeof(uint16);
1131 /* skip remaining ciphers */
1135 /* reset config cipher to a well-defined value */
1136 config->cipher = TLS_NULL_WITH_NULL_NULL;
1137 dtls_warn("No matching cipher found\n");
1141 if (data_length < sizeof(uint8)) {
1142 /* no compression specified, take the current compression method */
1144 config->compression = security->compression;
1146 config->compression = TLS_COMPRESSION_NULL;
1150 i = dtls_uint8_to_int(data);
1151 if (data_length < i + sizeof(uint8))
1154 data += sizeof(uint8);
1155 data_length -= sizeof(uint8) + i;
1159 for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
1160 if (dtls_uint8_to_int(data) == compression_methods[j]) {
1161 config->compression = compression_methods[j];
1165 data += sizeof(uint8);
1169 /* reset config cipher to a well-defined value */
1173 return dtls_check_tls_extension(peer, data, data_length, 1);
1175 if (peer->state == DTLS_STATE_CONNECTED) {
1176 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1178 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1183 * Parse the ClientKeyExchange and update the internal handshake state with
1187 check_client_keyexchange(dtls_context_t *ctx,
1188 dtls_handshake_parameters_t *handshake,
1189 uint8 *data, size_t length) {
1191 #if defined(DTLS_ECC) || defined(DTLS_X509)
1192 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) ||
1193 is_tls_ecdh_anon_with_aes_128_cbc_sha_256(handshake->cipher) ) {
1195 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1196 dtls_debug("The client key exchange is too short\n");
1197 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1199 data += DTLS_HS_LENGTH;
1201 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1202 dtls_alert("expected 65 bytes long public point\n");
1203 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1205 data += sizeof(uint8);
1207 if (dtls_uint8_to_int(data) != 4) {
1208 dtls_alert("expected uncompressed public point\n");
1209 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1211 data += sizeof(uint8);
1213 memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1214 sizeof(handshake->keyx.ecc.other_eph_pub_x));
1215 data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1217 memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1218 sizeof(handshake->keyx.ecc.other_eph_pub_y));
1219 data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1221 #endif /* DTLS_ECC */
1222 #if defined(DTLS_PSK) && defined(DTLS_ECC)
1223 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(handshake->cipher)) {
1226 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1227 dtls_debug("The client key exchange is too short\n");
1228 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1230 data += DTLS_HS_LENGTH;
1233 id_length = dtls_uint16_to_int(data);
1234 data += sizeof(uint16);
1236 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + DTLS_CKXEC_LENGTH + id_length != length) {
1237 dtls_debug("The identity has a wrong length\n");
1238 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1241 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1242 dtls_warn("please use a smaller client identity\n");
1243 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1246 handshake->keyx.psk.id_length = id_length;
1247 memcpy(handshake->keyx.psk.identity, data, id_length);
1251 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1252 dtls_alert("expected 65 bytes long public point\n");
1253 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1255 data += sizeof(uint8);
1257 if (dtls_uint8_to_int(data) != 4) {
1258 dtls_alert("expected uncompressed public point\n");
1259 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1261 data += sizeof(uint8);
1263 memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1264 sizeof(handshake->keyx.ecc.other_eph_pub_x));
1265 data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1267 memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1268 sizeof(handshake->keyx.ecc.other_eph_pub_y));
1269 data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1271 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
1273 if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1276 if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1277 dtls_debug("The client key exchange is too short\n");
1278 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1280 data += DTLS_HS_LENGTH;
1282 id_length = dtls_uint16_to_int(data);
1283 data += sizeof(uint16);
1285 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1286 dtls_debug("The identity has a wrong length\n");
1287 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1290 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1291 dtls_warn("please use a smaller client identity\n");
1292 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1295 handshake->keyx.psk.id_length = id_length;
1296 memcpy(handshake->keyx.psk.identity, data, id_length);
1298 #endif /* DTLS_PSK */
1303 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1304 dtls_debug_dump("add MAC data", data, length);
1305 dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1309 copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
1310 memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1311 sizeof(peer->handshake_params->hs_state.hs_hash));
1314 static inline size_t
1315 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
1316 return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1320 clear_hs_hash(dtls_peer_t *peer) {
1322 dtls_debug("clear MAC\n");
1323 dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
1327 * Checks if \p record + \p data contain a Finished message with valid
1330 * \param ctx The current DTLS context.
1331 * \param peer The remote peer of the security association.
1332 * \param data The cleartext payload of the message.
1333 * \param data_length Actual length of \p data.
1334 * \return \c 0 if the Finished message is valid, \c negative number otherwise.
1337 check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
1338 uint8 *data, size_t data_length) {
1339 size_t digest_length, label_size;
1340 const unsigned char *label;
1341 unsigned char buf[DTLS_HMAC_MAX];
1343 if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1344 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1346 /* Use a union here to ensure that sufficient stack space is
1347 * reserved. As statebuf and verify_data are not used at the same
1348 * time, we can re-use the storage safely.
1351 unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1352 unsigned char verify_data[DTLS_FIN_LENGTH];
1355 /* temporarily store hash status for roll-back after finalize */
1356 memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1358 digest_length = finalize_hs_hash(peer, buf);
1361 /* restore hash status */
1362 memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1364 if (peer->role == DTLS_CLIENT) {
1365 label = PRF_LABEL(server);
1366 label_size = PRF_LABEL_SIZE(server);
1367 } else { /* server */
1368 label = PRF_LABEL(client);
1369 label_size = PRF_LABEL_SIZE(client);
1372 dtls_prf(peer->handshake_params->tmp.master_secret,
1373 DTLS_MASTER_SECRET_LENGTH,
1375 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1377 b.verify_data, sizeof(b.verify_data));
1379 dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1380 dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1382 /* compare verify data and create DTLS alert code when they differ */
1383 return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1385 : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
1389 * Prepares the payload given in \p data for sending with
1390 * dtls_send(). The \p data is encrypted and compressed according to
1391 * the current security parameters of \p peer. The result of this
1392 * operation is put into \p sendbuf with a prepended record header of
1393 * type \p type ready for sending. As some cipher suites add a MAC
1394 * before encryption, \p data must be large enough to hold this data
1395 * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
1397 * \param peer The remote peer the packet will be sent to.
1398 * \param security The encryption paramater used to encrypt
1399 * \param type The content type of this record.
1400 * \param data_array Array with payloads in correct order.
1401 * \param data_len_array sizes of the payloads in correct order.
1402 * \param data_array_len The number of payloads given.
1403 * \param sendbuf The output buffer where the encrypted record
1405 * \param rlen This parameter must be initialized with the
1406 * maximum size of \p sendbuf and will be updated
1407 * to hold the actual size of the stored packet
1408 * on success. On error, the value of \p rlen is
1410 * \return Less than zero on error, or greater than zero success.
1413 dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
1415 uint8 *data_array[], size_t data_len_array[],
1416 size_t data_array_len,
1417 uint8 *sendbuf, size_t *rlen) {
1422 if (*rlen < DTLS_RH_LENGTH) {
1423 dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1424 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1427 p = dtls_set_record_header(type, security, sendbuf);
1430 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1431 /* no cipher suite */
1434 for (i = 0; i < data_array_len; i++) {
1435 /* check the minimum that we need for packets that are not encrypted */
1436 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1437 dtls_debug("dtls_prepare_record: send buffer too small\n");
1438 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1441 memcpy(p, data_array[i], data_len_array[i]);
1442 p += data_len_array[i];
1443 res += data_len_array[i];
1445 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
1446 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
1448 unsigned char nonce[DTLS_CBC_IV_LENGTH];
1450 /** Add IV into body of packet in case of AES CBC mode according to RFC 5246, Section 6.2.3.2
1452 * opaque IV[SecurityParameters.record_iv_length];
1453 * block-ciphered struct {
1454 * opaque content[TLSCompressed.length];
1455 * opaque MAC[SecurityParameters.mac_length];
1456 * uint8 padding[GenericBlockCipher.padding_length];
1457 * uint8 padding_length;
1463 dtls_prng(nonce, DTLS_CBC_IV_LENGTH);
1464 memcpy(p , nonce, DTLS_CBC_IV_LENGTH);
1465 p += DTLS_CBC_IV_LENGTH;
1466 res += DTLS_CBC_IV_LENGTH;
1468 for (i = 0; i < data_array_len; i++) {
1469 /* check the minimum that we need for packets that are not encrypted */
1470 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1471 dtls_debug("dtls_prepare_record: send buffer too small\n");
1472 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1475 memcpy(p, data_array[i], data_len_array[i]);
1476 p += data_len_array[i];
1477 res += data_len_array[i];
1480 res = dtls_encrypt(start + DTLS_CBC_IV_LENGTH, res - DTLS_CBC_IV_LENGTH,
1481 start + DTLS_CBC_IV_LENGTH, nonce,
1482 dtls_kb_local_write_key(security, peer->role),
1483 dtls_kb_key_size(security, peer->role),
1484 dtls_kb_local_mac_secret(security, peer->role),
1485 dtls_kb_mac_secret_size(security->cipher),
1491 res += DTLS_CBC_IV_LENGTH;
1493 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1495 * length of additional_data for the AEAD cipher which consists of
1496 * seq_num(2+6) + type(1) + version(2) + length(2)
1498 #define A_DATA_LEN 13
1499 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1500 unsigned char A_DATA[A_DATA_LEN];
1502 if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1503 dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1504 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1505 dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1507 dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1512 The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1513 the "nonce" SHALL be 12 bytes long and is constructed as follows:
1514 (this is an example of a "partially explicit" nonce; see Section
1515 3.2.1 in [RFC5116]).
1519 opaque nonce_explicit[8];
1524 In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1527 When the nonce_explicit is equal to the sequence number, the CCMNonce
1528 will have the structure of the CCMNonceExample given below.
1531 uint32 client_write_IV; // low order 32-bits
1532 uint64 seq_num; // TLS sequence number
1537 uint32 server_write_IV; // low order 32-bits
1538 uint64 seq_num; // TLS sequence number
1550 memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1554 for (i = 0; i < data_array_len; i++) {
1555 /* check the minimum that we need for packets that are not encrypted */
1556 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1557 dtls_debug("dtls_prepare_record: send buffer too small\n");
1558 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1561 memcpy(p, data_array[i], data_len_array[i]);
1562 p += data_len_array[i];
1563 res += data_len_array[i];
1566 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1567 memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1568 dtls_kb_iv_size(security->cipher));
1569 memcpy(nonce + dtls_kb_iv_size(security->cipher), start, 8); /* epoch + seq_num */
1571 dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1572 dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1573 dtls_kb_key_size(security, peer->role));
1575 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1577 * additional_data = seq_num + TLSCompressed.type +
1578 * TLSCompressed.version + TLSCompressed.length;
1580 memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1581 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1582 dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1584 res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1585 dtls_kb_local_write_key(security, peer->role),
1586 dtls_kb_key_size(security, peer->role),
1587 dtls_kb_local_mac_secret(security, peer->role),
1588 dtls_kb_mac_secret_size(security->cipher),
1595 res += 8; /* increment res by size of nonce_explicit */
1596 dtls_debug_dump("message:", start, res);
1599 /* fix length of fragment in sendbuf */
1600 dtls_int_to_uint16(sendbuf + 11, res);
1602 *rlen = DTLS_RH_LENGTH + res;
1607 dtls_send_handshake_msg_hash(dtls_context_t *ctx,
1611 uint8 *data, size_t data_length,
1614 uint8 buf[DTLS_HS_LENGTH];
1615 uint8 *data_array[2];
1616 size_t data_len_array[2];
1618 dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1620 dtls_set_handshake_header(header_type, peer, data_length, 0,
1624 update_hs_hash(peer, buf, sizeof(buf));
1626 data_array[i] = buf;
1627 data_len_array[i] = sizeof(buf);
1632 update_hs_hash(peer, data, data_length);
1634 data_array[i] = data;
1635 data_len_array[i] = data_length;
1638 dtls_debug("send handshake packet of type: %s (%i)\n",
1639 dtls_handshake_type_to_name(header_type), header_type);
1640 return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1641 data_array, data_len_array, i);
1645 dtls_send_handshake_msg(dtls_context_t *ctx,
1648 uint8 *data, size_t data_length)
1650 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1651 header_type, data, data_length, 1);
1655 * Returns true if the message @p Data is a handshake message that
1656 * must be included in the calculation of verify_data in the Finished
1659 * @param Type The message type. Only handshake messages but the initial
1660 * Client Hello and Hello Verify Request are included in the hash,
1661 * @param Data The PDU to examine.
1662 * @param Length The length of @p Data.
1664 * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
1668 #define MUST_HASH(Type, Data, Length) \
1669 ((Type) == DTLS_CT_HANDSHAKE && \
1670 ((Data) != NULL) && ((Length) > 0) && \
1671 ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) && \
1672 ((Data)[0] != DTLS_HT_CLIENT_HELLO || \
1673 ((Length) >= HS_HDR_LENGTH && \
1674 (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) || \
1675 (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1678 * Sends the data passed in @p buf as a DTLS record of type @p type to
1679 * the given peer. The data will be encrypted and compressed according
1680 * to the security parameters for @p peer.
1682 * @param ctx The DTLS context in effect.
1683 * @param peer The remote party where the packet is sent.
1684 * @param type The content type of this record.
1685 * @param buf The data to send.
1686 * @param buflen The number of bytes to send from @p buf.
1687 * @return Less than zero in case of an error or the number of
1688 * bytes that have been sent otherwise.
1691 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
1692 dtls_security_parameters_t *security , session_t *session,
1693 unsigned char type, uint8 *buf_array[],
1694 size_t buf_len_array[], size_t buf_array_len)
1696 /* We cannot use ctx->sendbuf here as it is reserved for collecting
1697 * the input for this function, i.e. buf == ctx->sendbuf.
1699 * TODO: check if we can use the receive buf here. This would mean
1700 * that we might not be able to handle multiple records stuffed in
1701 * one UDP datagram */
1702 unsigned char sendbuf[DTLS_MAX_BUF];
1703 size_t len = sizeof(sendbuf);
1706 size_t overall_len = 0;
1708 res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1713 /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1714 /* update_hs_hash(peer, buf, buflen); */
1716 dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1717 for (i = 0; i < buf_array_len; i++) {
1718 dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1719 overall_len += buf_len_array[i];
1722 if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1723 type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1724 /* copy handshake messages other than HelloVerify into retransmit buffer */
1725 netq_t *n = netq_node_new(overall_len);
1729 n->t = now + 2 * CLOCK_SECOND;
1730 n->retransmit_cnt = 0;
1731 n->timeout = 2 * CLOCK_SECOND;
1733 n->epoch = (security) ? security->epoch : 0;
1736 for (i = 0; i < buf_array_len; i++) {
1737 memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1738 n->length += buf_len_array[i];
1741 if (!netq_insert_node(ctx->sendqueue, n)) {
1742 dtls_warn("cannot add packet to retransmit buffer\n");
1746 /* must set timer within the context of the retransmit process */
1747 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1748 etimer_set(&ctx->retransmit_timer, n->timeout);
1749 PROCESS_CONTEXT_END(&dtls_retransmit_process);
1750 #else /* WITH_CONTIKI */
1751 dtls_debug("copied to sendqueue\n");
1752 #endif /* WITH_CONTIKI */
1755 dtls_warn("retransmit buffer full\n");
1758 /* FIXME: copy to peer's sendqueue (after fragmentation if
1759 * necessary) and initialize retransmit timer */
1760 res = CALL(ctx, write, session, sendbuf, len);
1762 /* Guess number of bytes application data actually sent:
1763 * dtls_prepare_record() tells us in len the number of bytes to
1764 * send, res will contain the bytes actually sent. */
1765 return res <= 0 ? res : overall_len - (len - res);
1769 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
1770 dtls_alert_t description) {
1771 uint8_t msg[] = { level, description };
1773 dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1778 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1782 peer = dtls_get_peer(ctx, remote);
1785 res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
1786 /* indicate tear down */
1787 peer->state = DTLS_STATE_CLOSING;
1792 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1794 if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1795 dtls_close(ctx, &peer->session);
1797 #ifndef WITH_CONTIKI
1798 HASH_DEL_PEER(ctx->peers, peer);
1799 #else /* WITH_CONTIKI */
1800 list_remove(ctx->peers, peer);
1801 #endif /* WITH_CONTIKI */
1803 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1805 dtls_free_peer(peer);
1809 * Checks a received Client Hello message for a valid cookie. When the
1810 * Client Hello contains no cookie, the function fails and a Hello
1811 * Verify Request is sent to the peer (using the write callback function
1812 * registered with \p ctx). The return value is \c -1 on error, \c 0 when
1813 * undecided, and \c 1 if the Client Hello was good.
1815 * \param ctx The DTLS context.
1816 * \param peer The remote party we are talking to, if any.
1817 * \param session Transport address of the remote peer.
1818 * \param state Current state of the connection.
1819 * \param msg The received datagram.
1820 * \param msglen Length of \p msg.
1821 * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
1825 dtls_verify_peer(dtls_context_t *ctx,
1828 const dtls_state_t state,
1829 uint8 *data, size_t data_length)
1831 uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
1833 int len = DTLS_COOKIE_LENGTH;
1834 uint8 *cookie = NULL;
1837 #define mycookie (buf + DTLS_HV_LENGTH)
1839 /* Store cookie where we can reuse it for the HelloVerify request. */
1840 err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1844 dtls_debug_dump("create cookie", mycookie, len);
1846 assert(len == DTLS_COOKIE_LENGTH);
1848 /* Perform cookie check. */
1849 len = dtls_get_cookie(data, data_length, &cookie);
1851 dtls_warn("error while fetching the cookie, err: %i\n", err);
1855 dtls_debug_dump("compare with cookie", cookie, len);
1857 /* check if cookies match */
1858 if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1859 dtls_debug("found matching cookie\n");
1864 dtls_debug_dump("invalid cookie", cookie, len);
1866 dtls_debug("cookie len is 0!\n");
1869 /* ClientHello did not contain any valid cookie, hence we send a
1870 * HelloVerify request. */
1872 dtls_int_to_uint16(p, DTLS_VERSION);
1873 p += sizeof(uint16);
1875 dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
1878 assert(p == mycookie);
1880 p += DTLS_COOKIE_LENGTH;
1882 /* TODO use the same record sequence number as in the ClientHello,
1883 see 4.2.1. Denial-of-Service Countermeasures */
1884 err = dtls_send_handshake_msg_hash(ctx,
1885 state == DTLS_STATE_CONNECTED ? peer : NULL,
1887 DTLS_HT_HELLO_VERIFY_REQUEST,
1890 dtls_warn("cannot send HelloVerify request\n");
1892 return err; /* HelloVerify is sent, now we cannot do anything but wait */
1897 #if defined(DTLS_ECC) || defined(DTLS_X509)
1899 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1900 unsigned char **result_r,
1901 unsigned char **result_s)
1904 uint8 *data_orig = data;
1906 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
1907 dtls_alert("only sha256 is supported in certificate verify\n");
1908 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1910 data += sizeof(uint8);
1911 data_length -= sizeof(uint8);
1913 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
1914 dtls_alert("only ecdsa signature is supported in client verify\n");
1915 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1917 data += sizeof(uint8);
1918 data_length -= sizeof(uint8);
1920 if (data_length < dtls_uint16_to_int(data)) {
1921 dtls_alert("signature length wrong\n");
1922 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1924 data += sizeof(uint16);
1925 data_length -= sizeof(uint16);
1927 if (dtls_uint8_to_int(data) != 0x30) {
1928 dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1929 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1931 data += sizeof(uint8);
1932 data_length -= sizeof(uint8);
1934 if (data_length < dtls_uint8_to_int(data)) {
1935 dtls_alert("signature length wrong\n");
1936 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1938 data += sizeof(uint8);
1939 data_length -= sizeof(uint8);
1941 if (dtls_uint8_to_int(data) != 0x02) {
1942 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1943 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1945 data += sizeof(uint8);
1946 data_length -= sizeof(uint8);
1948 i = dtls_uint8_to_int(data);
1949 data += sizeof(uint8);
1950 data_length -= sizeof(uint8);
1952 /* Sometimes these values have a leeding 0 byte */
1953 *result_r = data + i - DTLS_EC_KEY_SIZE;
1958 if (dtls_uint8_to_int(data) != 0x02) {
1959 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1960 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1962 data += sizeof(uint8);
1963 data_length -= sizeof(uint8);
1965 i = dtls_uint8_to_int(data);
1966 data += sizeof(uint8);
1967 data_length -= sizeof(uint8);
1969 /* Sometimes these values have a leeding 0 byte */
1970 *result_s = data + i - DTLS_EC_KEY_SIZE;
1975 return data - data_orig;
1979 check_client_certificate_verify(dtls_context_t *ctx,
1981 uint8 *data, size_t data_length)
1983 dtls_handshake_parameters_t *config = peer->handshake_params;
1985 unsigned char *result_r;
1986 unsigned char *result_s;
1987 dtls_hash_ctx hs_hash;
1988 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1990 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
1992 data += DTLS_HS_LENGTH;
1994 if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1995 dtls_alert("the packet length does not match the expected\n");
1996 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1999 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
2006 copy_hs_hash(peer, &hs_hash);
2008 dtls_hash_finalize(sha256hash, &hs_hash);
2010 ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
2011 sizeof(config->keyx.ecc.other_pub_x),
2012 sha256hash, sizeof(sha256hash),
2013 result_r, result_s);
2016 dtls_alert("wrong signature err: %i\n", ret);
2017 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2021 #endif /* DTLS_ECC */
2024 dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
2026 /* Ensure that the largest message to create fits in our source
2027 * buffer. (The size of the destination buffer is checked by the
2028 * encoding function, so we do not need to guess.) */
2029 uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
2032 uint8 extension_size;
2033 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2036 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
2038 extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
2040 /* Handshake header */
2044 dtls_int_to_uint16(p, DTLS_VERSION);
2045 p += sizeof(uint16);
2047 /* Set server random: First 4 bytes are the server's Unix timestamp,
2048 * followed by 28 bytes of generate random data. */
2050 dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
2051 dtls_prng(handshake->tmp.random.server + 4, 28);
2053 memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
2054 p += DTLS_RANDOM_LENGTH;
2056 *p++ = 0; /* no session id */
2058 if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
2059 /* selected cipher suite */
2060 dtls_int_to_uint16(p, handshake->cipher);
2061 p += sizeof(uint16);
2063 /* selected compression method */
2064 *p++ = compression_methods[handshake->compression];
2067 if (extension_size) {
2068 /* length of the extensions */
2069 dtls_int_to_uint16(p, extension_size - 2);
2070 p += sizeof(uint16);
2074 /* client certificate type extension */
2075 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2076 p += sizeof(uint16);
2078 /* length of this extension type */
2079 dtls_int_to_uint16(p, 1);
2080 p += sizeof(uint16);
2082 if (CALL(ctx, is_x509_active) == 0)
2083 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2085 #endif /* DTLS_X509 */
2086 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2090 /* client certificate type extension */
2091 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2092 p += sizeof(uint16);
2094 /* length of this extension type */
2095 dtls_int_to_uint16(p, 1);
2096 p += sizeof(uint16);
2099 if (CALL(ctx, is_x509_active) == 0)
2100 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2102 #endif /* DTLS_X509 */
2103 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2107 /* ec_point_formats */
2108 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2109 p += sizeof(uint16);
2111 /* length of this extension type */
2112 dtls_int_to_uint16(p, 2);
2113 p += sizeof(uint16);
2115 /* number of supported formats */
2116 dtls_int_to_uint8(p, 1);
2119 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2123 assert(p - buf <= sizeof(buf));
2125 /* TODO use the same record sequence number as in the ClientHello,
2126 see 4.2.1. Denial-of-Service Countermeasures */
2127 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
2132 #define DTLS_EC_SUBJECTPUBLICKEY_SIZE (2 * DTLS_EC_KEY_SIZE + sizeof(cert_asn1_header))
2135 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
2136 const dtls_ecc_key_t *key)
2138 uint8 buf[DTLS_CE_LENGTH];
2143 * Start message construction at beginning of buffer. */
2146 /* length of this certificate */
2147 dtls_int_to_uint24(p, DTLS_EC_SUBJECTPUBLICKEY_SIZE);
2148 p += sizeof(uint24);
2150 memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
2151 p += sizeof(cert_asn1_header);
2153 memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
2154 p += DTLS_EC_KEY_SIZE;
2156 memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
2157 p += DTLS_EC_KEY_SIZE;
2159 assert(p - buf <= sizeof(buf));
2161 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2164 #endif /* DTLS_ECC */
2168 dtls_send_certificate_x509(dtls_context_t *ctx, dtls_peer_t *peer)
2170 uint8 buf[DTLS_MAX_CERT_SIZE];
2173 unsigned char *cert;
2176 dtls_info("\n dtls_send_certificate_ecdsa\n");
2177 ret = CALL(ctx, get_x509_cert, &peer->session,
2178 (const unsigned char **)&cert, &cert_size);
2181 dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2187 * Start message construction at beginning of buffer. */
2190 dtls_int_to_uint24(p, cert_size); /* certificates length */
2191 p += sizeof(uint24);
2193 memcpy(p, cert, cert_size);
2196 assert(p - buf <= sizeof(buf));
2198 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2201 #endif /* DTLS_X509 */
2203 #if defined(DTLS_X509) || defined(DTLS_ECC)
2205 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
2210 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
2211 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
2212 /* store the pointer to the r component of the signature and make space */
2213 len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
2214 len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
2220 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2224 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2227 /* length of signature */
2228 dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
2229 p += sizeof(uint16);
2231 /* ASN.1 SEQUENCE */
2232 dtls_int_to_uint8(p, 0x30);
2235 dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
2238 /* ASN.1 Integer r */
2239 dtls_int_to_uint8(p, 0x02);
2242 dtls_int_to_uint8(p, len_r);
2245 /* the pint r was added here */
2248 /* ASN.1 Integer s */
2249 dtls_int_to_uint8(p, 0x02);
2252 dtls_int_to_uint8(p, len_s);
2255 /* the pint s was added here */
2262 dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2263 const dtls_ecc_key_t *key)
2265 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2266 * 33 bytes long add space for that */
2267 uint8 buf[DTLS_SKEXEC_LENGTH + 2];
2270 uint8 *ephemeral_pub_x;
2271 uint8 *ephemeral_pub_y;
2272 uint32_t point_r[9];
2273 uint32_t point_s[9];
2275 dtls_handshake_parameters_t *config = peer->handshake_params;
2277 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2278 /* ServerKeyExchange
2280 * Start message construction at beginning of buffer. */
2284 /* ECCurveType curve_type: named_curve */
2285 dtls_int_to_uint8(p, 3);
2288 /* NamedCurve namedcurve: secp256r1 */
2289 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2290 p += sizeof(uint16);
2292 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2295 /* This should be an uncompressed point, but I do not have access to the spec. */
2296 dtls_int_to_uint8(p, 4);
2299 /* store the pointer to the x component of the pub key and make space */
2300 ephemeral_pub_x = p;
2301 p += DTLS_EC_KEY_SIZE;
2303 /* store the pointer to the y component of the pub key and make space */
2304 ephemeral_pub_y = p;
2305 p += DTLS_EC_KEY_SIZE;
2307 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2308 ephemeral_pub_x, ephemeral_pub_y,
2311 /* sign the ephemeral and its paramaters */
2312 dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
2313 config->tmp.random.client, DTLS_RANDOM_LENGTH,
2314 config->tmp.random.server, DTLS_RANDOM_LENGTH,
2315 key_params, p - key_params,
2318 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2321 assert(p - buf <= sizeof(buf));
2323 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2326 #endif /* defined(DTLS_X509) || defined(DTLS_ECC) */
2328 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2329 static int dtls_send_server_key_exchange_ecdhe_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2330 const unsigned char *psk_hint, size_t psk_hint_len)
2332 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2333 * 33 bytes long add space for that */
2334 uint8 buf[DTLS_SKEXEC_LENGTH + DTLS_SKEXECPSK_LENGTH_MAX + 2];
2336 uint8 *ephemeral_pub_x;
2337 uint8 *ephemeral_pub_y;
2338 dtls_handshake_parameters_t *config = peer->handshake_params;
2340 /* ServerKeyExchange
2341 * Please see Session 2, RFC 5489.
2344 select (KeyExchangeAlgorithm) {
2345 //other cases for rsa, diffie_hellman, etc.
2346 case ec_diffie_hellman_psk: // NEW
2347 opaque psk_identity_hint<0..2^16-1>;
2348 ServerECDHParams params;
2350 } ServerKeyExchange; */
2353 assert(psk_hint_len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2354 if (psk_hint_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2355 // should never happen
2356 dtls_warn("psk identity hint is too long\n");
2357 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2360 // psk_identity_hint
2361 dtls_int_to_uint16(p, psk_hint_len);
2362 p += sizeof(uint16);
2364 memcpy(p, psk_hint, psk_hint_len);
2367 /* ServerECDHParams. */
2368 /* ECCurveType curve_type: named_curve */
2369 dtls_int_to_uint8(p, TLS_EC_CURVE_TYPE_NAMED_CURVE);
2372 /* NamedCurve namedcurve: secp256r1 */
2373 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2374 p += sizeof(uint16);
2376 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2379 /* This should be an uncompressed point, but I do not have access to the spec. */
2380 dtls_int_to_uint8(p, 4);
2383 /* store the pointer to the x component of the pub key and make space */
2384 ephemeral_pub_x = p;
2385 p += DTLS_EC_KEY_SIZE;
2387 /* store the pointer to the y component of the pub key and make space */
2388 ephemeral_pub_y = p;
2389 p += DTLS_EC_KEY_SIZE;
2391 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2392 ephemeral_pub_x, ephemeral_pub_y,
2395 assert(p - buf <= sizeof(buf));
2397 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2400 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2404 dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2405 const unsigned char *psk_hint, size_t len)
2407 uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
2412 assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2413 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2414 /* should never happen */
2415 dtls_warn("psk identity hint is too long\n");
2416 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2419 dtls_int_to_uint16(p, len);
2420 p += sizeof(uint16);
2422 memcpy(p, psk_hint, len);
2425 assert(p - buf <= sizeof(buf));
2427 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2430 #endif /* DTLS_PSK */
2432 #if defined(DTLS_ECC) || defined(DTLS_X509)
2434 dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
2441 * Start message construction at beginning of buffer. */
2444 /* certificate_types */
2445 dtls_int_to_uint8(p, 1);
2449 dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
2452 /* supported_signature_algorithms */
2453 dtls_int_to_uint16(p, 2);
2454 p += sizeof(uint16);
2457 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2461 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2464 /* certificate_authoritiess */
2465 dtls_int_to_uint16(p, 0);
2466 p += sizeof(uint16);
2468 assert(p - buf <= sizeof(buf));
2470 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
2473 #endif /* DTLS_ECC */
2476 dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
2481 * Start message construction at beginning of buffer. */
2483 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
2488 dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
2495 res = dtls_send_server_hello(ctx, peer);
2498 dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2502 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2503 ecdh_anon = is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2504 ecdhe_psk = is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2506 #if defined(DTLS_ECC) || defined(DTLS_X509)
2508 res = dtls_send_server_key_exchange_ecdh(ctx, peer, NULL);
2511 dtls_debug("dtls_server_hello(with ECDH): cannot prepare Server Key Exchange record\n");
2516 const dtls_ecc_key_t *ecdsa_key;
2519 if (CALL(ctx, is_x509_active) == 0)
2520 res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
2522 #endif /* DTLS_X509 */
2523 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2526 dtls_debug("no ecdsa key to send\n");
2531 if (CALL(ctx, is_x509_active) == 0)
2532 res = dtls_send_certificate_x509(ctx, peer);
2534 #endif /* DTLS_X509 */
2535 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2538 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2542 res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2545 dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2549 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
2550 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx)))) {
2551 res = dtls_send_server_certificate_request(ctx, peer);
2553 dtls_debug("dtls_server_hello(with ECDSA): cannot prepare certificate Request record\n");
2558 #endif /* DTLS_ECC */
2559 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2560 else if(ecdhe_psk) {
2561 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2564 /* The identity hint is optional, therefore we ignore the result
2565 * and check psk only. */
2566 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2567 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2570 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2575 res = dtls_send_server_key_exchange_ecdhe_psk(ctx, peer, psk_hint, (size_t)psk_len);
2578 dtls_debug("dtls_server_hello(with ECDHE): cannot prepare Server Key Exchange record\n");
2583 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2585 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2586 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2589 /* The identity hint is optional, therefore we ignore the result
2590 * and check psk only. */
2591 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2592 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2595 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2600 res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2603 dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2608 #endif /* DTLS_PSK */
2610 res = dtls_send_server_hello_done(ctx, peer);
2613 dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2620 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
2623 return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2628 dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
2630 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2631 uint8 buf[DTLS_CKXEC_LENGTH + 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2633 uint8 buf[DTLS_CKXEC_LENGTH];
2634 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2635 uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2637 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2641 switch (handshake->cipher) {
2643 case TLS_PSK_WITH_AES_128_CCM_8: {
2646 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2651 dtls_crit("no psk identity set in kx\n");
2655 if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2656 dtls_warn("the psk identity is too long\n");
2657 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2660 dtls_int_to_uint16(p, len);
2661 p += sizeof(uint16);
2663 memcpy(p, client_id, len);
2668 #endif /* DTLS_PSK */
2669 #if defined(DTLS_ECC) || defined(DTLS_X509)
2670 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2671 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
2672 uint8 *ephemeral_pub_x;
2673 uint8 *ephemeral_pub_y;
2675 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2678 /* This should be an uncompressed point, but I do not have access to the spec. */
2679 dtls_int_to_uint8(p, 4);
2682 ephemeral_pub_x = p;
2683 p += DTLS_EC_KEY_SIZE;
2684 ephemeral_pub_y = p;
2685 p += DTLS_EC_KEY_SIZE;
2687 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2688 ephemeral_pub_x, ephemeral_pub_y,
2693 #endif /* DTLS_ECC */
2694 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2695 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
2697 uint8 *ephemeral_pub_x;
2698 uint8 *ephemeral_pub_y;
2700 /* Please see Session 2, RFC 5489.
2702 select (KeyExchangeAlgorithm) {
2703 // other cases for rsa, diffie_hellman, etc.
2704 case ec_diffie_hellman_psk:
2705 opaque psk_identity<0..2^16-1>;
2706 ClientECDiffieHellmanPublic public;
2708 } ClientKeyExchange;
2711 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2716 dtls_crit("no psk identity set in kx\n");
2720 if (psk_len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2721 dtls_warn("the psk identity is too long\n");
2722 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2725 dtls_int_to_uint16(p, psk_len);
2726 p += sizeof(uint16);
2728 memcpy(p, client_id, psk_len);
2731 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2734 dtls_int_to_uint8(p, 4);
2737 ephemeral_pub_x = p;
2738 p += DTLS_EC_KEY_SIZE;
2739 ephemeral_pub_y = p;
2740 p += DTLS_EC_KEY_SIZE;
2742 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2743 ephemeral_pub_x, ephemeral_pub_y,
2747 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2749 dtls_crit("cipher not supported\n");
2750 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2753 assert(p - buf <= sizeof(buf));
2755 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
2759 #if defined(DTLS_ECC) || defined(DTLS_X509)
2761 dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2762 const dtls_ecc_key_t *key)
2764 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2765 * 33 bytes long add space for that */
2766 uint8 buf[DTLS_CV_LENGTH + 2];
2768 uint32_t point_r[9];
2769 uint32_t point_s[9];
2770 dtls_hash_ctx hs_hash;
2771 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2773 /* ServerKeyExchange
2775 * Start message construction at beginning of buffer. */
2778 copy_hs_hash(peer, &hs_hash);
2780 dtls_hash_finalize(sha256hash, &hs_hash);
2782 /* sign the ephemeral and its paramaters */
2783 dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
2784 sha256hash, sizeof(sha256hash),
2787 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2789 assert(p - buf <= sizeof(buf));
2791 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
2794 #endif /* DTLS_ECC */
2797 dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
2798 const unsigned char *label, size_t labellen)
2801 uint8 hash[DTLS_HMAC_MAX];
2802 uint8 buf[DTLS_FIN_LENGTH];
2803 dtls_hash_ctx hs_hash;
2806 copy_hs_hash(peer, &hs_hash);
2808 length = dtls_hash_finalize(hash, &hs_hash);
2810 dtls_prf(peer->handshake_params->tmp.master_secret,
2811 DTLS_MASTER_SECRET_LENGTH,
2813 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2815 p, DTLS_FIN_LENGTH);
2817 dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2819 p += DTLS_FIN_LENGTH;
2821 assert(p - buf <= sizeof(buf));
2823 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2828 dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
2829 uint8 cookie[], size_t cookie_length) {
2830 uint8 buf[DTLS_CH_LENGTH_MAX];
2832 uint8_t cipher_size = 0;
2833 uint8_t extension_size = 0;
2839 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2842 switch(ctx->selected_cipher)
2844 case TLS_PSK_WITH_AES_128_CCM_8:
2845 psk = is_psk_supported(ctx);
2847 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2848 ecdsa = is_ecdsa_supported(ctx, 1);
2849 x509 = is_x509_supported(ctx, 1);
2851 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
2852 ecdh_anon = is_ecdh_anon_supported(ctx);
2854 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
2855 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2858 psk = is_psk_supported(ctx);
2859 ecdsa = is_ecdsa_supported(ctx, 1);
2860 ecdh_anon = is_ecdh_anon_supported(ctx);
2861 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2862 x509 = is_x509_supported(ctx, 1);
2866 cipher_size = 2 + ((ecdsa || x509) ? 2 : 0) + (psk ? 2 : 0) + (ecdh_anon ? 2 : 0) + (ecdhe_psk ? 2 : 0);
2868 /* Is extension needed? */
2869 extension_size = (ecdsa || x509 || ecdhe_psk || ecdh_anon) ? 2 : 0;
2870 /* Supported EC and Supported Point Formats */
2871 extension_size += (ecdsa || x509 || ecdhe_psk | ecdh_anon) ? ( 8 + 6) : 0;
2872 /* Supported Client and Server Cert Types */
2873 extension_size += (ecdsa || x509) ? ( 6 + 6) : 0;
2875 if (cipher_size == 0) {
2876 dtls_crit("no cipher callbacks implemented\n");
2879 dtls_int_to_uint16(p, DTLS_VERSION);
2880 p += sizeof(uint16);
2882 if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2883 dtls_warn("the cookie is too long\n");
2884 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2887 if (cookie_length == 0) {
2888 /* Set client random: First 4 bytes are the client's Unix timestamp,
2889 * followed by 28 bytes of generate random data. */
2891 dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2892 dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2893 DTLS_RANDOM_LENGTH - sizeof(uint32));
2895 /* we must use the same Client Random as for the previous request */
2896 memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2897 p += DTLS_RANDOM_LENGTH;
2899 /* session id (length 0) */
2900 dtls_int_to_uint8(p, 0);
2904 dtls_int_to_uint8(p, cookie_length);
2906 if (cookie_length != 0) {
2907 memcpy(p, cookie, cookie_length);
2911 /* add known cipher(s) */
2912 dtls_int_to_uint16(p, cipher_size - 2);
2913 p += sizeof(uint16);
2916 dtls_int_to_uint16(p, TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256);
2917 p += sizeof(uint16);
2920 dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
2921 p += sizeof(uint16);
2923 if (ecdsa || x509) {
2924 dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
2925 p += sizeof(uint16);
2928 dtls_int_to_uint16(p, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
2929 p += sizeof(uint16);
2932 /* compression method */
2933 dtls_int_to_uint8(p, 1);
2936 dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
2939 if (extension_size) {
2940 /* length of the extensions */
2941 dtls_int_to_uint16(p, extension_size - 2);
2942 p += sizeof(uint16);
2945 if (ecdsa || x509) {
2946 /* client certificate type extension */
2947 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2948 p += sizeof(uint16);
2950 /* length of this extension type */
2951 dtls_int_to_uint16(p, 2);
2952 p += sizeof(uint16);
2954 /* length of the list */
2955 dtls_int_to_uint8(p, 1);
2959 if (CALL(ctx, is_x509_active) == 0)
2960 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2962 #endif /* DTLS_X509 */
2963 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2967 /* server certificate type extension */
2968 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2969 p += sizeof(uint16);
2971 /* length of this extension type */
2972 dtls_int_to_uint16(p, 2);
2973 p += sizeof(uint16);
2975 /* length of the list */
2976 dtls_int_to_uint8(p, 1);
2980 if (CALL(ctx, is_x509_active) == 0)
2981 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2983 #endif /* DTLS_X509 */
2984 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2989 if (ecdsa || x509 || ecdhe_psk || ecdh_anon ) {
2990 /* elliptic_curves */
2991 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
2992 p += sizeof(uint16);
2994 /* length of this extension type */
2995 dtls_int_to_uint16(p, 4);
2996 p += sizeof(uint16);
2998 /* length of the list */
2999 dtls_int_to_uint16(p, 2);
3000 p += sizeof(uint16);
3002 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
3003 p += sizeof(uint16);
3005 /* ec_point_formats */
3006 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
3007 p += sizeof(uint16);
3009 /* length of this extension type */
3010 dtls_int_to_uint16(p, 2);
3011 p += sizeof(uint16);
3013 /* number of supported formats */
3014 dtls_int_to_uint8(p, 1);
3017 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
3021 assert(p - buf <= sizeof(buf));
3023 if (cookie_length != 0)
3024 clear_hs_hash(peer);
3026 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3027 DTLS_HT_CLIENT_HELLO,
3028 buf, p - buf, cookie_length != 0);
3032 check_server_hello(dtls_context_t *ctx,
3034 uint8 *data, size_t data_length)
3036 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3038 /* This function is called when we expect a ServerHello (i.e. we
3039 * have sent a ClientHello). We might instead receive a HelloVerify
3040 * request containing a cookie. If so, we must repeat the
3041 * ClientHello with the given Cookie.
3043 if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
3044 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3046 update_hs_hash(peer, data, data_length);
3048 /* FIXME: check data_length before accessing fields */
3050 /* Get the server's random data and store selected cipher suite
3051 * and compression method (like dtls_update_parameters().
3052 * Then calculate master secret and wait for ServerHelloDone. When received,
3053 * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
3055 /* check server version */
3056 data += DTLS_HS_LENGTH;
3057 data_length -= DTLS_HS_LENGTH;
3059 if (dtls_uint16_to_int(data) != DTLS_VERSION) {
3060 dtls_alert("unknown DTLS version\n");
3061 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
3064 data += sizeof(uint16); /* skip version field */
3065 data_length -= sizeof(uint16);
3067 /* store server random data */
3068 memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
3069 /* skip server random */
3070 data += DTLS_RANDOM_LENGTH;
3071 data_length -= DTLS_RANDOM_LENGTH;
3073 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
3075 /* Check cipher suite. As we offer all we have, it is sufficient
3076 * to check if the cipher suite selected by the server is in our
3077 * list of known cipher suites. Subsets are not supported. */
3078 handshake->cipher = dtls_uint16_to_int(data);
3079 if (!known_cipher(ctx, handshake->cipher, 1)) {
3080 dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
3082 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3084 data += sizeof(uint16);
3085 data_length -= sizeof(uint16);
3087 /* Check if NULL compression was selected. We do not know any other. */
3088 if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
3089 dtls_alert("unsupported compression method 0x%02x\n", data[0]);
3090 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3092 data += sizeof(uint8);
3093 data_length -= sizeof(uint8);
3095 return dtls_check_tls_extension(peer, data, data_length, 0);
3098 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3102 check_server_hello_verify_request(dtls_context_t *ctx,
3104 uint8 *data, size_t data_length)
3106 dtls_hello_verify_t *hv;
3109 if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
3110 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3112 hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
3114 res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
3117 dtls_warn("cannot send ClientHello\n");
3125 check_peer_certificate(dtls_context_t *ctx,
3127 uint8 *data, size_t data_length)
3130 dtls_handshake_parameters_t *config = peer->handshake_params;
3132 update_hs_hash(peer, data, data_length);
3134 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3136 data += DTLS_HS_LENGTH;
3138 if (dtls_uint24_to_int(data) != DTLS_EC_SUBJECTPUBLICKEY_SIZE) {
3139 dtls_alert("expect length of %d bytes for certificate\n",
3140 DTLS_EC_SUBJECTPUBLICKEY_SIZE);
3141 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3143 data += sizeof(uint24);
3145 if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
3146 dtls_alert("got an unexpected Subject public key format\n");
3147 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3149 data += sizeof(cert_asn1_header);
3151 memcpy(config->keyx.ecc.other_pub_x, data,
3152 sizeof(config->keyx.ecc.other_pub_x));
3153 data += sizeof(config->keyx.ecc.other_pub_x);
3155 memcpy(config->keyx.ecc.other_pub_y, data,
3156 sizeof(config->keyx.ecc.other_pub_y));
3157 data += sizeof(config->keyx.ecc.other_pub_y);
3159 err = CALL(ctx, verify_ecdsa_key, &peer->session,
3160 config->keyx.ecc.other_pub_x,
3161 config->keyx.ecc.other_pub_y,
3162 sizeof(config->keyx.ecc.other_pub_x));
3164 dtls_warn("The certificate was not accepted\n");
3170 #endif /* DTLS_ECC */
3174 check_peer_certificate_x509(dtls_context_t *ctx,
3176 uint8 *data, size_t data_length)
3179 dtls_handshake_parameters_t *config = peer->handshake_params;
3182 dtls_info("\n check_peer_certificate_x509\n");
3183 update_hs_hash(peer, data, data_length);
3185 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3187 data += DTLS_HS_LENGTH;
3189 cert_length = dtls_uint24_to_int(data);
3190 data += sizeof(uint24);
3192 ret = CALL(ctx, verify_x509_cert, &peer->session, data, cert_length,
3193 config->keyx.ecc.other_pub_x, sizeof(config->keyx.ecc.other_pub_x),
3194 config->keyx.ecc.other_pub_y, sizeof(config->keyx.ecc.other_pub_y));
3196 dtls_warn("The certificate was not accepted\n");
3202 #endif /* DTLS_X509 */
3204 #if defined(DTLS_X509) || defined(DTLS_ECC)
3206 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
3208 uint8 *data, size_t data_length)
3210 dtls_handshake_parameters_t *config = peer->handshake_params;
3212 unsigned char *result_r;
3213 unsigned char *result_s;
3214 unsigned char *key_params;
3216 update_hs_hash(peer, data, data_length);
3218 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3220 data += DTLS_HS_LENGTH;
3222 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
3223 dtls_alert("the packet length does not match the expected\n");
3224 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3228 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3229 dtls_alert("Only named curves supported\n");
3230 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3232 data += sizeof(uint8);
3233 data_length -= sizeof(uint8);
3235 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3236 dtls_alert("secp256r1 supported\n");
3237 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3239 data += sizeof(uint16);
3240 data_length -= sizeof(uint16);
3242 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3243 dtls_alert("expected 65 bytes long public point\n");
3244 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3246 data += sizeof(uint8);
3247 data_length -= sizeof(uint8);
3249 if (dtls_uint8_to_int(data) != 4) {
3250 dtls_alert("expected uncompressed public point\n");
3251 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3253 data += sizeof(uint8);
3254 data_length -= sizeof(uint8);
3256 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3257 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3258 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3260 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3261 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3262 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3264 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
3271 ret = dtls_ecdsa_verify_sig(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
3272 sizeof(config->keyx.ecc.other_pub_x),
3273 config->tmp.random.client, DTLS_RANDOM_LENGTH,
3274 config->tmp.random.server, DTLS_RANDOM_LENGTH,
3276 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
3277 result_r, result_s);
3280 dtls_alert("wrong signature\n");
3281 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3287 check_server_key_exchange_ecdh(dtls_context_t *ctx,
3289 uint8 *data, size_t data_length)
3291 dtls_handshake_parameters_t *config = peer->handshake_params;
3293 update_hs_hash(peer, data, data_length);
3295 assert(is_tls_ecdh_anon_with_aes_128_cbc_sha_256(config->cipher));
3297 data += DTLS_HS_LENGTH;
3299 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3300 dtls_alert("the packet length does not match the expected\n");
3301 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3304 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3305 dtls_alert("Only named curves supported\n");
3306 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3308 data += sizeof(uint8);
3309 data_length -= sizeof(uint8);
3311 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3312 dtls_alert("secp256r1 supported\n");
3313 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3315 data += sizeof(uint16);
3316 data_length -= sizeof(uint16);
3318 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3319 dtls_alert("expected 65 bytes long public point\n");
3320 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3322 data += sizeof(uint8);
3323 data_length -= sizeof(uint8);
3325 if (dtls_uint8_to_int(data) != 4) {
3326 dtls_alert("expected uncompressed public point\n");
3327 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3329 data += sizeof(uint8);
3330 data_length -= sizeof(uint8);
3332 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3333 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3334 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3336 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3337 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3338 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3342 #endif /* DTLS_ECC */
3343 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3344 check_server_key_exchange_ecdhe_psk(dtls_context_t *ctx,
3346 uint8 *data, size_t data_length)
3348 dtls_handshake_parameters_t *config = peer->handshake_params;
3349 uint16_t psk_len = 0;
3351 /* ServerKeyExchange
3352 * Please see Session 2, RFC 5489.
3355 select (KeyExchangeAlgorithm) {
3356 //other cases for rsa, diffie_hellman, etc.
3357 case ec_diffie_hellman_psk: // NEW
3358 opaque psk_identity_hint<0..2^16-1>;
3359 ServerECDHParams params;
3361 } ServerKeyExchange; */
3363 update_hs_hash(peer, data, data_length);
3365 assert(is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(config->cipher));
3367 data += DTLS_HS_LENGTH;
3369 psk_len = dtls_uint16_to_int(data);
3370 data += sizeof(uint16);
3372 if (psk_len != data_length - DTLS_HS_LENGTH - DTLS_SKEXEC_ECDH_ANON_LENGTH - sizeof(uint16)) {
3373 dtls_warn("the length of the server identity hint is worng\n");
3374 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3377 if (psk_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3378 dtls_warn("please use a smaller server identity hint\n");
3379 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3382 // store the psk_identity_hint in config->keyx.psk for later use
3383 config->keyx.psk.id_length = psk_len;
3384 memcpy(config->keyx.psk.identity, data, psk_len);
3387 data_length -= psk_len;
3389 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3390 dtls_alert("the packet length does not match the expected\n");
3391 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3394 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3395 dtls_alert("Only named curves supported\n");
3396 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3398 data += sizeof(uint8);
3399 data_length -= sizeof(uint8);
3401 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3402 dtls_alert("secp256r1 supported\n");
3403 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3405 data += sizeof(uint16);
3406 data_length -= sizeof(uint16);
3408 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3409 dtls_alert("expected 65 bytes long public point\n");
3410 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3412 data += sizeof(uint8);
3413 data_length -= sizeof(uint8);
3415 if (dtls_uint8_to_int(data) != 4) {
3416 dtls_alert("expected uncompressed public point\n");
3417 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3419 data += sizeof(uint8);
3420 data_length -= sizeof(uint8);
3422 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3423 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3424 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3426 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3427 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3428 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3432 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
3436 check_server_key_exchange_psk(dtls_context_t *ctx,
3438 uint8 *data, size_t data_length)
3440 dtls_handshake_parameters_t *config = peer->handshake_params;
3443 update_hs_hash(peer, data, data_length);
3445 assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
3447 data += DTLS_HS_LENGTH;
3449 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
3450 dtls_alert("the packet length does not match the expected\n");
3451 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3454 len = dtls_uint16_to_int(data);
3455 data += sizeof(uint16);
3457 if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
3458 dtls_warn("the length of the server identity hint is worng\n");
3459 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3462 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3463 dtls_warn("please use a smaller server identity hint\n");
3464 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3467 /* store the psk_identity_hint in config->keyx.psk for later use */
3468 config->keyx.psk.id_length = len;
3469 memcpy(config->keyx.psk.identity, data, len);
3472 #endif /* DTLS_PSK */
3475 check_certificate_request(dtls_context_t *ctx,
3477 uint8 *data, size_t data_length)
3484 update_hs_hash(peer, data, data_length);
3486 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
3488 data += DTLS_HS_LENGTH;
3490 if (data_length < DTLS_HS_LENGTH + 5) {
3491 dtls_alert("the packet length does not match the expected\n");
3492 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3495 i = dtls_uint8_to_int(data);
3496 data += sizeof(uint8);
3497 if (i + 1 > data_length) {
3498 dtls_alert("the cerfificate types are too long\n");
3499 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3503 for (; i > 0 ; i -= sizeof(uint8)) {
3504 if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
3506 auth_alg = dtls_uint8_to_int(data);
3507 data += sizeof(uint8);
3510 if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
3511 dtls_alert("the request authentication algorithm is not supproted\n");
3512 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3515 i = dtls_uint16_to_int(data);
3516 data += sizeof(uint16);
3517 if (i + 1 > data_length) {
3518 dtls_alert("the signature and hash algorithm list is too long\n");
3519 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3524 for (; i > 0 ; i -= sizeof(uint16)) {
3525 int current_hash_alg;
3526 int current_sig_alg;
3528 current_hash_alg = dtls_uint8_to_int(data);
3529 data += sizeof(uint8);
3530 current_sig_alg = dtls_uint8_to_int(data);
3531 data += sizeof(uint8);
3533 if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 &&
3534 current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
3535 hash_alg = current_hash_alg;
3536 sig_alg = current_sig_alg;
3540 if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
3541 sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
3542 dtls_alert("no supported hash and signature algorithem\n");
3543 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3546 /* common names are ignored */
3548 peer->handshake_params->do_client_auth = 1;
3553 check_server_hellodone(dtls_context_t *ctx,
3555 uint8 *data, size_t data_length)
3559 const dtls_ecc_key_t *ecdsa_key;
3561 unsigned char *cert;
3563 #endif /* DTLS_X509 */
3564 #endif /* DTLS_ECC */
3566 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3568 /* calculate master key, send CCS */
3570 update_hs_hash(peer, data, data_length);
3572 #if defined(DTLS_ECC) || defined(DTLS_X509)
3573 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3575 if (CALL(ctx, is_x509_active) == 0)
3576 res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
3578 #endif /* DTLS_X509 */
3579 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
3581 dtls_crit("no ecdsa key to use\n");
3586 if (CALL(ctx, is_x509_active) == 0)
3587 res = dtls_send_certificate_x509(ctx, peer);
3589 #endif /* DTLS_X509 */
3590 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
3593 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3597 #endif /* DTLS_ECC */
3599 /* send ClientKeyExchange */
3600 res = dtls_send_client_key_exchange(ctx, peer);
3603 dtls_debug("cannot send KeyExchange message\n");
3608 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3609 res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
3612 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3616 #endif /* DTLS_ECC */
3618 res = calculate_key_block(ctx, handshake, peer,
3619 &peer->session, peer->role);
3624 res = dtls_send_ccs(ctx, peer);
3626 dtls_debug("cannot send CCS message\n");
3630 /* and switch cipher suite */
3631 dtls_security_params_switch(peer);
3633 /* Client Finished */
3634 return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
3638 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
3641 dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
3642 dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
3645 *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
3646 clen = length - sizeof(dtls_record_header_t);
3649 dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
3653 if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
3654 /* no cipher suite selected */
3656 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
3657 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
3659 unsigned char nonce[DTLS_CBC_IV_LENGTH];
3661 if (clen < (DTLS_CBC_IV_LENGTH + DTLS_HMAC_DIGEST_SIZE)) /* need at least IV and MAC */
3664 memcpy(nonce, *cleartext , DTLS_CBC_IV_LENGTH);
3665 clen -= DTLS_CBC_IV_LENGTH;
3666 *cleartext += DTLS_CBC_IV_LENGTH ;
3668 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3669 dtls_kb_remote_write_key(security, peer->role),
3670 dtls_kb_key_size(security, peer->role),
3671 dtls_kb_remote_mac_secret(security, peer->role),
3672 dtls_kb_mac_secret_size(security->cipher),
3676 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
3678 * length of additional_data for the AEAD cipher which consists of
3679 * seq_num(2+6) + type(1) + version(2) + length(2)
3681 #define A_DATA_LEN 13
3682 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
3683 unsigned char A_DATA[A_DATA_LEN];
3685 if (clen < 16) /* need at least IV and MAC */
3688 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
3689 memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
3690 dtls_kb_iv_size(security->cipher));
3692 /* read epoch and seq_num from message */
3693 memcpy(nonce + dtls_kb_iv_size(security->cipher), *cleartext, 8);
3697 dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
3698 dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
3699 dtls_kb_key_size(security, peer->role));
3700 dtls_debug_dump("ciphertext", *cleartext, clen);
3702 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
3704 * additional_data = seq_num + TLSCompressed.type +
3705 * TLSCompressed.version + TLSCompressed.length;
3707 memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
3708 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
3709 dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
3711 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3712 dtls_kb_remote_write_key(security, peer->role),
3713 dtls_kb_key_size(security, peer->role),
3714 dtls_kb_remote_mac_secret(security, peer->role),
3715 dtls_kb_mac_secret_size(security->cipher),
3721 dtls_warn("decryption failed\n");
3724 dtls_debug("decrypt_verify(): found %i bytes cleartext\n", clen);
3726 dtls_security_params_free_other(peer);
3727 dtls_debug_dump("cleartext", *cleartext, clen);
3734 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
3736 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3737 DTLS_HT_HELLO_REQUEST,
3742 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
3744 dtls_peer_t *peer = NULL;
3747 peer = dtls_get_peer(ctx, dst);
3752 if (peer->state != DTLS_STATE_CONNECTED)
3755 peer->handshake_params = dtls_handshake_new();
3756 if (!peer->handshake_params)
3759 peer->handshake_params->hs_state.mseq_r = 0;
3760 peer->handshake_params->hs_state.mseq_s = 0;
3762 if (peer->role == DTLS_CLIENT) {
3763 /* send ClientHello with empty Cookie */
3764 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3766 dtls_warn("cannot send ClientHello\n");
3768 peer->state = DTLS_STATE_CLIENTHELLO;
3770 } else if (peer->role == DTLS_SERVER) {
3771 return dtls_send_hello_request(ctx, peer);
3778 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3779 const dtls_peer_type role, const dtls_state_t state,
3780 uint8 *data, size_t data_length) {
3784 /* This will clear the retransmission buffer if we get an expected
3785 * handshake message. We have to make sure that no handshake message
3786 * should get expected when we still should retransmit something, when
3787 * we do everything accordingly to the DTLS 1.2 standard this should
3788 * not be a problem. */
3790 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3791 if (state == DTLS_STATE_WAIT_CHANGECIPHERSPEC && hs_header->msg_type == DTLS_HT_FINISHED) {
3794 dtls_clear_retransmission(ctx, peer);
3797 /* The following switch construct handles the given message with
3798 * respect to the current internal state for this peer. In case of
3799 * error, it is left with return 0. */
3801 dtls_debug("handle handshake packet of type: %s (%i)\n",
3802 dtls_handshake_type_to_name(data[0]), data[0]);
3805 /************************************************************************
3807 ************************************************************************/
3808 case DTLS_HT_HELLO_VERIFY_REQUEST:
3810 if (state != DTLS_STATE_CLIENTHELLO) {
3811 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3814 err = check_server_hello_verify_request(ctx, peer, data, data_length);
3816 dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3821 case DTLS_HT_SERVER_HELLO:
3823 if (state != DTLS_STATE_CLIENTHELLO) {
3824 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3827 err = check_server_hello(ctx, peer, data, data_length);
3829 dtls_warn("error in check_server_hello err: %i\n", err);
3832 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3833 peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE; //ecdsa
3834 else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher) ||
3835 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher))
3836 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE; //ecdh
3838 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE; //psk
3839 /* update_hs_hash(peer, data, data_length); */
3843 #if defined(DTLS_ECC) || defined(DTLS_X509)
3844 case DTLS_HT_CERTIFICATE:
3846 if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3847 (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3848 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3851 if (CALL(ctx, is_x509_active) == 0)
3852 err = check_peer_certificate_x509(ctx, peer, data, data_length);
3854 #endif /* DTLS_X509 */
3855 err = check_peer_certificate(ctx, peer, data, data_length);
3857 dtls_warn("error in check_peer_certificate err: %i\n", err);
3860 if (role == DTLS_CLIENT) {
3861 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3862 } else if (role == DTLS_SERVER){
3863 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3865 /* update_hs_hash(peer, data, data_length); */
3868 #endif /* DTLS_ECC */
3870 case DTLS_HT_SERVER_KEY_EXCHANGE:
3872 #if defined(DTLS_ECC) || defined(DTLS_X509)
3873 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3874 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3875 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3877 err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3880 if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3881 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3882 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3884 err = check_server_key_exchange_ecdh(ctx, peer, data, data_length);
3886 #endif /* DTLS_ECC */
3888 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3889 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3890 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3891 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3893 err = check_server_key_exchange_ecdhe_psk(ctx, peer, data, data_length);
3895 #endif defined(DTLS_PSK) && defined(DTLS_ECC)
3898 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3899 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3900 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3902 err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3904 #endif /* DTLS_PSK */
3907 dtls_warn("error in check_server_key_exchange err: %i\n", err);
3910 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3911 /* update_hs_hash(peer, data, data_length); */
3915 case DTLS_HT_SERVER_HELLO_DONE:
3917 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3918 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3921 err = check_server_hellodone(ctx, peer, data, data_length);
3923 dtls_warn("error in check_server_hellodone err: %i\n", err);
3926 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3927 /* update_hs_hash(peer, data, data_length); */
3931 case DTLS_HT_CERTIFICATE_REQUEST:
3933 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3934 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3937 err = check_certificate_request(ctx, peer, data, data_length);
3939 dtls_warn("error in check_certificate_request err: %i\n", err);
3945 case DTLS_HT_FINISHED:
3946 /* expect a Finished message from server */
3948 if (state != DTLS_STATE_WAIT_FINISHED) {
3949 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3952 err = check_finished(ctx, peer, data, data_length);
3954 dtls_warn("error in check_finished err: %i\n", err);
3957 if (role == DTLS_SERVER) {
3958 /* send ServerFinished */
3959 update_hs_hash(peer, data, data_length);
3961 /* send change cipher spec message and switch to new configuration */
3962 err = dtls_send_ccs(ctx, peer);
3964 dtls_warn("cannot send CCS message\n");
3968 dtls_security_params_switch(peer);
3970 err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3972 dtls_warn("sending server Finished failed\n");
3976 dtls_handshake_free(peer->handshake_params);
3977 peer->handshake_params = NULL;
3978 dtls_debug("Handshake complete\n");
3980 peer->state = DTLS_STATE_CONNECTED;
3982 /* return here to not increase the message receive counter */
3985 /************************************************************************
3987 ************************************************************************/
3989 case DTLS_HT_CLIENT_KEY_EXCHANGE:
3990 /* handle ClientHello, update msg and msglen and goto next if not finished */
3992 if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3993 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3996 err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3998 dtls_warn("error in check_client_keyexchange err: %i\n", err);
4001 update_hs_hash(peer, data, data_length);
4003 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
4004 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
4005 peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY; //ecdsa
4007 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC; //psk || ecdh_anon
4010 #if defined(DTLS_ECC) || defined(DTLS_X509)
4011 case DTLS_HT_CERTIFICATE_VERIFY:
4013 if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
4014 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4017 err = check_client_certificate_verify(ctx, peer, data, data_length);
4019 dtls_warn("error in check_client_certificate_verify err: %i\n", err);
4023 update_hs_hash(peer, data, data_length);
4024 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
4026 #endif /* DTLS_ECC */
4028 case DTLS_HT_CLIENT_HELLO:
4030 if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
4031 (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
4032 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4035 /* When no DTLS state exists for this peer, we only allow a
4036 Client Hello message with
4038 a) a valid cookie, or
4041 Anything else will be rejected. Fragementation is not allowed
4042 here as it would require peer state as well.
4044 err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
4046 dtls_warn("error in dtls_verify_peer err: %i\n", err);
4051 dtls_debug("server hello verify was sent\n");
4055 /* At this point, we have a good relationship with this peer. This
4056 * state is left for re-negotiation of key material. */
4057 /* As per RFC 6347 - section 4.2.8 if this is an attempt to
4058 * rehandshake, we can delete the existing key material
4059 * as the client has demonstrated reachibility by completing
4060 * the cookie exchange */
4061 if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
4062 dtls_debug("removing the peer\n");
4063 #ifndef WITH_CONTIKI
4064 HASH_DEL_PEER(ctx->peers, peer);
4065 #else /* WITH_CONTIKI */
4066 list_remove(ctx->peers, peer);
4067 #endif /* WITH_CONTIKI */
4069 dtls_free_peer(peer);
4073 dtls_debug("creating new peer\n");
4074 dtls_security_parameters_t *security;
4076 /* msg contains a Client Hello with a valid cookie, so we can
4077 * safely create the server state machine and continue with
4079 peer = dtls_new_peer(session);
4081 dtls_alert("cannot create peer\n");
4082 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4084 peer->role = DTLS_SERVER;
4086 /* Initialize record sequence number to 1 for new peers. The first
4087 * record with sequence number 0 is a stateless Hello Verify Request.
4089 security = dtls_security_params(peer);
4091 dtls_add_peer(ctx, peer);
4093 if (peer && !peer->handshake_params) {
4094 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4096 peer->handshake_params = dtls_handshake_new();
4097 if (!peer->handshake_params)
4098 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4100 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4101 peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
4102 peer->handshake_params->hs_state.mseq_s = 1;
4105 clear_hs_hash(peer);
4107 /* First negotiation step: check for PSK
4109 * Note that we already have checked that msg is a Handshake
4110 * message containing a ClientHello. dtls_get_cipher() therefore
4111 * does not check again.
4113 err = dtls_update_parameters(ctx, peer, data, data_length);
4115 dtls_warn("error updating security parameters\n");
4119 /* update finish MAC */
4120 update_hs_hash(peer, data, data_length);
4122 err = dtls_send_server_hello_msgs(ctx, peer);
4126 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
4127 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
4128 peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE; //ecdhe
4130 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE; //psk, ecdh_anon
4132 /* after sending the ServerHelloDone, we expect the
4133 * ClientKeyExchange (possibly containing the PSK id),
4134 * followed by a ChangeCipherSpec and an encrypted Finished.
4139 case DTLS_HT_HELLO_REQUEST:
4141 if (state != DTLS_STATE_CONNECTED) {
4142 /* we should just ignore such packets when in handshake */
4146 if (peer && !peer->handshake_params) {
4147 peer->handshake_params = dtls_handshake_new();
4148 if (!peer->handshake_params)
4149 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4151 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4152 peer->handshake_params->hs_state.mseq_r = 0;
4153 peer->handshake_params->hs_state.mseq_s = 0;
4156 /* send ClientHello with empty Cookie */
4157 err = dtls_send_client_hello(ctx, peer, NULL, 0);
4159 dtls_warn("cannot send ClientHello\n");
4162 peer->state = DTLS_STATE_CLIENTHELLO;
4166 dtls_crit("unhandled message %d\n", data[0]);
4167 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4170 if (peer && peer->handshake_params && err >= 0) {
4171 peer->handshake_params->hs_state.mseq_r++;
4178 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
4179 const dtls_peer_type role, const dtls_state_t state,
4180 uint8 *data, size_t data_length)
4182 dtls_handshake_header_t *hs_header;
4185 if (data_length < DTLS_HS_LENGTH) {
4186 dtls_warn("handshake message too short\n");
4187 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4189 hs_header = DTLS_HANDSHAKE_HEADER(data);
4191 dtls_debug("received handshake packet of type: %s (%i)\n",
4192 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4194 if (!peer || !peer->handshake_params) {
4195 /* This is the initial ClientHello */
4196 if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
4197 dtls_warn("If there is no peer only ClientHello is allowed\n");
4198 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
4201 /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
4202 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
4203 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
4204 return handle_handshake_msg(ctx, peer, session, role, state, data,
4207 dtls_warn("ignore unexpected handshake message\n");
4211 /* This is a ClientHello send when doing retransmission */
4212 if (peer && hs_header->msg_type == DTLS_HT_CLIENT_HELLO &&
4213 dtls_uint16_to_int(hs_header->message_seq) == 0) {
4214 res = dtls_verify_peer(ctx, peer, session, state, data, data_length);
4216 dtls_warn("error in dtls_verify_peer err: %i\n", res);
4219 dtls_debug("server hello verify was sent\n");
4224 if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
4225 dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
4226 peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
4228 } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
4229 /* A packet in between is missing, buffer this packet. */
4232 /* TODO: only add packet that are not too new. */
4233 if (data_length > DTLS_MAX_BUF) {
4234 dtls_warn("the packet is too big to buffer for reoder\n");
4238 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4240 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4241 if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
4242 dtls_warn("a packet with this sequence number is already stored\n");
4245 node = netq_next(node);
4248 n = netq_node_new(data_length);
4250 dtls_warn("no space in reoder buffer\n");
4255 n->length = data_length;
4256 memcpy(n->data, data, data_length);
4258 if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
4259 dtls_warn("cannot add packet to reoder buffer\n");
4262 dtls_info("Added packet for reordering\n");
4264 } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4265 /* Found the expected packet, use this and all the buffered packet */
4268 res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
4272 /* We do not know in which order the packet are in the list just search the list for every packet. */
4273 while (next && peer->handshake_params) {
4275 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4277 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4279 if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4280 netq_remove(peer->handshake_params->reorder_queue, node);
4282 res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
4289 node = netq_next(node);
4300 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
4301 uint8 *record_header, uint8 *data, size_t data_length)
4305 /* A CCS message is handled after a KeyExchange message was
4306 * received from the client. When security parameters have been
4307 * updated successfully and a ChangeCipherSpec message was sent
4308 * by ourself, the security context is switched and the record
4309 * sequence number is reset. */
4311 if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
4312 dtls_warn("expected ChangeCipherSpec during handshake\n");
4316 if (data_length < 1 || data[0] != 1)
4317 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4319 dtls_handshake_parameters_t *handshake = peer->handshake_params;
4320 /* Just change the cipher when we are on the same epoch */
4321 if (peer->role == DTLS_SERVER) {
4322 err = calculate_key_block(ctx, handshake, peer,
4323 &peer->session, peer->role);
4329 peer->state = DTLS_STATE_WAIT_FINISHED;
4335 * Handles incoming Alert messages. This function returns \c 1 if the
4336 * connection should be closed and the peer is to be invalidated.
4339 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
4340 uint8 *record_header, uint8 *data, size_t data_length) {
4341 int free_peer = 0; /* indicates whether to free peer */
4343 if (data_length < 2)
4344 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4346 dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
4349 dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
4353 /* The peer object is invalidated for FATAL alerts and close
4354 * notifies. This is done in two steps.: First, remove the object
4355 * from our list of peers. After that, the event handler callback is
4356 * invoked with the still existing peer object. Finally, the storage
4357 * used by peer is released.
4359 if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
4360 dtls_alert("%d invalidate peer\n", data[1]);
4362 #ifndef WITH_CONTIKI
4363 HASH_DEL_PEER(ctx->peers, peer);
4364 #else /* WITH_CONTIKI */
4365 list_remove(ctx->peers, peer);
4368 PRINTF("removed peer [");
4369 PRINT6ADDR(&peer->session.addr);
4370 PRINTF("]:%d\n", uip_ntohs(peer->session.port));
4372 #endif /* WITH_CONTIKI */
4378 (void)CALL(ctx, event, &peer->session,
4379 (dtls_alert_level_t)data[0], (unsigned short)data[1]);
4381 case DTLS_ALERT_CLOSE_NOTIFY:
4382 /* If state is DTLS_STATE_CLOSING, we have already sent a
4383 * close_notify so, do not send that again. */
4384 if (peer->state != DTLS_STATE_CLOSING) {
4385 peer->state = DTLS_STATE_CLOSING;
4386 dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
4388 peer->state = DTLS_STATE_CLOSED;
4395 dtls_clear_retransmission(ctx, peer);
4396 dtls_destroy_peer(ctx, peer, 0);
4402 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
4403 session_t *session, int err)
4408 if (err < -(1 << 8) && err > -(3 << 8)) {
4409 level = ((-err) & 0xff00) >> 8;
4410 desc = (-err) & 0xff;
4412 peer = dtls_get_peer(ctx, session);
4415 peer->state = DTLS_STATE_CLOSING;
4416 return dtls_send_alert(ctx, peer, level, desc);
4418 } else if (err == -1) {
4420 peer = dtls_get_peer(ctx, session);
4423 peer->state = DTLS_STATE_CLOSING;
4424 return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
4431 * Handles incoming data as DTLS message from given peer.
4434 dtls_handle_message(dtls_context_t *ctx,
4436 uint8 *msg, int msglen) {
4437 dtls_peer_t *peer = NULL;
4438 unsigned int rlen; /* record length */
4439 uint8 *data; /* (decrypted) payload */
4440 int data_length; /* length of decrypted payload
4441 (without MAC and padding) */
4444 /* check if we have DTLS state for addr/port/ifindex */
4445 peer = dtls_get_peer(ctx, session);
4448 dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
4449 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
4451 dtls_debug("dtls_handle_message: FOUND PEER\n");
4454 while ((rlen = is_record(msg,msglen))) {
4455 dtls_peer_type role;
4458 dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
4460 data_length = decrypt_verify(peer, msg, rlen, &data);
4461 if (data_length < 0) {
4462 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4463 data = msg + DTLS_RH_LENGTH;
4464 data_length = rlen - DTLS_RH_LENGTH;
4465 state = DTLS_STATE_WAIT_CLIENTHELLO;
4468 if (DTLS_CT_HANDSHAKE == msg[0] && DTLS_STATE_WAIT_FINISHED == peer->state) {
4469 int err = dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
4470 dtls_info("decrypt_verify() failed\n");
4472 dtls_alert_send_from_err(ctx, peer, &peer->session, err);
4474 (void)CALL(ctx, event, &peer->session,
4475 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4476 peer->state = DTLS_STATE_CLOSED;
4477 /* dtls_clear_retransmission(ctx, peer); */
4478 dtls_destroy_peer(ctx, peer, 1);
4481 data = msg + DTLS_RH_LENGTH;
4482 data_length = rlen - DTLS_RH_LENGTH;
4484 state = peer->state;
4489 state = peer->state;
4492 /* is_record() ensures that msg contains at least a record header */
4493 data = msg + DTLS_RH_LENGTH;
4494 data_length = rlen - DTLS_RH_LENGTH;
4495 state = DTLS_STATE_WAIT_CLIENTHELLO;
4499 dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
4500 dtls_debug_hexdump("receive unencrypted", data, data_length);
4502 /* Handle received record according to the first byte of the
4503 * message, i.e. the subprotocol. We currently do not support
4504 * combining multiple fragments of one type into a single
4509 case DTLS_CT_CHANGE_CIPHER_SPEC:
4510 err = handle_ccs(ctx, peer, msg, data, data_length);
4512 dtls_warn("error while handling ChangeCipherSpec message\n");
4513 dtls_alert_send_from_err(ctx, peer, session, err);
4515 (void)CALL(ctx, event, &peer->session,
4516 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4518 /* invalidate peer */
4519 dtls_clear_retransmission(ctx, peer);
4520 dtls_destroy_peer(ctx, peer, 1);
4529 dtls_clear_retransmission(ctx, peer);
4531 err = handle_alert(ctx, peer, msg, data, data_length);
4532 if (err < 0 || err == 1) {
4533 dtls_warn("received alert, peer has been invalidated\n");
4534 /* handle alert has invalidated peer */
4536 return err < 0 ?err:-1;
4540 case DTLS_CT_HANDSHAKE:
4542 /* Handshake messages other than Finish must use the current
4543 * epoch, Finish has epoch + 1. */
4547 /* Handle the client's last flight retransmission when the server's
4548 * Finished message is lost. This avoids deadlock. */
4549 if (DTLS_SERVER == role && DTLS_STATE_CONNECTED == state) {
4550 dtls_start_retransmission(ctx, peer);
4553 uint16_t expected_epoch = dtls_security_params(peer)->epoch;
4554 uint16_t msg_epoch =
4555 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
4557 /* The new security parameters must be used for all messages
4558 * that are sent after the ChangeCipherSpec message. This
4559 * means that the client's Finished message uses epoch + 1
4560 * while the server is still in the old epoch.
4562 if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
4566 if (expected_epoch != msg_epoch) {
4567 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4568 state = DTLS_STATE_WAIT_CLIENTHELLO;
4571 dtls_warn("Wrong epoch, expected %i, got: %i\n",
4572 expected_epoch, msg_epoch);
4578 err = handle_handshake(ctx, peer, session, role, state, data, data_length);
4580 dtls_warn("error while handling handshake packet\n");
4581 dtls_alert_send_from_err(ctx, peer, session, err);
4584 (void)CALL(ctx, event, &peer->session,
4585 DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
4586 dtls_destroy_peer(ctx, peer, 1);
4591 if (peer && peer->state == DTLS_STATE_CONNECTED) {
4592 /* stop retransmissions */
4593 dtls_stop_retransmission(ctx, peer);
4594 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
4598 case DTLS_CT_APPLICATION_DATA:
4599 dtls_info("** application data:\n");
4601 dtls_warn("no peer available, send an alert\n");
4602 // TODO: should we send a alert here?
4605 dtls_clear_retransmission(ctx, peer);
4606 CALL(ctx, read, &peer->session, data, data_length);
4609 dtls_info("dropped unknown message of type %d\n",msg[0]);
4612 /* advance msg by length of ciphertext */
4621 dtls_new_context(void *app_data) {
4624 #ifndef WITH_CONTIKI
4625 FILE *urandom = fopen("/dev/urandom", "r");
4626 unsigned char buf[sizeof(unsigned long)];
4627 #endif /* WITH_CONTIKI */
4631 /* FIXME: need something better to init PRNG here */
4632 dtls_prng_init(now);
4633 #else /* WITH_CONTIKI */
4635 dtls_emerg("cannot initialize PRNG\n");
4639 if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
4640 dtls_emerg("cannot initialize PRNG\n");
4646 dtls_prng_init((unsigned long)*buf);
4647 #endif /* WITH_CONTIKI */
4649 c = malloc_context();
4653 memset(c, 0, sizeof(dtls_context_t));
4656 LIST_STRUCT_INIT(c, sendqueue);
4659 LIST_STRUCT_INIT(c, peers);
4660 /* LIST_STRUCT_INIT(c, key_store); */
4662 process_start(&dtls_retransmit_process, (char *)c);
4663 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
4664 /* the retransmit timer must be initialized to some large value */
4665 etimer_set(&c->retransmit_timer, 0xFFFF);
4666 PROCESS_CONTEXT_END(&coap_retransmit_process);
4667 #endif /* WITH_CONTIKI */
4669 if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
4670 c->cookie_secret_age = now;
4677 dtls_alert("cannot create DTLS context\n");
4679 dtls_free_context(c);
4684 dtls_free_context(dtls_context_t *ctx) {
4691 #ifndef WITH_CONTIKI
4695 HASH_ITER(hh, ctx->peers, p, tmp) {
4696 dtls_destroy_peer(ctx, p, 1);
4699 #else /* WITH_CONTIKI */
4700 for (p = list_head(ctx->peers); p; p = list_item_next(p))
4701 dtls_destroy_peer(ctx, p, 1);
4702 #endif /* WITH_CONTIKI */
4708 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
4715 /* check if the same peer is already in our list */
4716 if (peer == dtls_get_peer(ctx, &peer->session)) {
4717 dtls_debug("found peer, try to re-connect\n");
4718 return dtls_renegotiate(ctx, &peer->session);
4721 /* set local peer role to client, remote is server */
4722 peer->role = DTLS_CLIENT;
4724 dtls_add_peer(ctx, peer);
4726 /* send ClientHello with empty Cookie */
4727 peer->handshake_params = dtls_handshake_new();
4728 if (!peer->handshake_params)
4731 peer->handshake_params->hs_state.mseq_r = 0;
4732 peer->handshake_params->hs_state.mseq_s = 0;
4733 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4734 res = dtls_send_client_hello(ctx, peer, NULL, 0);
4736 dtls_warn("cannot send ClientHello\n");
4738 peer->state = DTLS_STATE_CLIENTHELLO;
4744 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
4748 peer = dtls_get_peer(ctx, dst);
4751 peer = dtls_new_peer(dst);
4754 dtls_crit("cannot create new peer\n");
4758 res = dtls_connect_peer(ctx, peer);
4760 /* Invoke event callback to indicate connection attempt or
4761 * re-negotiation. */
4763 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
4764 } else if (res == 0) {
4765 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
4772 dtls_retransmit(dtls_context_t *context, netq_t *node) {
4773 if (!context || !node)
4776 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
4777 if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
4778 unsigned char sendbuf[DTLS_MAX_BUF];
4779 size_t len = sizeof(sendbuf);
4781 unsigned char *data = node->data;
4782 size_t length = node->length;
4784 dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
4787 node->retransmit_cnt++;
4791 node->t = now + (node->timeout << node->retransmit_cnt);
4793 netq_insert_node(context->sendqueue, node);
4795 if (node->type == DTLS_CT_HANDSHAKE) {
4796 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4798 dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
4799 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4801 dtls_debug("** retransmit packet\n");
4804 err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
4807 dtls_warn("can not retransmit packet, err: %i\n", err);
4810 dtls_debug_hexdump("retransmit header", sendbuf,
4811 sizeof(dtls_record_header_t));
4812 dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
4814 (void)CALL(context, write, &node->peer->session, sendbuf, len);
4818 /* no more retransmissions, remove node from system */
4820 dtls_debug("** removed transaction\n");
4822 /* And finally delete the node */
4823 netq_node_free(node);
4827 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4829 node = list_head(context->sendqueue);
4832 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4835 node = list_item_next(node);
4840 dtls_start_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4842 node = list_head(context->sendqueue);
4845 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4846 node->retransmit_cnt = 0;
4849 node = list_item_next(node);
4854 dtls_clear_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4856 node = list_head(context->sendqueue);
4859 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4861 node = list_item_next(node);
4862 list_remove(context->sendqueue, tmp);
4863 netq_node_free(tmp);
4865 node = list_item_next(node);
4871 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
4873 netq_t *node = netq_head(context->sendqueue);
4878 if (node->t && node->t <= now){
4879 netq_pop_first(context->sendqueue);
4880 dtls_retransmit(context, node);
4881 node = netq_head(context->sendqueue);
4883 node = list_item_next(node);
4889 dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
4890 const uint8_t* label, const uint32_t labellen,
4891 const uint8_t* random1, const uint32_t random1len,
4892 const uint8_t* random2, const uint32_t random2len,
4893 uint8_t* buf, const uint32_t buflen) {
4894 dtls_peer_t *peer = NULL;
4895 dtls_security_parameters_t *security = NULL;
4898 if(!ctx || !session || !label || !buf || labellen == 0 || buflen == 0) {
4899 dtls_warn("dtls_prf_with_current_keyblock(): invalid parameter\n");
4903 peer = dtls_get_peer(ctx, session);
4905 dtls_warn("dtls_prf_with_current_keyblock(): cannot find peer\n");
4909 security = dtls_security_params(peer);
4911 dtls_crit("dtls_prf_with_current_keyblock(): peer has empty security parameters\n");
4915 /* note that keysize should never be zero as bad things will happen */
4916 keysize = dtls_kb_size(security, peer->role);
4917 assert(keysize > 0);
4919 return dtls_prf(security->key_block, keysize,
4921 random1, random1len,
4922 random2, random2len,
4927 /*---------------------------------------------------------------------------*/
4928 /* message retransmission */
4929 /*---------------------------------------------------------------------------*/
4930 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4937 dtls_debug("Started DTLS retransmit process\r\n");
4941 if (ev == PROCESS_EVENT_TIMER) {
4942 if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4944 node = list_head(the_dtls_context.sendqueue);
4947 if (node && node->t <= now) {
4948 dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
4949 node = list_head(the_dtls_context.sendqueue);
4952 /* need to set timer to some value even if no nextpdu is available */
4954 etimer_set(&the_dtls_context.retransmit_timer,
4955 node->t <= now ? 1 : node->t - now);
4957 etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4965 #endif /* WITH_CONTIKI */