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 dtls_get_peer(const dtls_context_t *ctx, const session_t *session) {
232 dtls_peer_t *p = NULL;
235 HASH_FIND_PEER(ctx->peers, session, p);
236 #else /* WITH_CONTIKI */
237 for (p = list_head(ctx->peers); p; p = list_item_next(p))
238 if (dtls_session_equals(&p->session, session))
240 #endif /* WITH_CONTIKI */
246 dtls_add_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
248 HASH_ADD_PEER(ctx->peers, session, peer);
249 #else /* WITH_CONTIKI */
250 list_add(ctx->peers, peer);
251 #endif /* WITH_CONTIKI */
255 dtls_write(struct dtls_context_t *ctx,
256 session_t *dst, uint8 *buf, size_t len) {
258 dtls_peer_t *peer = dtls_get_peer(ctx, dst);
260 /* Check if peer connection already exists */
261 if (!peer) { /* no ==> create one */
264 /* dtls_connect() returns a value greater than zero if a new
265 * connection attempt is made, 0 for session reuse. */
266 res = dtls_connect(ctx, dst);
268 return (res >= 0) ? 0 : res;
269 } else { /* a session exists, check if it is in state connected */
271 if (peer->state != DTLS_STATE_CONNECTED) {
274 return dtls_send(ctx, peer, DTLS_CT_APPLICATION_DATA, buf, len);
280 dtls_get_cookie(uint8 *msg, size_t msglen, uint8 **cookie) {
281 /* To access the cookie, we have to determine the session id's
282 * length and skip the whole thing. */
283 if (msglen < DTLS_HS_LENGTH + DTLS_CH_LENGTH + sizeof(uint8))
284 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
286 if (dtls_uint16_to_int(msg + DTLS_HS_LENGTH) != DTLS_VERSION)
287 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
289 msglen -= DTLS_HS_LENGTH + DTLS_CH_LENGTH;
290 msg += DTLS_HS_LENGTH + DTLS_CH_LENGTH;
292 SKIP_VAR_FIELD(msg, msglen, uint8); /* skip session id */
294 if (msglen < (*msg & 0xff) + sizeof(uint8))
295 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
297 *cookie = msg + sizeof(uint8);
298 return dtls_uint8_to_int(msg);
301 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
305 dtls_create_cookie(dtls_context_t *ctx,
307 uint8 *msg, size_t msglen,
308 uint8 *cookie, int *clen) {
309 unsigned char buf[DTLS_HMAC_MAX];
312 /* create cookie with HMAC-SHA256 over:
314 * - session parameters (only IP address?)
316 * - random gmt and bytes
319 * - compression method
322 /* We use our own buffer as hmac_context instead of a dynamic buffer
323 * created by dtls_hmac_new() to separate storage space for cookie
324 * creation from storage that is used in real sessions. Note that
325 * the buffer size must fit with the default hash algorithm (see
326 * implementation of dtls_hmac_context_new()). */
328 dtls_hmac_context_t hmac_context;
329 dtls_hmac_init(&hmac_context, ctx->cookie_secret, DTLS_COOKIE_SECRET_LENGTH);
331 dtls_hmac_update(&hmac_context,
332 (unsigned char *)&session->addr, session->size);
334 /* feed in the beginning of the Client Hello up to and including the
336 e = sizeof(dtls_client_hello_t);
337 e += (*(msg + DTLS_HS_LENGTH + e) & 0xff) + sizeof(uint8);
338 if (e + DTLS_HS_LENGTH > msglen)
339 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
341 dtls_hmac_update(&hmac_context, msg + DTLS_HS_LENGTH, e);
343 /* skip cookie bytes and length byte */
344 e += *(uint8 *)(msg + DTLS_HS_LENGTH + e) & 0xff;
346 if (e + DTLS_HS_LENGTH > msglen)
347 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
349 dtls_hmac_update(&hmac_context,
350 msg + DTLS_HS_LENGTH + e,
351 dtls_get_fragment_length(DTLS_HANDSHAKE_HEADER(msg)) - e);
353 len = dtls_hmac_finalize(&hmac_context, buf);
356 memset(cookie + len, 0, *clen - len);
360 memcpy(cookie, buf, *clen);
364 #ifdef DTLS_CHECK_CONTENTTYPE
365 /* used to check if a received datagram contains a DTLS message */
366 static char const content_types[] = {
367 DTLS_CT_CHANGE_CIPHER_SPEC,
370 DTLS_CT_APPLICATION_DATA,
376 * Checks if \p msg points to a valid DTLS record. If
380 is_record(uint8 *msg, size_t msglen) {
381 unsigned int rlen = 0;
383 if (msglen >= DTLS_RH_LENGTH /* FIXME allow empty records? */
384 #ifdef DTLS_CHECK_CONTENTTYPE
385 && strchr(content_types, msg[0])
387 && msg[1] == HIGH(DTLS_VERSION)
388 && msg[2] == LOW(DTLS_VERSION))
390 rlen = DTLS_RH_LENGTH +
391 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->length);
393 /* we do not accept wrong length field in record header */
402 * Initializes \p buf as record header. The caller must ensure that \p
403 * buf is capable of holding at least \c sizeof(dtls_record_header_t)
404 * bytes. Increments sequence number counter of \p security.
405 * \return pointer to the next byte after the written header.
406 * The length will be set to 0 and has to be changed before sending.
408 static inline uint8 *
409 dtls_set_record_header(uint8 type, dtls_security_parameters_t *security,
412 dtls_int_to_uint8(buf, type);
413 buf += sizeof(uint8);
415 dtls_int_to_uint16(buf, DTLS_VERSION);
416 buf += sizeof(uint16);
419 dtls_int_to_uint16(buf, security->epoch);
420 buf += sizeof(uint16);
422 dtls_int_to_uint48(buf, security->rseq);
423 buf += sizeof(uint48);
425 /* increment record sequence counter by 1 */
428 memset(buf, 0, sizeof(uint16) + sizeof(uint48));
429 buf += sizeof(uint16) + sizeof(uint48);
432 memset(buf, 0, sizeof(uint16));
433 return buf + sizeof(uint16);
437 * Initializes \p buf as handshake header. The caller must ensure that \p
438 * buf is capable of holding at least \c sizeof(dtls_handshake_header_t)
439 * bytes. Increments message sequence number counter of \p peer.
440 * \return pointer to the next byte after \p buf
442 static inline uint8 *
443 dtls_set_handshake_header(uint8 type, dtls_peer_t *peer,
445 int frag_offset, int frag_length,
448 dtls_int_to_uint8(buf, type);
449 buf += sizeof(uint8);
451 dtls_int_to_uint24(buf, length);
452 buf += sizeof(uint24);
454 if (peer && peer->handshake_params) {
455 /* and copy the result to buf */
456 dtls_int_to_uint16(buf, peer->handshake_params->hs_state.mseq_s);
458 /* increment handshake message sequence counter by 1 */
459 peer->handshake_params->hs_state.mseq_s++;
461 memset(buf, 0, sizeof(uint16));
463 buf += sizeof(uint16);
465 dtls_int_to_uint24(buf, frag_offset);
466 buf += sizeof(uint24);
468 dtls_int_to_uint24(buf, frag_length);
469 buf += sizeof(uint24);
474 /** only one compression method is currently defined */
475 static uint8 compression_methods[] = {
479 /** returns true if the cipher matches TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
480 static inline int is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(dtls_cipher_t cipher)
483 return cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
486 #endif /* DTLS_ECC */
489 /** returns true if the cipher matches TLS_PSK_WITH_AES_128_CCM_8 */
490 static inline int is_tls_psk_with_aes_128_ccm_8(dtls_cipher_t cipher)
493 return cipher == TLS_PSK_WITH_AES_128_CCM_8;
496 #endif /* DTLS_PSK */
499 /** returns true if the cipher matches TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 */
500 static inline int is_tls_ecdh_anon_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
503 return cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256;
509 /** returns true if the cipher matches TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 */
510 static inline int is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(dtls_cipher_t cipher)
512 #if defined(DTLS_ECC) && defined(DTLS_PSK)
513 return cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256;
516 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
521 /** returns true if the application is configured for psk */
522 static inline int is_psk_supported(dtls_context_t *ctx)
525 return ctx && ctx->h && ctx->h->get_psk_info;
528 #endif /* DTLS_PSK */
531 /** returns true if the application is configured for ecdhe_ecdsa */
532 static inline int is_ecdsa_supported(dtls_context_t *ctx, int is_client)
535 return ctx && ctx->h && ((!is_client && ctx->h->get_ecdsa_key) ||
536 (is_client && ctx->h->verify_ecdsa_key));
539 #endif /* DTLS_ECC */
542 /** Returns true if the application is configured for ecdhe_ecdsa with
543 * client authentication */
544 static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
547 return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
550 #endif /* DTLS_ECC */
553 /** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
554 static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
557 return ctx && (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
563 /** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
564 static inline int is_ecdhe_psk_supported(dtls_context_t *ctx)
566 #if defined(DTLS_ECC) && defined(DTLS_PSK)
567 return is_psk_supported(ctx);
570 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
575 * Returns @c 1 if @p code is a cipher suite other than @c
576 * TLS_NULL_WITH_NULL_NULL that we recognize.
578 * @param ctx The current DTLS context
579 * @param code The cipher suite identifier to check
580 * @param is_client 1 for a dtls client, 0 for server
581 * @return @c 1 iff @p code is recognized,
584 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
590 psk = is_psk_supported(ctx);
591 ecdsa = is_ecdsa_supported(ctx, is_client);
592 ecdh_anon = is_ecdh_anon_supported(ctx);
593 ecdhe_psk = is_ecdhe_psk_supported(ctx);
595 return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
596 (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code)) ||
597 (ecdh_anon && is_tls_ecdh_anon_with_aes_128_cbc_sha_256(code)) ||
598 (ecdhe_psk && is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(code));
602 * This method detects if we already have a established DTLS session with
603 * peer and the peer is attempting to perform a fresh handshake by sending
604 * messages with epoch = 0. This is to handle situations mentioned in
605 * RFC 6347 - section 4.2.8.
607 * @param msg The packet received from Client
608 * @param msglen Packet length
609 * @param peer peer who is the sender for this packet
610 * @return @c 1 if this is a rehandshake attempt by
614 hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
617 if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
618 if (msg[0] == DTLS_CT_HANDSHAKE) {
619 uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
620 if (msg_epoch == 0) {
621 dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
622 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
623 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
632 /** Dump out the cipher keys and IVs used for the symetric cipher. */
633 static void dtls_debug_keyblock(dtls_security_parameters_t *config)
635 dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
636 dtls_debug_dump(" client_MAC_secret",
637 dtls_kb_client_mac_secret(config, peer->role),
638 dtls_kb_mac_secret_size(config, peer->role));
640 dtls_debug_dump(" server_MAC_secret",
641 dtls_kb_server_mac_secret(config, peer->role),
642 dtls_kb_mac_secret_size(config, peer->role));
644 dtls_debug_dump(" client_write_key",
645 dtls_kb_client_write_key(config, peer->role),
646 dtls_kb_key_size(config, peer->role));
648 dtls_debug_dump(" server_write_key",
649 dtls_kb_server_write_key(config, peer->role),
650 dtls_kb_key_size(config, peer->role));
652 dtls_debug_dump(" client_IV",
653 dtls_kb_client_iv(config, peer->role),
654 dtls_kb_iv_size(config, peer->role));
656 dtls_debug_dump(" server_IV",
657 dtls_kb_server_iv(config, peer->role),
658 dtls_kb_iv_size(config, peer->role));
661 /** returns the name of the goven handshake type number.
662 * see IANA for a full list of types:
663 * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
665 static char *dtls_handshake_type_to_name(int type)
668 case DTLS_HT_HELLO_REQUEST:
669 return "hello_request";
670 case DTLS_HT_CLIENT_HELLO:
671 return "client_hello";
672 case DTLS_HT_SERVER_HELLO:
673 return "server_hello";
674 case DTLS_HT_HELLO_VERIFY_REQUEST:
675 return "hello_verify_request";
676 case DTLS_HT_CERTIFICATE:
677 return "certificate";
678 case DTLS_HT_SERVER_KEY_EXCHANGE:
679 return "server_key_exchange";
680 case DTLS_HT_CERTIFICATE_REQUEST:
681 return "certificate_request";
682 case DTLS_HT_SERVER_HELLO_DONE:
683 return "server_hello_done";
684 case DTLS_HT_CERTIFICATE_VERIFY:
685 return "certificate_verify";
686 case DTLS_HT_CLIENT_KEY_EXCHANGE:
687 return "client_key_exchange";
688 case DTLS_HT_FINISHED:
696 * Calculate the pre master secret and after that calculate the master-secret.
699 calculate_key_block(dtls_context_t *ctx,
700 dtls_handshake_parameters_t *handshake,
703 dtls_peer_type role) {
704 #if defined(DTLS_PSK) && defined(DTLS_ECC)
705 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH + uECC_BYTES];
707 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH];
708 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
709 int pre_master_len = 0;
710 dtls_security_parameters_t *security = dtls_security_params_next(peer);
711 uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
714 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
717 switch (handshake->cipher) {
719 case TLS_PSK_WITH_AES_128_CCM_8: {
720 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
723 len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
724 handshake->keyx.psk.identity,
725 handshake->keyx.psk.id_length,
726 psk, DTLS_PSK_MAX_KEY_LEN);
728 dtls_crit("no psk key for session available\n");
731 /* Temporarily use the key_block storage space for the pre master secret. */
732 pre_master_len = dtls_psk_pre_master_secret(psk, len,
734 MAX_KEYBLOCK_LENGTH);
736 dtls_debug_hexdump("psk", psk, len);
738 memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
739 if (pre_master_len < 0) {
740 dtls_crit("the psk was too long, for the pre master secret\n");
741 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
746 #endif /* DTLS_PSK */
748 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
749 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
750 pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecc.own_eph_priv,
751 handshake->keyx.ecc.other_eph_pub_x,
752 handshake->keyx.ecc.other_eph_pub_y,
753 sizeof(handshake->keyx.ecc.own_eph_priv),
755 MAX_KEYBLOCK_LENGTH);
756 if (pre_master_len < 0) {
757 dtls_crit("the curve was too long, for the pre master secret\n");
758 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
762 #endif /* DTLS_ECC */
763 #if defined(DTLS_PSK) && defined(DTLS_ECC)
764 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
765 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
768 psklen = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
769 handshake->keyx.psk.identity,
770 handshake->keyx.psk.id_length,
771 psk, DTLS_PSK_MAX_KEY_LEN);
773 dtls_crit("no psk key for session available\n");
777 pre_master_len = dtls_ecdhe_psk_pre_master_secret(psk, psklen,
778 handshake->keyx.ecc.own_eph_priv,
779 handshake->keyx.ecc.other_eph_pub_x,
780 handshake->keyx.ecc.other_eph_pub_y,
781 sizeof(handshake->keyx.ecc.own_eph_priv),
783 MAX_KEYBLOCK_LENGTH + uECC_BYTES);
785 if (pre_master_len < 0) {
786 dtls_crit("the curve was too long, for the pre master secret\n");
787 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
791 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
793 dtls_crit("calculate_key_block: unknown cipher\n");
794 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
797 dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
798 dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
799 dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
801 dtls_prf(pre_master_secret, pre_master_len,
802 PRF_LABEL(master), PRF_LABEL_SIZE(master),
803 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
804 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
806 DTLS_MASTER_SECRET_LENGTH);
808 dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
810 /* create key_block from master_secret
811 * key_block = PRF(master_secret,
812 "key expansion" + tmp.random.server + tmp.random.client) */
814 dtls_prf(master_secret,
815 DTLS_MASTER_SECRET_LENGTH,
816 PRF_LABEL(key), PRF_LABEL_SIZE(key),
817 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
818 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
820 dtls_kb_size(security, role));
822 memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
823 dtls_debug_keyblock(security);
825 security->cipher = handshake->cipher;
826 security->compression = handshake->compression;
832 /* TODO: add a generic method which iterates over a list and searches for a specific key */
833 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
836 /* length of curve list */
837 i = dtls_uint16_to_int(data);
838 data += sizeof(uint16);
839 if (i + sizeof(uint16) != data_length) {
840 dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
841 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
844 for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
845 /* check if this curve is supported */
846 curve_name = dtls_uint16_to_int(data);
847 data += sizeof(uint16);
849 if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
853 dtls_warn("no supported elliptic curve found\n");
854 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
857 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
860 /* length of cert type list */
861 i = dtls_uint8_to_int(data);
862 data += sizeof(uint8);
863 if (i + sizeof(uint8) != data_length) {
864 dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
865 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
868 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
869 /* check if this cert type is supported */
870 cert_type = dtls_uint8_to_int(data);
871 data += sizeof(uint8);
873 if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
877 dtls_warn("no supported certificate type found\n");
878 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
881 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
884 /* length of ec_point_formats list */
885 i = dtls_uint8_to_int(data);
886 data += sizeof(uint8);
887 if (i + sizeof(uint8) != data_length) {
888 dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
889 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
892 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
893 /* check if this ec_point_format is supported */
894 cert_type = dtls_uint8_to_int(data);
895 data += sizeof(uint8);
897 if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
901 dtls_warn("no supported ec_point_format found\n");
902 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
906 * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
909 dtls_check_tls_extension(dtls_peer_t *peer,
910 uint8 *data, size_t data_length, int client_hello)
913 int ext_elliptic_curve = 0;
914 int ext_client_cert_type = 0;
915 int ext_server_cert_type = 0;
916 int ext_ec_point_formats = 0;
917 dtls_handshake_parameters_t *handshake = peer->handshake_params;
919 if (data_length < sizeof(uint16)) {
920 /* no tls extensions specified */
921 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
927 /* get the length of the tls extension list */
928 j = dtls_uint16_to_int(data);
929 data += sizeof(uint16);
930 data_length -= sizeof(uint16);
935 /* check for TLS extensions needed for this cipher */
936 while (data_length) {
937 if (data_length < sizeof(uint16) * 2)
940 /* get the tls extension type */
941 i = dtls_uint16_to_int(data);
942 data += sizeof(uint16);
943 data_length -= sizeof(uint16);
945 /* get the length of the tls extension */
946 j = dtls_uint16_to_int(data);
947 data += sizeof(uint16);
948 data_length -= sizeof(uint16);
954 case TLS_EXT_ELLIPTIC_CURVES:
955 ext_elliptic_curve = 1;
956 if (verify_ext_eliptic_curves(data, j))
959 case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
960 ext_client_cert_type = 1;
962 if (verify_ext_cert_type(data, j))
965 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
969 case TLS_EXT_SERVER_CERTIFICATE_TYPE:
970 ext_server_cert_type = 1;
972 if (verify_ext_cert_type(data, j))
975 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
979 case TLS_EXT_EC_POINT_FORMATS:
980 ext_ec_point_formats = 1;
981 if (verify_ext_ec_point_formats(data, j))
984 case TLS_EXT_ENCRYPT_THEN_MAC:
985 /* As only AEAD cipher suites are currently available, this
986 * extension can be skipped.
988 dtls_info("skipped encrypt-then-mac extension\n");
991 dtls_warn("unsupported tls extension: %i\n", i);
997 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
998 if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
999 || !ext_ec_point_formats) {
1000 dtls_warn("not all required tls extensions found in client hello\n");
1003 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
1004 if (!ext_client_cert_type || !ext_server_cert_type) {
1005 dtls_warn("not all required tls extensions found in server hello\n");
1012 if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
1013 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1015 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1020 * Parses the ClientHello from the client and updates the internal handshake
1021 * parameters with the new data for the given \p peer. When the ClientHello
1022 * handshake message in \p data does not contain a cipher suite or
1023 * compression method, it is copied from the the current security parameters.
1025 * \param ctx The current DTLS context.
1026 * \param peer The remote peer whose security parameters are about to change.
1027 * \param data The handshake message with a ClientHello.
1028 * \param data_length The actual size of \p data.
1029 * \return \c -Something if an error occurred, \c 0 on success.
1032 dtls_update_parameters(dtls_context_t *ctx,
1034 uint8 *data, size_t data_length) {
1037 dtls_handshake_parameters_t *config = peer->handshake_params;
1038 dtls_security_parameters_t *security = dtls_security_params(peer);
1041 assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
1043 /* skip the handshake header and client version information */
1044 data += DTLS_HS_LENGTH + sizeof(uint16);
1045 data_length -= DTLS_HS_LENGTH + sizeof(uint16);
1047 /* store client random in config */
1048 memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
1049 data += DTLS_RANDOM_LENGTH;
1050 data_length -= DTLS_RANDOM_LENGTH;
1052 /* Caution: SKIP_VAR_FIELD may jump to error: */
1053 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
1054 SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
1056 i = dtls_uint16_to_int(data);
1057 if (data_length < i + sizeof(uint16)) {
1058 /* Looks like we do not have a cipher nor compression. This is ok
1059 * for renegotiation, but not for the initial handshake. */
1061 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
1064 config->cipher = security->cipher;
1065 config->compression = security->compression;
1070 data += sizeof(uint16);
1071 data_length -= sizeof(uint16) + i;
1075 config->cipher = dtls_uint16_to_int(data);
1076 ok = known_cipher(ctx, config->cipher, 0);
1077 i -= sizeof(uint16);
1078 data += sizeof(uint16);
1081 /* skip remaining ciphers */
1085 /* reset config cipher to a well-defined value */
1086 config->cipher = TLS_NULL_WITH_NULL_NULL;
1087 dtls_warn("No matching cipher found\n");
1091 if (data_length < sizeof(uint8)) {
1092 /* no compression specified, take the current compression method */
1094 config->compression = security->compression;
1096 config->compression = TLS_COMPRESSION_NULL;
1100 i = dtls_uint8_to_int(data);
1101 if (data_length < i + sizeof(uint8))
1104 data += sizeof(uint8);
1105 data_length -= sizeof(uint8) + i;
1109 for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
1110 if (dtls_uint8_to_int(data) == compression_methods[j]) {
1111 config->compression = compression_methods[j];
1115 data += sizeof(uint8);
1119 /* reset config cipher to a well-defined value */
1123 return dtls_check_tls_extension(peer, data, data_length, 1);
1125 if (peer->state == DTLS_STATE_CONNECTED) {
1126 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1128 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1133 * Parse the ClientKeyExchange and update the internal handshake state with
1137 check_client_keyexchange(dtls_context_t *ctx,
1138 dtls_handshake_parameters_t *handshake,
1139 uint8 *data, size_t length) {
1142 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) ||
1143 is_tls_ecdh_anon_with_aes_128_cbc_sha_256(handshake->cipher) ) {
1145 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1146 dtls_debug("The client key exchange is too short\n");
1147 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1149 data += DTLS_HS_LENGTH;
1151 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1152 dtls_alert("expected 65 bytes long public point\n");
1153 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1155 data += sizeof(uint8);
1157 if (dtls_uint8_to_int(data) != 4) {
1158 dtls_alert("expected uncompressed public point\n");
1159 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1161 data += sizeof(uint8);
1163 memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1164 sizeof(handshake->keyx.ecc.other_eph_pub_x));
1165 data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1167 memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1168 sizeof(handshake->keyx.ecc.other_eph_pub_y));
1169 data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1171 #endif /* DTLS_ECC */
1172 #if defined(DTLS_PSK) && defined(DTLS_ECC)
1173 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(handshake->cipher)) {
1176 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1177 dtls_debug("The client key exchange is too short\n");
1178 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1180 data += DTLS_HS_LENGTH;
1183 id_length = dtls_uint16_to_int(data);
1184 data += sizeof(uint16);
1186 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + DTLS_CKXEC_LENGTH + id_length != length) {
1187 dtls_debug("The identity has a wrong length\n");
1188 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1191 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1192 dtls_warn("please use a smaller client identity\n");
1193 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1196 handshake->keyx.psk.id_length = id_length;
1197 memcpy(handshake->keyx.psk.identity, data, id_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 /* defined(DTLS_PSK) && defined(DTLS_ECC) */
1223 if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1226 if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
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;
1232 id_length = dtls_uint16_to_int(data);
1233 data += sizeof(uint16);
1235 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1236 dtls_debug("The identity has a wrong length\n");
1237 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1240 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1241 dtls_warn("please use a smaller client identity\n");
1242 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1245 handshake->keyx.psk.id_length = id_length;
1246 memcpy(handshake->keyx.psk.identity, data, id_length);
1248 #endif /* DTLS_PSK */
1253 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1254 dtls_debug_dump("add MAC data", data, length);
1255 dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1259 copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
1260 memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1261 sizeof(peer->handshake_params->hs_state.hs_hash));
1264 static inline size_t
1265 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
1266 return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1270 clear_hs_hash(dtls_peer_t *peer) {
1272 dtls_debug("clear MAC\n");
1273 dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
1277 * Checks if \p record + \p data contain a Finished message with valid
1280 * \param ctx The current DTLS context.
1281 * \param peer The remote peer of the security association.
1282 * \param data The cleartext payload of the message.
1283 * \param data_length Actual length of \p data.
1284 * \return \c 0 if the Finished message is valid, \c negative number otherwise.
1287 check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
1288 uint8 *data, size_t data_length) {
1289 size_t digest_length, label_size;
1290 const unsigned char *label;
1291 unsigned char buf[DTLS_HMAC_MAX];
1293 if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1294 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1296 /* Use a union here to ensure that sufficient stack space is
1297 * reserved. As statebuf and verify_data are not used at the same
1298 * time, we can re-use the storage safely.
1301 unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1302 unsigned char verify_data[DTLS_FIN_LENGTH];
1305 /* temporarily store hash status for roll-back after finalize */
1306 memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1308 digest_length = finalize_hs_hash(peer, buf);
1311 /* restore hash status */
1312 memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1314 if (peer->role == DTLS_CLIENT) {
1315 label = PRF_LABEL(server);
1316 label_size = PRF_LABEL_SIZE(server);
1317 } else { /* server */
1318 label = PRF_LABEL(client);
1319 label_size = PRF_LABEL_SIZE(client);
1322 dtls_prf(peer->handshake_params->tmp.master_secret,
1323 DTLS_MASTER_SECRET_LENGTH,
1325 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1327 b.verify_data, sizeof(b.verify_data));
1329 dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1330 dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1332 /* compare verify data and create DTLS alert code when they differ */
1333 return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1335 : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
1339 * Prepares the payload given in \p data for sending with
1340 * dtls_send(). The \p data is encrypted and compressed according to
1341 * the current security parameters of \p peer. The result of this
1342 * operation is put into \p sendbuf with a prepended record header of
1343 * type \p type ready for sending. As some cipher suites add a MAC
1344 * before encryption, \p data must be large enough to hold this data
1345 * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
1347 * \param peer The remote peer the packet will be sent to.
1348 * \param security The encryption paramater used to encrypt
1349 * \param type The content type of this record.
1350 * \param data_array Array with payloads in correct order.
1351 * \param data_len_array sizes of the payloads in correct order.
1352 * \param data_array_len The number of payloads given.
1353 * \param sendbuf The output buffer where the encrypted record
1355 * \param rlen This parameter must be initialized with the
1356 * maximum size of \p sendbuf and will be updated
1357 * to hold the actual size of the stored packet
1358 * on success. On error, the value of \p rlen is
1360 * \return Less than zero on error, or greater than zero success.
1363 dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
1365 uint8 *data_array[], size_t data_len_array[],
1366 size_t data_array_len,
1367 uint8 *sendbuf, size_t *rlen) {
1372 if (*rlen < DTLS_RH_LENGTH) {
1373 dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1374 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1377 p = dtls_set_record_header(type, security, sendbuf);
1380 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1381 /* no cipher suite */
1384 for (i = 0; i < data_array_len; i++) {
1385 /* check the minimum that we need for packets that are not encrypted */
1386 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1387 dtls_debug("dtls_prepare_record: send buffer too small\n");
1388 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1391 memcpy(p, data_array[i], data_len_array[i]);
1392 p += data_len_array[i];
1393 res += data_len_array[i];
1395 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
1396 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
1398 unsigned char nonce[DTLS_CBC_IV_LENGTH];
1400 /** Add IV into body of packet in case of AES CBC mode according to RFC 5246, Section 6.2.3.2
1402 * opaque IV[SecurityParameters.record_iv_length];
1403 * block-ciphered struct {
1404 * opaque content[TLSCompressed.length];
1405 * opaque MAC[SecurityParameters.mac_length];
1406 * uint8 padding[GenericBlockCipher.padding_length];
1407 * uint8 padding_length;
1413 dtls_prng(nonce, DTLS_CBC_IV_LENGTH);
1414 memcpy(p , nonce, DTLS_CBC_IV_LENGTH);
1415 p += DTLS_CBC_IV_LENGTH;
1416 res += DTLS_CBC_IV_LENGTH;
1418 for (i = 0; i < data_array_len; i++) {
1419 /* check the minimum that we need for packets that are not encrypted */
1420 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1421 dtls_debug("dtls_prepare_record: send buffer too small\n");
1422 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1425 memcpy(p, data_array[i], data_len_array[i]);
1426 p += data_len_array[i];
1427 res += data_len_array[i];
1430 res = dtls_encrypt(start + DTLS_CBC_IV_LENGTH, res - DTLS_CBC_IV_LENGTH,
1431 start + DTLS_CBC_IV_LENGTH, nonce,
1432 dtls_kb_local_write_key(security, peer->role),
1433 dtls_kb_key_size(security, peer->role),
1439 res += DTLS_CBC_IV_LENGTH;
1441 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1443 * length of additional_data for the AEAD cipher which consists of
1444 * seq_num(2+6) + type(1) + version(2) + length(2)
1446 #define A_DATA_LEN 13
1447 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1448 unsigned char A_DATA[A_DATA_LEN];
1450 if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1451 dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1452 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1453 dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1455 dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1460 The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1461 the "nonce" SHALL be 12 bytes long and is constructed as follows:
1462 (this is an example of a "partially explicit" nonce; see Section
1463 3.2.1 in [RFC5116]).
1467 opaque nonce_explicit[8];
1472 In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1475 When the nonce_explicit is equal to the sequence number, the CCMNonce
1476 will have the structure of the CCMNonceExample given below.
1479 uint32 client_write_IV; // low order 32-bits
1480 uint64 seq_num; // TLS sequence number
1485 uint32 server_write_IV; // low order 32-bits
1486 uint64 seq_num; // TLS sequence number
1498 memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1502 for (i = 0; i < data_array_len; i++) {
1503 /* check the minimum that we need for packets that are not encrypted */
1504 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1505 dtls_debug("dtls_prepare_record: send buffer too small\n");
1506 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1509 memcpy(p, data_array[i], data_len_array[i]);
1510 p += data_len_array[i];
1511 res += data_len_array[i];
1514 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1515 memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1516 dtls_kb_iv_size(security, peer->role));
1517 memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
1519 dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1520 dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1521 dtls_kb_key_size(security, peer->role));
1523 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1525 * additional_data = seq_num + TLSCompressed.type +
1526 * TLSCompressed.version + TLSCompressed.length;
1528 memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1529 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1530 dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1533 res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1534 dtls_kb_local_write_key(security, peer->role),
1535 dtls_kb_key_size(security, peer->role),
1542 res += 8; /* increment res by size of nonce_explicit */
1543 dtls_debug_dump("message:", start, res);
1546 /* fix length of fragment in sendbuf */
1547 dtls_int_to_uint16(sendbuf + 11, res);
1549 *rlen = DTLS_RH_LENGTH + res;
1554 dtls_send_handshake_msg_hash(dtls_context_t *ctx,
1558 uint8 *data, size_t data_length,
1561 uint8 buf[DTLS_HS_LENGTH];
1562 uint8 *data_array[2];
1563 size_t data_len_array[2];
1565 dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1567 dtls_set_handshake_header(header_type, peer, data_length, 0,
1571 update_hs_hash(peer, buf, sizeof(buf));
1573 data_array[i] = buf;
1574 data_len_array[i] = sizeof(buf);
1579 update_hs_hash(peer, data, data_length);
1581 data_array[i] = data;
1582 data_len_array[i] = data_length;
1585 dtls_debug("send handshake packet of type: %s (%i)\n",
1586 dtls_handshake_type_to_name(header_type), header_type);
1587 return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1588 data_array, data_len_array, i);
1592 dtls_send_handshake_msg(dtls_context_t *ctx,
1595 uint8 *data, size_t data_length)
1597 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1598 header_type, data, data_length, 1);
1602 * Returns true if the message @p Data is a handshake message that
1603 * must be included in the calculation of verify_data in the Finished
1606 * @param Type The message type. Only handshake messages but the initial
1607 * Client Hello and Hello Verify Request are included in the hash,
1608 * @param Data The PDU to examine.
1609 * @param Length The length of @p Data.
1611 * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
1615 #define MUST_HASH(Type, Data, Length) \
1616 ((Type) == DTLS_CT_HANDSHAKE && \
1617 ((Data) != NULL) && ((Length) > 0) && \
1618 ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) && \
1619 ((Data)[0] != DTLS_HT_CLIENT_HELLO || \
1620 ((Length) >= HS_HDR_LENGTH && \
1621 (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) || \
1622 (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1625 * Sends the data passed in @p buf as a DTLS record of type @p type to
1626 * the given peer. The data will be encrypted and compressed according
1627 * to the security parameters for @p peer.
1629 * @param ctx The DTLS context in effect.
1630 * @param peer The remote party where the packet is sent.
1631 * @param type The content type of this record.
1632 * @param buf The data to send.
1633 * @param buflen The number of bytes to send from @p buf.
1634 * @return Less than zero in case of an error or the number of
1635 * bytes that have been sent otherwise.
1638 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
1639 dtls_security_parameters_t *security , session_t *session,
1640 unsigned char type, uint8 *buf_array[],
1641 size_t buf_len_array[], size_t buf_array_len)
1643 /* We cannot use ctx->sendbuf here as it is reserved for collecting
1644 * the input for this function, i.e. buf == ctx->sendbuf.
1646 * TODO: check if we can use the receive buf here. This would mean
1647 * that we might not be able to handle multiple records stuffed in
1648 * one UDP datagram */
1649 unsigned char sendbuf[DTLS_MAX_BUF];
1650 size_t len = sizeof(sendbuf);
1653 size_t overall_len = 0;
1655 res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1660 /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1661 /* update_hs_hash(peer, buf, buflen); */
1663 dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1664 for (i = 0; i < buf_array_len; i++) {
1665 dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1666 overall_len += buf_len_array[i];
1669 if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1670 type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1671 /* copy handshake messages other than HelloVerify into retransmit buffer */
1672 netq_t *n = netq_node_new(overall_len);
1676 n->t = now + 2 * CLOCK_SECOND;
1677 n->retransmit_cnt = 0;
1678 n->timeout = 2 * CLOCK_SECOND;
1680 n->epoch = (security) ? security->epoch : 0;
1683 for (i = 0; i < buf_array_len; i++) {
1684 memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1685 n->length += buf_len_array[i];
1688 if (!netq_insert_node(ctx->sendqueue, n)) {
1689 dtls_warn("cannot add packet to retransmit buffer\n");
1693 /* must set timer within the context of the retransmit process */
1694 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1695 etimer_set(&ctx->retransmit_timer, n->timeout);
1696 PROCESS_CONTEXT_END(&dtls_retransmit_process);
1697 #else /* WITH_CONTIKI */
1698 dtls_debug("copied to sendqueue\n");
1699 #endif /* WITH_CONTIKI */
1702 dtls_warn("retransmit buffer full\n");
1705 /* FIXME: copy to peer's sendqueue (after fragmentation if
1706 * necessary) and initialize retransmit timer */
1707 res = CALL(ctx, write, session, sendbuf, len);
1709 /* Guess number of bytes application data actually sent:
1710 * dtls_prepare_record() tells us in len the number of bytes to
1711 * send, res will contain the bytes actually sent. */
1712 return res <= 0 ? res : overall_len - (len - res);
1716 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
1717 dtls_alert_t description) {
1718 uint8_t msg[] = { level, description };
1720 dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1725 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1729 peer = dtls_get_peer(ctx, remote);
1732 res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
1733 /* indicate tear down */
1734 peer->state = DTLS_STATE_CLOSING;
1739 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1741 if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1742 dtls_close(ctx, &peer->session);
1744 #ifndef WITH_CONTIKI
1745 HASH_DEL_PEER(ctx->peers, peer);
1746 #else /* WITH_CONTIKI */
1747 list_remove(ctx->peers, peer);
1748 #endif /* WITH_CONTIKI */
1750 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1752 dtls_free_peer(peer);
1756 * Checks a received Client Hello message for a valid cookie. When the
1757 * Client Hello contains no cookie, the function fails and a Hello
1758 * Verify Request is sent to the peer (using the write callback function
1759 * registered with \p ctx). The return value is \c -1 on error, \c 0 when
1760 * undecided, and \c 1 if the Client Hello was good.
1762 * \param ctx The DTLS context.
1763 * \param peer The remote party we are talking to, if any.
1764 * \param session Transport address of the remote peer.
1765 * \param state Current state of the connection.
1766 * \param msg The received datagram.
1767 * \param msglen Length of \p msg.
1768 * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
1772 dtls_verify_peer(dtls_context_t *ctx,
1775 const dtls_state_t state,
1776 uint8 *data, size_t data_length)
1778 uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
1780 int len = DTLS_COOKIE_LENGTH;
1781 uint8 *cookie = NULL;
1784 #define mycookie (buf + DTLS_HV_LENGTH)
1786 /* Store cookie where we can reuse it for the HelloVerify request. */
1787 err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1791 dtls_debug_dump("create cookie", mycookie, len);
1793 assert(len == DTLS_COOKIE_LENGTH);
1795 /* Perform cookie check. */
1796 len = dtls_get_cookie(data, data_length, &cookie);
1798 dtls_warn("error while fetching the cookie, err: %i\n", err);
1802 dtls_debug_dump("compare with cookie", cookie, len);
1804 /* check if cookies match */
1805 if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1806 dtls_debug("found matching cookie\n");
1811 dtls_debug_dump("invalid cookie", cookie, len);
1813 dtls_debug("cookie len is 0!\n");
1816 /* ClientHello did not contain any valid cookie, hence we send a
1817 * HelloVerify request. */
1819 dtls_int_to_uint16(p, DTLS_VERSION);
1820 p += sizeof(uint16);
1822 dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
1825 assert(p == mycookie);
1827 p += DTLS_COOKIE_LENGTH;
1829 /* TODO use the same record sequence number as in the ClientHello,
1830 see 4.2.1. Denial-of-Service Countermeasures */
1831 err = dtls_send_handshake_msg_hash(ctx,
1832 state == DTLS_STATE_CONNECTED ? peer : NULL,
1834 DTLS_HT_HELLO_VERIFY_REQUEST,
1837 dtls_warn("cannot send HelloVerify request\n");
1839 return err; /* HelloVerify is sent, now we cannot do anything but wait */
1846 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1847 unsigned char **result_r,
1848 unsigned char **result_s)
1851 uint8 *data_orig = data;
1853 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
1854 dtls_alert("only sha256 is supported in certificate verify\n");
1855 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1857 data += sizeof(uint8);
1858 data_length -= sizeof(uint8);
1860 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
1861 dtls_alert("only ecdsa signature is supported in client verify\n");
1862 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1864 data += sizeof(uint8);
1865 data_length -= sizeof(uint8);
1867 if (data_length < dtls_uint16_to_int(data)) {
1868 dtls_alert("signature length wrong\n");
1869 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1871 data += sizeof(uint16);
1872 data_length -= sizeof(uint16);
1874 if (dtls_uint8_to_int(data) != 0x30) {
1875 dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1876 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1878 data += sizeof(uint8);
1879 data_length -= sizeof(uint8);
1881 if (data_length < dtls_uint8_to_int(data)) {
1882 dtls_alert("signature length wrong\n");
1883 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1885 data += sizeof(uint8);
1886 data_length -= sizeof(uint8);
1888 if (dtls_uint8_to_int(data) != 0x02) {
1889 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1890 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1892 data += sizeof(uint8);
1893 data_length -= sizeof(uint8);
1895 i = dtls_uint8_to_int(data);
1896 data += sizeof(uint8);
1897 data_length -= sizeof(uint8);
1899 /* Sometimes these values have a leeding 0 byte */
1900 *result_r = data + i - DTLS_EC_KEY_SIZE;
1905 if (dtls_uint8_to_int(data) != 0x02) {
1906 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1907 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1909 data += sizeof(uint8);
1910 data_length -= sizeof(uint8);
1912 i = dtls_uint8_to_int(data);
1913 data += sizeof(uint8);
1914 data_length -= sizeof(uint8);
1916 /* Sometimes these values have a leeding 0 byte */
1917 *result_s = data + i - DTLS_EC_KEY_SIZE;
1922 return data - data_orig;
1926 check_client_certificate_verify(dtls_context_t *ctx,
1928 uint8 *data, size_t data_length)
1930 dtls_handshake_parameters_t *config = peer->handshake_params;
1932 unsigned char *result_r;
1933 unsigned char *result_s;
1934 dtls_hash_ctx hs_hash;
1935 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1937 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
1939 data += DTLS_HS_LENGTH;
1941 if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1942 dtls_alert("the packet length does not match the expected\n");
1943 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1946 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
1953 copy_hs_hash(peer, &hs_hash);
1955 dtls_hash_finalize(sha256hash, &hs_hash);
1957 ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
1958 sizeof(config->keyx.ecc.other_pub_x),
1959 sha256hash, sizeof(sha256hash),
1960 result_r, result_s);
1963 dtls_alert("wrong signature err: %i\n", ret);
1964 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1968 #endif /* DTLS_ECC */
1971 dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
1973 /* Ensure that the largest message to create fits in our source
1974 * buffer. (The size of the destination buffer is checked by the
1975 * encoding function, so we do not need to guess.) */
1976 uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
1979 uint8 extension_size;
1980 dtls_handshake_parameters_t *handshake = peer->handshake_params;
1983 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
1985 extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
1987 /* Handshake header */
1991 dtls_int_to_uint16(p, DTLS_VERSION);
1992 p += sizeof(uint16);
1994 /* Set server random: First 4 bytes are the server's Unix timestamp,
1995 * followed by 28 bytes of generate random data. */
1997 dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
1998 dtls_prng(handshake->tmp.random.server + 4, 28);
2000 memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
2001 p += DTLS_RANDOM_LENGTH;
2003 *p++ = 0; /* no session id */
2005 if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
2006 /* selected cipher suite */
2007 dtls_int_to_uint16(p, handshake->cipher);
2008 p += sizeof(uint16);
2010 /* selected compression method */
2011 *p++ = compression_methods[handshake->compression];
2014 if (extension_size) {
2015 /* length of the extensions */
2016 dtls_int_to_uint16(p, extension_size - 2);
2017 p += sizeof(uint16);
2021 /* client certificate type extension */
2022 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2023 p += sizeof(uint16);
2025 /* length of this extension type */
2026 dtls_int_to_uint16(p, 1);
2027 p += sizeof(uint16);
2029 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2032 /* client certificate type extension */
2033 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2034 p += sizeof(uint16);
2036 /* length of this extension type */
2037 dtls_int_to_uint16(p, 1);
2038 p += sizeof(uint16);
2040 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2043 /* ec_point_formats */
2044 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2045 p += sizeof(uint16);
2047 /* length of this extension type */
2048 dtls_int_to_uint16(p, 2);
2049 p += sizeof(uint16);
2051 /* number of supported formats */
2052 dtls_int_to_uint8(p, 1);
2055 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2059 assert(p - buf <= sizeof(buf));
2061 /* TODO use the same record sequence number as in the ClientHello,
2062 see 4.2.1. Denial-of-Service Countermeasures */
2063 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
2069 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
2070 const dtls_ecc_key_t *key)
2072 uint8 buf[DTLS_CE_LENGTH];
2077 * Start message construction at beginning of buffer. */
2080 dtls_int_to_uint24(p, 94); /* certificates length */
2081 p += sizeof(uint24);
2083 dtls_int_to_uint24(p, 91); /* length of this certificate */
2084 p += sizeof(uint24);
2086 memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
2087 p += sizeof(cert_asn1_header);
2089 memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
2090 p += DTLS_EC_KEY_SIZE;
2092 memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
2093 p += DTLS_EC_KEY_SIZE;
2095 assert(p - buf <= sizeof(buf));
2097 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2102 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
2107 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
2108 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
2109 /* store the pointer to the r component of the signature and make space */
2110 len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
2111 len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
2117 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2121 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2124 /* length of signature */
2125 dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
2126 p += sizeof(uint16);
2128 /* ASN.1 SEQUENCE */
2129 dtls_int_to_uint8(p, 0x30);
2132 dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
2135 /* ASN.1 Integer r */
2136 dtls_int_to_uint8(p, 0x02);
2139 dtls_int_to_uint8(p, len_r);
2142 /* the pint r was added here */
2145 /* ASN.1 Integer s */
2146 dtls_int_to_uint8(p, 0x02);
2149 dtls_int_to_uint8(p, len_s);
2152 /* the pint s was added here */
2159 dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2160 const dtls_ecc_key_t *key)
2162 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2163 * 33 bytes long add space for that */
2164 uint8 buf[DTLS_SKEXEC_LENGTH + 2];
2167 uint8 *ephemeral_pub_x;
2168 uint8 *ephemeral_pub_y;
2169 uint32_t point_r[9];
2170 uint32_t point_s[9];
2172 dtls_handshake_parameters_t *config = peer->handshake_params;
2174 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2175 /* ServerKeyExchange
2177 * Start message construction at beginning of buffer. */
2181 /* ECCurveType curve_type: named_curve */
2182 dtls_int_to_uint8(p, 3);
2185 /* NamedCurve namedcurve: secp256r1 */
2186 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2187 p += sizeof(uint16);
2189 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2192 /* This should be an uncompressed point, but I do not have access to the spec. */
2193 dtls_int_to_uint8(p, 4);
2196 /* store the pointer to the x component of the pub key and make space */
2197 ephemeral_pub_x = p;
2198 p += DTLS_EC_KEY_SIZE;
2200 /* store the pointer to the y component of the pub key and make space */
2201 ephemeral_pub_y = p;
2202 p += DTLS_EC_KEY_SIZE;
2204 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2205 ephemeral_pub_x, ephemeral_pub_y,
2209 /* sign the ephemeral and its paramaters */
2210 dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
2211 config->tmp.random.client, DTLS_RANDOM_LENGTH,
2212 config->tmp.random.server, DTLS_RANDOM_LENGTH,
2213 key_params, p - key_params,
2216 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2219 assert(p - buf <= sizeof(buf));
2221 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2224 #endif /* DTLS_ECC */
2226 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2227 static int dtls_send_server_key_exchange_ecdhe_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2228 const unsigned char *psk_hint, size_t psk_hint_len)
2230 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2231 * 33 bytes long add space for that */
2232 uint8 buf[DTLS_SKEXEC_LENGTH + DTLS_SKEXECPSK_LENGTH_MAX + 2];
2234 uint8 *ephemeral_pub_x;
2235 uint8 *ephemeral_pub_y;
2236 dtls_handshake_parameters_t *config = peer->handshake_params;
2238 /* ServerKeyExchange
2239 * Please see Session 2, RFC 5489.
2242 select (KeyExchangeAlgorithm) {
2243 //other cases for rsa, diffie_hellman, etc.
2244 case ec_diffie_hellman_psk: // NEW
2245 opaque psk_identity_hint<0..2^16-1>;
2246 ServerECDHParams params;
2248 } ServerKeyExchange; */
2251 assert(psk_hint_len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2252 if (psk_hint_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2253 // should never happen
2254 dtls_warn("psk identity hint is too long\n");
2255 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2258 // psk_identity_hint
2259 dtls_int_to_uint16(p, psk_hint_len);
2260 p += sizeof(uint16);
2262 memcpy(p, psk_hint, psk_hint_len);
2265 /* ServerECDHParams. */
2266 /* ECCurveType curve_type: named_curve */
2267 dtls_int_to_uint8(p, TLS_EC_CURVE_TYPE_NAMED_CURVE);
2270 /* NamedCurve namedcurve: secp256r1 */
2271 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2272 p += sizeof(uint16);
2274 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2277 /* This should be an uncompressed point, but I do not have access to the spec. */
2278 dtls_int_to_uint8(p, 4);
2281 /* store the pointer to the x component of the pub key and make space */
2282 ephemeral_pub_x = p;
2283 p += DTLS_EC_KEY_SIZE;
2285 /* store the pointer to the y component of the pub key and make space */
2286 ephemeral_pub_y = p;
2287 p += DTLS_EC_KEY_SIZE;
2289 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2290 ephemeral_pub_x, ephemeral_pub_y,
2293 assert(p - buf <= sizeof(buf));
2295 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2298 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2302 dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2303 const unsigned char *psk_hint, size_t len)
2305 uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
2310 assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2311 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2312 /* should never happen */
2313 dtls_warn("psk identity hint is too long\n");
2314 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2317 dtls_int_to_uint16(p, len);
2318 p += sizeof(uint16);
2320 memcpy(p, psk_hint, len);
2323 assert(p - buf <= sizeof(buf));
2325 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2328 #endif /* DTLS_PSK */
2332 dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
2339 * Start message construction at beginning of buffer. */
2342 /* certificate_types */
2343 dtls_int_to_uint8(p, 1);
2347 dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
2350 /* supported_signature_algorithms */
2351 dtls_int_to_uint16(p, 2);
2352 p += sizeof(uint16);
2355 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2359 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2362 /* certificate_authoritiess */
2363 dtls_int_to_uint16(p, 0);
2364 p += sizeof(uint16);
2366 assert(p - buf <= sizeof(buf));
2368 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
2371 #endif /* DTLS_ECC */
2374 dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
2379 * Start message construction at beginning of buffer. */
2381 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
2386 dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
2393 res = dtls_send_server_hello(ctx, peer);
2396 dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2400 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2401 ecdh_anon = is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2402 ecdhe_psk = is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2406 res = dtls_send_server_key_exchange_ecdh(ctx, peer, NULL);
2409 dtls_debug("dtls_server_hello(with ECDH): cannot prepare Server Key Exchange record\n");
2414 const dtls_ecc_key_t *ecdsa_key;
2416 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2418 dtls_crit("no ecdsa certificate to send in certificate\n");
2422 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2425 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2429 res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2432 dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2436 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
2437 is_ecdsa_client_auth_supported(ctx)) {
2438 res = dtls_send_server_certificate_request(ctx, peer);
2441 dtls_debug("dtls_server_hello(with ECDSA): cannot prepare certificate Request record\n");
2446 #endif /* DTLS_ECC */
2447 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2448 else if(ecdhe_psk) {
2449 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2452 /* The identity hint is optional, therefore we ignore the result
2453 * and check psk only. */
2454 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2455 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2458 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2463 res = dtls_send_server_key_exchange_ecdhe_psk(ctx, peer, psk_hint, (size_t)psk_len);
2466 dtls_debug("dtls_server_hello(with ECDHE): cannot prepare Server Key Exchange record\n");
2471 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2473 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2474 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2477 /* The identity hint is optional, therefore we ignore the result
2478 * and check psk only. */
2479 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2480 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2483 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2488 res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2491 dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2496 #endif /* DTLS_PSK */
2498 res = dtls_send_server_hello_done(ctx, peer);
2501 dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2508 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
2511 return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2516 dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
2518 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2519 uint8 buf[DTLS_CKXEC_LENGTH + 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2521 uint8 buf[DTLS_CKXEC_LENGTH];
2522 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2523 uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2525 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2529 switch (handshake->cipher) {
2531 case TLS_PSK_WITH_AES_128_CCM_8: {
2534 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2539 dtls_crit("no psk identity set in kx\n");
2543 if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2544 dtls_warn("the psk identity is too long\n");
2545 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2548 dtls_int_to_uint16(p, len);
2549 p += sizeof(uint16);
2551 memcpy(p, client_id, len);
2556 #endif /* DTLS_PSK */
2558 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2559 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
2560 uint8 *ephemeral_pub_x;
2561 uint8 *ephemeral_pub_y;
2563 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2566 /* This should be an uncompressed point, but I do not have access to the spec. */
2567 dtls_int_to_uint8(p, 4);
2570 ephemeral_pub_x = p;
2571 p += DTLS_EC_KEY_SIZE;
2572 ephemeral_pub_y = p;
2573 p += DTLS_EC_KEY_SIZE;
2575 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2576 ephemeral_pub_x, ephemeral_pub_y,
2581 #endif /* DTLS_ECC */
2582 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2583 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
2585 uint8 *ephemeral_pub_x;
2586 uint8 *ephemeral_pub_y;
2588 /* Please see Session 2, RFC 5489.
2590 select (KeyExchangeAlgorithm) {
2591 // other cases for rsa, diffie_hellman, etc.
2592 case ec_diffie_hellman_psk:
2593 opaque psk_identity<0..2^16-1>;
2594 ClientECDiffieHellmanPublic public;
2596 } ClientKeyExchange;
2599 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2604 dtls_crit("no psk identity set in kx\n");
2608 if (psk_len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2609 dtls_warn("the psk identity is too long\n");
2610 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2613 dtls_int_to_uint16(p, psk_len);
2614 p += sizeof(uint16);
2616 memcpy(p, client_id, psk_len);
2619 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2622 dtls_int_to_uint8(p, 4);
2625 ephemeral_pub_x = p;
2626 p += DTLS_EC_KEY_SIZE;
2627 ephemeral_pub_y = p;
2628 p += DTLS_EC_KEY_SIZE;
2630 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2631 ephemeral_pub_x, ephemeral_pub_y,
2635 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2637 dtls_crit("cipher not supported\n");
2638 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2641 assert(p - buf <= sizeof(buf));
2643 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
2649 dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2650 const dtls_ecc_key_t *key)
2652 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2653 * 33 bytes long add space for that */
2654 uint8 buf[DTLS_CV_LENGTH + 2];
2656 uint32_t point_r[9];
2657 uint32_t point_s[9];
2658 dtls_hash_ctx hs_hash;
2659 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2661 /* ServerKeyExchange
2663 * Start message construction at beginning of buffer. */
2666 copy_hs_hash(peer, &hs_hash);
2668 dtls_hash_finalize(sha256hash, &hs_hash);
2670 /* sign the ephemeral and its paramaters */
2671 dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
2672 sha256hash, sizeof(sha256hash),
2675 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2677 assert(p - buf <= sizeof(buf));
2679 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
2682 #endif /* DTLS_ECC */
2685 dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
2686 const unsigned char *label, size_t labellen)
2689 uint8 hash[DTLS_HMAC_MAX];
2690 uint8 buf[DTLS_FIN_LENGTH];
2691 dtls_hash_ctx hs_hash;
2694 copy_hs_hash(peer, &hs_hash);
2696 length = dtls_hash_finalize(hash, &hs_hash);
2698 dtls_prf(peer->handshake_params->tmp.master_secret,
2699 DTLS_MASTER_SECRET_LENGTH,
2701 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2703 p, DTLS_FIN_LENGTH);
2705 dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2707 p += DTLS_FIN_LENGTH;
2709 assert(p - buf <= sizeof(buf));
2711 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2716 dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
2717 uint8 cookie[], size_t cookie_length) {
2718 uint8 buf[DTLS_CH_LENGTH_MAX];
2720 uint8_t cipher_size;
2721 uint8_t extension_size;
2726 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2729 switch(ctx->selected_cipher)
2731 case TLS_PSK_WITH_AES_128_CCM_8:
2732 psk = is_psk_supported(ctx);
2734 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2735 ecdsa = is_ecdsa_supported(ctx, 1);
2737 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
2738 ecdh_anon = is_ecdh_anon_supported(ctx);
2740 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
2741 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2744 psk = is_psk_supported(ctx);
2745 ecdsa = is_ecdsa_supported(ctx, 1);
2746 ecdh_anon = is_ecdh_anon_supported(ctx);
2747 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2751 cipher_size = 2 + (ecdsa ? 2 : 0) + (psk ? 2 : 0) + (ecdh_anon ? 2 : 0) + (ecdhe_psk ? 2 : 0);
2752 extension_size = (ecdsa) ? (2 + 6 + 6 + 8 + 6) : 0;
2754 if (cipher_size == 0) {
2755 dtls_crit("no cipher callbacks implemented\n");
2758 dtls_int_to_uint16(p, DTLS_VERSION);
2759 p += sizeof(uint16);
2761 if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2762 dtls_warn("the cookie is too long\n");
2763 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2766 if (cookie_length == 0) {
2767 /* Set client random: First 4 bytes are the client's Unix timestamp,
2768 * followed by 28 bytes of generate random data. */
2770 dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2771 dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2772 DTLS_RANDOM_LENGTH - sizeof(uint32));
2774 /* we must use the same Client Random as for the previous request */
2775 memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2776 p += DTLS_RANDOM_LENGTH;
2778 /* session id (length 0) */
2779 dtls_int_to_uint8(p, 0);
2783 dtls_int_to_uint8(p, cookie_length);
2785 if (cookie_length != 0) {
2786 memcpy(p, cookie, cookie_length);
2790 /* add known cipher(s) */
2791 dtls_int_to_uint16(p, cipher_size - 2);
2792 p += sizeof(uint16);
2795 dtls_int_to_uint16(p, TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256);
2796 p += sizeof(uint16);
2799 dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
2800 p += sizeof(uint16);
2803 dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
2804 p += sizeof(uint16);
2807 dtls_int_to_uint16(p, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
2808 p += sizeof(uint16);
2811 /* compression method */
2812 dtls_int_to_uint8(p, 1);
2815 dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
2818 if (extension_size) {
2819 /* length of the extensions */
2820 dtls_int_to_uint16(p, extension_size - 2);
2821 p += sizeof(uint16);
2825 /* client certificate type extension */
2826 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2827 p += sizeof(uint16);
2829 /* length of this extension type */
2830 dtls_int_to_uint16(p, 2);
2831 p += sizeof(uint16);
2833 /* length of the list */
2834 dtls_int_to_uint8(p, 1);
2837 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2840 /* client certificate type extension */
2841 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2842 p += sizeof(uint16);
2844 /* length of this extension type */
2845 dtls_int_to_uint16(p, 2);
2846 p += sizeof(uint16);
2848 /* length of the list */
2849 dtls_int_to_uint8(p, 1);
2852 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2855 /* elliptic_curves */
2856 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
2857 p += sizeof(uint16);
2859 /* length of this extension type */
2860 dtls_int_to_uint16(p, 4);
2861 p += sizeof(uint16);
2863 /* length of the list */
2864 dtls_int_to_uint16(p, 2);
2865 p += sizeof(uint16);
2867 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2868 p += sizeof(uint16);
2870 /* ec_point_formats */
2871 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2872 p += sizeof(uint16);
2874 /* length of this extension type */
2875 dtls_int_to_uint16(p, 2);
2876 p += sizeof(uint16);
2878 /* number of supported formats */
2879 dtls_int_to_uint8(p, 1);
2882 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2886 assert(p - buf <= sizeof(buf));
2888 if (cookie_length != 0)
2889 clear_hs_hash(peer);
2891 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
2892 DTLS_HT_CLIENT_HELLO,
2893 buf, p - buf, cookie_length != 0);
2897 check_server_hello(dtls_context_t *ctx,
2899 uint8 *data, size_t data_length)
2901 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2903 /* This function is called when we expect a ServerHello (i.e. we
2904 * have sent a ClientHello). We might instead receive a HelloVerify
2905 * request containing a cookie. If so, we must repeat the
2906 * ClientHello with the given Cookie.
2908 if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
2909 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2911 update_hs_hash(peer, data, data_length);
2913 /* FIXME: check data_length before accessing fields */
2915 /* Get the server's random data and store selected cipher suite
2916 * and compression method (like dtls_update_parameters().
2917 * Then calculate master secret and wait for ServerHelloDone. When received,
2918 * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
2920 /* check server version */
2921 data += DTLS_HS_LENGTH;
2922 data_length -= DTLS_HS_LENGTH;
2924 if (dtls_uint16_to_int(data) != DTLS_VERSION) {
2925 dtls_alert("unknown DTLS version\n");
2926 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
2929 data += sizeof(uint16); /* skip version field */
2930 data_length -= sizeof(uint16);
2932 /* store server random data */
2933 memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
2934 /* skip server random */
2935 data += DTLS_RANDOM_LENGTH;
2936 data_length -= DTLS_RANDOM_LENGTH;
2938 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
2940 /* Check cipher suite. As we offer all we have, it is sufficient
2941 * to check if the cipher suite selected by the server is in our
2942 * list of known cipher suites. Subsets are not supported. */
2943 handshake->cipher = dtls_uint16_to_int(data);
2944 if (!known_cipher(ctx, handshake->cipher, 1)) {
2945 dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
2947 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
2949 data += sizeof(uint16);
2950 data_length -= sizeof(uint16);
2952 /* Check if NULL compression was selected. We do not know any other. */
2953 if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
2954 dtls_alert("unsupported compression method 0x%02x\n", data[0]);
2955 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
2957 data += sizeof(uint8);
2958 data_length -= sizeof(uint8);
2960 return dtls_check_tls_extension(peer, data, data_length, 0);
2963 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2967 check_server_hello_verify_request(dtls_context_t *ctx,
2969 uint8 *data, size_t data_length)
2971 dtls_hello_verify_t *hv;
2974 if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
2975 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
2977 hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
2979 res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
2982 dtls_warn("cannot send ClientHello\n");
2989 check_server_certificate(dtls_context_t *ctx,
2991 uint8 *data, size_t data_length)
2994 dtls_handshake_parameters_t *config = peer->handshake_params;
2996 update_hs_hash(peer, data, data_length);
2998 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3000 data += DTLS_HS_LENGTH;
3002 if (dtls_uint24_to_int(data) != 94) {
3003 dtls_alert("expect length of 94 bytes for server certificate message\n");
3004 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3006 data += sizeof(uint24);
3008 if (dtls_uint24_to_int(data) != 91) {
3009 dtls_alert("expect length of 91 bytes for certificate\n");
3010 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3012 data += sizeof(uint24);
3014 if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
3015 dtls_alert("got an unexpected Subject public key format\n");
3016 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3018 data += sizeof(cert_asn1_header);
3020 memcpy(config->keyx.ecc.other_pub_x, data,
3021 sizeof(config->keyx.ecc.other_pub_x));
3022 data += sizeof(config->keyx.ecc.other_pub_x);
3024 memcpy(config->keyx.ecc.other_pub_y, data,
3025 sizeof(config->keyx.ecc.other_pub_y));
3026 data += sizeof(config->keyx.ecc.other_pub_y);
3028 err = CALL(ctx, verify_ecdsa_key, &peer->session,
3029 config->keyx.ecc.other_pub_x,
3030 config->keyx.ecc.other_pub_y,
3031 sizeof(config->keyx.ecc.other_pub_x));
3033 dtls_warn("The certificate was not accepted\n");
3041 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
3043 uint8 *data, size_t data_length)
3045 dtls_handshake_parameters_t *config = peer->handshake_params;
3047 unsigned char *result_r;
3048 unsigned char *result_s;
3049 unsigned char *key_params;
3051 update_hs_hash(peer, data, data_length);
3053 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3055 data += DTLS_HS_LENGTH;
3057 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
3058 dtls_alert("the packet length does not match the expected\n");
3059 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3063 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3064 dtls_alert("Only named curves supported\n");
3065 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3067 data += sizeof(uint8);
3068 data_length -= sizeof(uint8);
3070 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3071 dtls_alert("secp256r1 supported\n");
3072 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3074 data += sizeof(uint16);
3075 data_length -= sizeof(uint16);
3077 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3078 dtls_alert("expected 65 bytes long public point\n");
3079 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3081 data += sizeof(uint8);
3082 data_length -= sizeof(uint8);
3084 if (dtls_uint8_to_int(data) != 4) {
3085 dtls_alert("expected uncompressed public point\n");
3086 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3088 data += sizeof(uint8);
3089 data_length -= sizeof(uint8);
3091 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3092 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3093 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3095 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3096 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3097 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3099 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
3106 ret = dtls_ecdsa_verify_sig(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
3107 sizeof(config->keyx.ecc.other_pub_x),
3108 config->tmp.random.client, DTLS_RANDOM_LENGTH,
3109 config->tmp.random.server, DTLS_RANDOM_LENGTH,
3111 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
3112 result_r, result_s);
3115 dtls_alert("wrong signature\n");
3116 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3122 check_server_key_exchange_ecdh(dtls_context_t *ctx,
3124 uint8 *data, size_t data_length)
3126 dtls_handshake_parameters_t *config = peer->handshake_params;
3128 update_hs_hash(peer, data, data_length);
3130 assert(is_tls_ecdh_anon_with_aes_128_cbc_sha_256(config->cipher));
3132 data += DTLS_HS_LENGTH;
3134 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3135 dtls_alert("the packet length does not match the expected\n");
3136 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3139 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3140 dtls_alert("Only named curves supported\n");
3141 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3143 data += sizeof(uint8);
3144 data_length -= sizeof(uint8);
3146 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3147 dtls_alert("secp256r1 supported\n");
3148 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3150 data += sizeof(uint16);
3151 data_length -= sizeof(uint16);
3153 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3154 dtls_alert("expected 65 bytes long public point\n");
3155 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3157 data += sizeof(uint8);
3158 data_length -= sizeof(uint8);
3160 if (dtls_uint8_to_int(data) != 4) {
3161 dtls_alert("expected uncompressed public point\n");
3162 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3164 data += sizeof(uint8);
3165 data_length -= sizeof(uint8);
3167 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3168 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3169 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3171 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3172 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3173 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3177 #endif /* DTLS_ECC */
3178 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3179 check_server_key_exchange_ecdhe_psk(dtls_context_t *ctx,
3181 uint8 *data, size_t data_length)
3183 dtls_handshake_parameters_t *config = peer->handshake_params;
3184 uint16_t psk_len = 0;
3186 /* ServerKeyExchange
3187 * Please see Session 2, RFC 5489.
3190 select (KeyExchangeAlgorithm) {
3191 //other cases for rsa, diffie_hellman, etc.
3192 case ec_diffie_hellman_psk: // NEW
3193 opaque psk_identity_hint<0..2^16-1>;
3194 ServerECDHParams params;
3196 } ServerKeyExchange; */
3198 update_hs_hash(peer, data, data_length);
3200 assert(is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(config->cipher));
3202 data += DTLS_HS_LENGTH;
3204 psk_len = dtls_uint16_to_int(data);
3205 data += sizeof(uint16);
3207 if (psk_len != data_length - DTLS_HS_LENGTH - DTLS_SKEXEC_ECDH_ANON_LENGTH - sizeof(uint16)) {
3208 dtls_warn("the length of the server identity hint is worng\n");
3209 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3212 if (psk_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3213 dtls_warn("please use a smaller server identity hint\n");
3214 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3217 // store the psk_identity_hint in config->keyx.psk for later use
3218 config->keyx.psk.id_length = psk_len;
3219 memcpy(config->keyx.psk.identity, data, psk_len);
3222 data_length -= psk_len;
3224 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3225 dtls_alert("the packet length does not match the expected\n");
3226 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3229 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3230 dtls_alert("Only named curves supported\n");
3231 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3233 data += sizeof(uint8);
3234 data_length -= sizeof(uint8);
3236 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3237 dtls_alert("secp256r1 supported\n");
3238 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3240 data += sizeof(uint16);
3241 data_length -= sizeof(uint16);
3243 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3244 dtls_alert("expected 65 bytes long public point\n");
3245 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3247 data += sizeof(uint8);
3248 data_length -= sizeof(uint8);
3250 if (dtls_uint8_to_int(data) != 4) {
3251 dtls_alert("expected uncompressed public point\n");
3252 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3254 data += sizeof(uint8);
3255 data_length -= sizeof(uint8);
3257 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3258 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3259 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3261 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3262 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3263 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3267 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
3271 check_server_key_exchange_psk(dtls_context_t *ctx,
3273 uint8 *data, size_t data_length)
3275 dtls_handshake_parameters_t *config = peer->handshake_params;
3278 update_hs_hash(peer, data, data_length);
3280 assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
3282 data += DTLS_HS_LENGTH;
3284 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
3285 dtls_alert("the packet length does not match the expected\n");
3286 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3289 len = dtls_uint16_to_int(data);
3290 data += sizeof(uint16);
3292 if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
3293 dtls_warn("the length of the server identity hint is worng\n");
3294 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3297 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3298 dtls_warn("please use a smaller server identity hint\n");
3299 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3302 /* store the psk_identity_hint in config->keyx.psk for later use */
3303 config->keyx.psk.id_length = len;
3304 memcpy(config->keyx.psk.identity, data, len);
3307 #endif /* DTLS_PSK */
3310 check_certificate_request(dtls_context_t *ctx,
3312 uint8 *data, size_t data_length)
3319 update_hs_hash(peer, data, data_length);
3321 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
3323 data += DTLS_HS_LENGTH;
3325 if (data_length < DTLS_HS_LENGTH + 5) {
3326 dtls_alert("the packet length does not match the expected\n");
3327 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3330 i = dtls_uint8_to_int(data);
3331 data += sizeof(uint8);
3332 if (i + 1 > data_length) {
3333 dtls_alert("the cerfificate types are too long\n");
3334 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3338 for (; i > 0 ; i -= sizeof(uint8)) {
3339 if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
3341 auth_alg = dtls_uint8_to_int(data);
3342 data += sizeof(uint8);
3345 if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
3346 dtls_alert("the request authentication algorithm is not supproted\n");
3347 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3350 i = dtls_uint16_to_int(data);
3351 data += sizeof(uint16);
3352 if (i + 1 > data_length) {
3353 dtls_alert("the signature and hash algorithm list is too long\n");
3354 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3359 for (; i > 0 ; i -= sizeof(uint16)) {
3360 int current_hash_alg;
3361 int current_sig_alg;
3363 current_hash_alg = dtls_uint8_to_int(data);
3364 data += sizeof(uint8);
3365 current_sig_alg = dtls_uint8_to_int(data);
3366 data += sizeof(uint8);
3368 if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 &&
3369 current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
3370 hash_alg = current_hash_alg;
3371 sig_alg = current_sig_alg;
3375 if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
3376 sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
3377 dtls_alert("no supported hash and signature algorithem\n");
3378 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3381 /* common names are ignored */
3383 peer->handshake_params->do_client_auth = 1;
3388 check_server_hellodone(dtls_context_t *ctx,
3390 uint8 *data, size_t data_length)
3394 const dtls_ecc_key_t *ecdsa_key;
3395 #endif /* DTLS_ECC */
3397 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3399 /* calculate master key, send CCS */
3401 update_hs_hash(peer, data, data_length);
3404 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3406 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
3408 dtls_crit("no ecdsa certificate to send in certificate\n");
3412 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
3415 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3419 #endif /* DTLS_ECC */
3421 /* send ClientKeyExchange */
3422 res = dtls_send_client_key_exchange(ctx, peer);
3425 dtls_debug("cannot send KeyExchange message\n");
3430 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3432 res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
3435 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3439 #endif /* DTLS_ECC */
3441 res = calculate_key_block(ctx, handshake, peer,
3442 &peer->session, peer->role);
3447 res = dtls_send_ccs(ctx, peer);
3449 dtls_debug("cannot send CCS message\n");
3453 /* and switch cipher suite */
3454 dtls_security_params_switch(peer);
3456 /* Client Finished */
3457 return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
3461 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
3464 dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
3465 dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
3468 *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
3469 clen = length - sizeof(dtls_record_header_t);
3472 dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
3476 if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
3477 /* no cipher suite selected */
3479 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
3480 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
3482 unsigned char nonce[DTLS_CBC_IV_LENGTH];
3484 if (clen < (DTLS_CBC_IV_LENGTH + DTLS_HMAC_DIGEST_SIZE)) /* need at least IV and MAC */
3487 memcpy(nonce, *cleartext , DTLS_CBC_IV_LENGTH);
3488 clen -= DTLS_CBC_IV_LENGTH;
3489 *cleartext += DTLS_CBC_IV_LENGTH ;
3491 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3492 dtls_kb_remote_write_key(security, peer->role),
3493 dtls_kb_key_size(security, peer->role),
3497 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
3499 * length of additional_data for the AEAD cipher which consists of
3500 * seq_num(2+6) + type(1) + version(2) + length(2)
3502 #define A_DATA_LEN 13
3503 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
3504 unsigned char A_DATA[A_DATA_LEN];
3506 if (clen < 16) /* need at least IV and MAC */
3509 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
3510 memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
3511 dtls_kb_iv_size(security, peer->role));
3513 /* read epoch and seq_num from message */
3514 memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
3518 dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
3519 dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
3520 dtls_kb_key_size(security, peer->role));
3521 dtls_debug_dump("ciphertext", *cleartext, clen);
3523 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
3525 * additional_data = seq_num + TLSCompressed.type +
3526 * TLSCompressed.version + TLSCompressed.length;
3528 memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
3529 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
3530 dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
3532 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3533 dtls_kb_remote_write_key(security, peer->role),
3534 dtls_kb_key_size(security, peer->role),
3540 dtls_warn("decryption failed\n");
3543 dtls_debug("decrypt_verify(): found %i bytes cleartext\n", clen);
3545 dtls_security_params_free_other(peer);
3546 dtls_debug_dump("cleartext", *cleartext, clen);
3553 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
3555 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3556 DTLS_HT_HELLO_REQUEST,
3561 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
3563 dtls_peer_t *peer = NULL;
3566 peer = dtls_get_peer(ctx, dst);
3571 if (peer->state != DTLS_STATE_CONNECTED)
3574 peer->handshake_params = dtls_handshake_new();
3575 if (!peer->handshake_params)
3578 peer->handshake_params->hs_state.mseq_r = 0;
3579 peer->handshake_params->hs_state.mseq_s = 0;
3581 if (peer->role == DTLS_CLIENT) {
3582 /* send ClientHello with empty Cookie */
3583 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3585 dtls_warn("cannot send ClientHello\n");
3587 peer->state = DTLS_STATE_CLIENTHELLO;
3589 } else if (peer->role == DTLS_SERVER) {
3590 return dtls_send_hello_request(ctx, peer);
3597 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3598 const dtls_peer_type role, const dtls_state_t state,
3599 uint8 *data, size_t data_length) {
3603 /* This will clear the retransmission buffer if we get an expected
3604 * handshake message. We have to make sure that no handshake message
3605 * should get expected when we still should retransmit something, when
3606 * we do everything accordingly to the DTLS 1.2 standard this should
3607 * not be a problem. */
3609 dtls_stop_retransmission(ctx, peer);
3612 /* The following switch construct handles the given message with
3613 * respect to the current internal state for this peer. In case of
3614 * error, it is left with return 0. */
3616 dtls_debug("handle handshake packet of type: %s (%i)\n",
3617 dtls_handshake_type_to_name(data[0]), data[0]);
3620 /************************************************************************
3622 ************************************************************************/
3623 case DTLS_HT_HELLO_VERIFY_REQUEST:
3625 if (state != DTLS_STATE_CLIENTHELLO) {
3626 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3629 err = check_server_hello_verify_request(ctx, peer, data, data_length);
3631 dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3636 case DTLS_HT_SERVER_HELLO:
3638 if (state != DTLS_STATE_CLIENTHELLO) {
3639 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3642 err = check_server_hello(ctx, peer, data, data_length);
3644 dtls_warn("error in check_server_hello err: %i\n", err);
3647 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3648 peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE; //ecdsa
3649 else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher) ||
3650 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher))
3651 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE; //ecdh
3653 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE; //psk
3654 /* update_hs_hash(peer, data, data_length); */
3659 case DTLS_HT_CERTIFICATE:
3661 if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3662 (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3663 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3665 err = check_server_certificate(ctx, peer, data, data_length);
3667 dtls_warn("error in check_server_certificate err: %i\n", err);
3670 if (role == DTLS_CLIENT) {
3671 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3672 } else if (role == DTLS_SERVER){
3673 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3675 /* update_hs_hash(peer, data, data_length); */
3678 #endif /* DTLS_ECC */
3680 case DTLS_HT_SERVER_KEY_EXCHANGE:
3683 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3684 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3685 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3687 err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3690 if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3691 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3692 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3694 err = check_server_key_exchange_ecdh(ctx, peer, data, data_length);
3696 #endif /* DTLS_ECC */
3698 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3699 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3700 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3701 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3703 err = check_server_key_exchange_ecdhe_psk(ctx, peer, data, data_length);
3705 #endif defined(DTLS_PSK) && defined(DTLS_ECC)
3708 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3709 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3710 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3712 err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3714 #endif /* DTLS_PSK */
3717 dtls_warn("error in check_server_key_exchange err: %i\n", err);
3720 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3721 /* update_hs_hash(peer, data, data_length); */
3725 case DTLS_HT_SERVER_HELLO_DONE:
3727 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3728 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3731 err = check_server_hellodone(ctx, peer, data, data_length);
3733 dtls_warn("error in check_server_hellodone err: %i\n", err);
3736 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3737 /* update_hs_hash(peer, data, data_length); */
3741 case DTLS_HT_CERTIFICATE_REQUEST:
3743 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3744 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3747 err = check_certificate_request(ctx, peer, data, data_length);
3749 dtls_warn("error in check_certificate_request err: %i\n", err);
3755 case DTLS_HT_FINISHED:
3756 /* expect a Finished message from server */
3758 if (state != DTLS_STATE_WAIT_FINISHED) {
3759 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3762 err = check_finished(ctx, peer, data, data_length);
3764 dtls_warn("error in check_finished err: %i\n", err);
3767 if (role == DTLS_SERVER) {
3768 /* send ServerFinished */
3769 update_hs_hash(peer, data, data_length);
3771 /* send change cipher spec message and switch to new configuration */
3772 err = dtls_send_ccs(ctx, peer);
3774 dtls_warn("cannot send CCS message\n");
3778 dtls_security_params_switch(peer);
3780 err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3782 dtls_warn("sending server Finished failed\n");
3786 dtls_handshake_free(peer->handshake_params);
3787 peer->handshake_params = NULL;
3788 dtls_debug("Handshake complete\n");
3790 peer->state = DTLS_STATE_CONNECTED;
3792 /* return here to not increase the message receive counter */
3795 /************************************************************************
3797 ************************************************************************/
3799 case DTLS_HT_CLIENT_KEY_EXCHANGE:
3800 /* handle ClientHello, update msg and msglen and goto next if not finished */
3802 if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3803 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3806 err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3808 dtls_warn("error in check_client_keyexchange err: %i\n", err);
3811 update_hs_hash(peer, data, data_length);
3813 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3814 is_ecdsa_client_auth_supported(ctx))
3815 peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY; //ecdsa
3817 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC; //psk || ecdh_anon
3821 case DTLS_HT_CERTIFICATE_VERIFY:
3823 if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
3824 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3827 err = check_client_certificate_verify(ctx, peer, data, data_length);
3829 dtls_warn("error in check_client_certificate_verify err: %i\n", err);
3833 update_hs_hash(peer, data, data_length);
3834 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3836 #endif /* DTLS_ECC */
3838 case DTLS_HT_CLIENT_HELLO:
3840 if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
3841 (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
3842 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3845 /* When no DTLS state exists for this peer, we only allow a
3846 Client Hello message with
3848 a) a valid cookie, or
3851 Anything else will be rejected. Fragementation is not allowed
3852 here as it would require peer state as well.
3854 err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
3856 dtls_warn("error in dtls_verify_peer err: %i\n", err);
3861 dtls_debug("server hello verify was sent\n");
3865 /* At this point, we have a good relationship with this peer. This
3866 * state is left for re-negotiation of key material. */
3867 /* As per RFC 6347 - section 4.2.8 if this is an attempt to
3868 * rehandshake, we can delete the existing key material
3869 * as the client has demonstrated reachibility by completing
3870 * the cookie exchange */
3871 if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
3872 dtls_debug("removing the peer\n");
3873 #ifndef WITH_CONTIKI
3874 HASH_DEL_PEER(ctx->peers, peer);
3875 #else /* WITH_CONTIKI */
3876 list_remove(ctx->peers, peer);
3877 #endif /* WITH_CONTIKI */
3879 dtls_free_peer(peer);
3883 dtls_debug("creating new peer\n");
3884 dtls_security_parameters_t *security;
3886 /* msg contains a Client Hello with a valid cookie, so we can
3887 * safely create the server state machine and continue with
3889 peer = dtls_new_peer(session);
3891 dtls_alert("cannot create peer\n");
3892 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3894 peer->role = DTLS_SERVER;
3896 /* Initialize record sequence number to 1 for new peers. The first
3897 * record with sequence number 0 is a stateless Hello Verify Request.
3899 security = dtls_security_params(peer);
3901 dtls_add_peer(ctx, peer);
3903 if (peer && !peer->handshake_params) {
3904 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
3906 peer->handshake_params = dtls_handshake_new();
3907 if (!peer->handshake_params)
3908 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3910 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3911 peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
3912 peer->handshake_params->hs_state.mseq_s = 1;
3915 clear_hs_hash(peer);
3917 /* First negotiation step: check for PSK
3919 * Note that we already have checked that msg is a Handshake
3920 * message containing a ClientHello. dtls_get_cipher() therefore
3921 * does not check again.
3923 err = dtls_update_parameters(ctx, peer, data, data_length);
3925 dtls_warn("error updating security parameters\n");
3929 /* update finish MAC */
3930 update_hs_hash(peer, data, data_length);
3932 err = dtls_send_server_hello_msgs(ctx, peer);
3936 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3937 is_ecdsa_client_auth_supported(ctx))
3938 peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE; //ecdhe
3940 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE; //psk, ecdh_anon
3942 /* after sending the ServerHelloDone, we expect the
3943 * ClientKeyExchange (possibly containing the PSK id),
3944 * followed by a ChangeCipherSpec and an encrypted Finished.
3949 case DTLS_HT_HELLO_REQUEST:
3951 if (state != DTLS_STATE_CONNECTED) {
3952 /* we should just ignore such packets when in handshake */
3956 if (peer && !peer->handshake_params) {
3957 peer->handshake_params = dtls_handshake_new();
3958 if (!peer->handshake_params)
3959 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3961 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
3962 peer->handshake_params->hs_state.mseq_r = 0;
3963 peer->handshake_params->hs_state.mseq_s = 0;
3966 /* send ClientHello with empty Cookie */
3967 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3969 dtls_warn("cannot send ClientHello\n");
3972 peer->state = DTLS_STATE_CLIENTHELLO;
3976 dtls_crit("unhandled message %d\n", data[0]);
3977 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3980 if (peer && peer->handshake_params && err >= 0) {
3981 peer->handshake_params->hs_state.mseq_r++;
3988 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3989 const dtls_peer_type role, const dtls_state_t state,
3990 uint8 *data, size_t data_length)
3992 dtls_handshake_header_t *hs_header;
3995 if (data_length < DTLS_HS_LENGTH) {
3996 dtls_warn("handshake message too short\n");
3997 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3999 hs_header = DTLS_HANDSHAKE_HEADER(data);
4001 dtls_debug("received handshake packet of type: %s (%i)\n",
4002 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4004 if (!peer || !peer->handshake_params) {
4005 /* This is the initial ClientHello */
4006 if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
4007 dtls_warn("If there is no peer only ClientHello is allowed\n");
4008 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
4011 /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
4012 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
4013 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
4014 return handle_handshake_msg(ctx, peer, session, role, state, data,
4017 dtls_warn("ignore unexpected handshake message\n");
4022 if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
4023 dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
4024 peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
4026 } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
4027 /* A packet in between is missing, buffer this packet. */
4030 /* TODO: only add packet that are not too new. */
4031 if (data_length > DTLS_MAX_BUF) {
4032 dtls_warn("the packet is too big to buffer for reoder\n");
4036 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4038 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4039 if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
4040 dtls_warn("a packet with this sequence number is already stored\n");
4043 node = netq_next(node);
4046 n = netq_node_new(data_length);
4048 dtls_warn("no space in reoder buffer\n");
4053 n->length = data_length;
4054 memcpy(n->data, data, data_length);
4056 if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
4057 dtls_warn("cannot add packet to reoder buffer\n");
4060 dtls_info("Added packet for reordering\n");
4062 } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4063 /* Found the expected packet, use this and all the buffered packet */
4066 res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
4070 /* We do not know in which order the packet are in the list just search the list for every packet. */
4071 while (next && peer->handshake_params) {
4073 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4075 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4077 if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4078 netq_remove(peer->handshake_params->reorder_queue, node);
4080 res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
4087 node = netq_next(node);
4098 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
4099 uint8 *record_header, uint8 *data, size_t data_length)
4102 dtls_handshake_parameters_t *handshake = peer->handshake_params;
4104 /* A CCS message is handled after a KeyExchange message was
4105 * received from the client. When security parameters have been
4106 * updated successfully and a ChangeCipherSpec message was sent
4107 * by ourself, the security context is switched and the record
4108 * sequence number is reset. */
4110 if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
4111 dtls_warn("expected ChangeCipherSpec during handshake\n");
4115 if (data_length < 1 || data[0] != 1)
4116 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4118 /* Just change the cipher when we are on the same epoch */
4119 if (peer->role == DTLS_SERVER) {
4120 err = calculate_key_block(ctx, handshake, peer,
4121 &peer->session, peer->role);
4127 peer->state = DTLS_STATE_WAIT_FINISHED;
4133 * Handles incoming Alert messages. This function returns \c 1 if the
4134 * connection should be closed and the peer is to be invalidated.
4137 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
4138 uint8 *record_header, uint8 *data, size_t data_length) {
4139 int free_peer = 0; /* indicates whether to free peer */
4141 if (data_length < 2)
4142 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4144 dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
4147 dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
4151 /* The peer object is invalidated for FATAL alerts and close
4152 * notifies. This is done in two steps.: First, remove the object
4153 * from our list of peers. After that, the event handler callback is
4154 * invoked with the still existing peer object. Finally, the storage
4155 * used by peer is released.
4157 if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
4158 dtls_alert("%d invalidate peer\n", data[1]);
4160 #ifndef WITH_CONTIKI
4161 HASH_DEL_PEER(ctx->peers, peer);
4162 #else /* WITH_CONTIKI */
4163 list_remove(ctx->peers, peer);
4166 PRINTF("removed peer [");
4167 PRINT6ADDR(&peer->session.addr);
4168 PRINTF("]:%d\n", uip_ntohs(peer->session.port));
4170 #endif /* WITH_CONTIKI */
4176 (void)CALL(ctx, event, &peer->session,
4177 (dtls_alert_level_t)data[0], (unsigned short)data[1]);
4179 case DTLS_ALERT_CLOSE_NOTIFY:
4180 /* If state is DTLS_STATE_CLOSING, we have already sent a
4181 * close_notify so, do not send that again. */
4182 if (peer->state != DTLS_STATE_CLOSING) {
4183 peer->state = DTLS_STATE_CLOSING;
4184 dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
4186 peer->state = DTLS_STATE_CLOSED;
4193 dtls_stop_retransmission(ctx, peer);
4194 dtls_destroy_peer(ctx, peer, 0);
4200 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
4201 session_t *session, int err)
4206 if (err < -(1 << 8) && err > -(3 << 8)) {
4207 level = ((-err) & 0xff00) >> 8;
4208 desc = (-err) & 0xff;
4210 peer = dtls_get_peer(ctx, session);
4213 peer->state = DTLS_STATE_CLOSING;
4214 return dtls_send_alert(ctx, peer, level, desc);
4216 } else if (err == -1) {
4218 peer = dtls_get_peer(ctx, session);
4221 peer->state = DTLS_STATE_CLOSING;
4222 return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
4229 * Handles incoming data as DTLS message from given peer.
4232 dtls_handle_message(dtls_context_t *ctx,
4234 uint8 *msg, int msglen) {
4235 dtls_peer_t *peer = NULL;
4236 unsigned int rlen; /* record length */
4237 uint8 *data; /* (decrypted) payload */
4238 int data_length; /* length of decrypted payload
4239 (without MAC and padding) */
4242 /* check if we have DTLS state for addr/port/ifindex */
4243 peer = dtls_get_peer(ctx, session);
4246 dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
4247 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
4249 dtls_debug("dtls_handle_message: FOUND PEER\n");
4252 while ((rlen = is_record(msg,msglen))) {
4253 dtls_peer_type role;
4256 dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
4258 data_length = decrypt_verify(peer, msg, rlen, &data);
4259 if (data_length < 0) {
4260 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4261 data = msg + DTLS_RH_LENGTH;
4262 data_length = rlen - DTLS_RH_LENGTH;
4263 state = DTLS_STATE_WAIT_CLIENTHELLO;
4266 int err = dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
4267 dtls_info("decrypt_verify() failed\n");
4268 if (peer->state < DTLS_STATE_CONNECTED) {
4269 dtls_alert_send_from_err(ctx, peer, &peer->session, err);
4270 peer->state = DTLS_STATE_CLOSED;
4271 /* dtls_stop_retransmission(ctx, peer); */
4272 dtls_destroy_peer(ctx, peer, 1);
4278 state = peer->state;
4281 /* is_record() ensures that msg contains at least a record header */
4282 data = msg + DTLS_RH_LENGTH;
4283 data_length = rlen - DTLS_RH_LENGTH;
4284 state = DTLS_STATE_WAIT_CLIENTHELLO;
4288 dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
4289 dtls_debug_hexdump("receive unencrypted", data, data_length);
4291 /* Handle received record according to the first byte of the
4292 * message, i.e. the subprotocol. We currently do not support
4293 * combining multiple fragments of one type into a single
4298 case DTLS_CT_CHANGE_CIPHER_SPEC:
4300 dtls_stop_retransmission(ctx, peer);
4302 err = handle_ccs(ctx, peer, msg, data, data_length);
4304 dtls_warn("error while handling ChangeCipherSpec message\n");
4305 dtls_alert_send_from_err(ctx, peer, session, err);
4307 /* invalidate peer */
4308 dtls_destroy_peer(ctx, peer, 1);
4317 dtls_stop_retransmission(ctx, peer);
4319 err = handle_alert(ctx, peer, msg, data, data_length);
4320 if (err < 0 || err == 1) {
4321 dtls_warn("received alert, peer has been invalidated\n");
4322 /* handle alert has invalidated peer */
4324 return err < 0 ?err:-1;
4328 case DTLS_CT_HANDSHAKE:
4329 /* Handshake messages other than Finish must use the current
4330 * epoch, Finish has epoch + 1. */
4333 uint16_t expected_epoch = dtls_security_params(peer)->epoch;
4334 uint16_t msg_epoch =
4335 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
4337 /* The new security parameters must be used for all messages
4338 * that are sent after the ChangeCipherSpec message. This
4339 * means that the client's Finished message uses epoch + 1
4340 * while the server is still in the old epoch.
4342 if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
4346 if (expected_epoch != msg_epoch) {
4347 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4348 state = DTLS_STATE_WAIT_CLIENTHELLO;
4351 dtls_warn("Wrong epoch, expected %i, got: %i\n",
4352 expected_epoch, msg_epoch);
4358 err = handle_handshake(ctx, peer, session, role, state, data, data_length);
4360 dtls_warn("error while handling handshake packet\n");
4361 dtls_alert_send_from_err(ctx, peer, session, err);
4364 if (peer && peer->state == DTLS_STATE_CONNECTED) {
4365 /* stop retransmissions */
4366 dtls_stop_retransmission(ctx, peer);
4367 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
4371 case DTLS_CT_APPLICATION_DATA:
4372 dtls_info("** application data:\n");
4374 dtls_warn("no peer available, send an alert\n");
4375 // TODO: should we send a alert here?
4378 dtls_stop_retransmission(ctx, peer);
4379 CALL(ctx, read, &peer->session, data, data_length);
4382 dtls_info("dropped unknown message of type %d\n",msg[0]);
4385 /* advance msg by length of ciphertext */
4394 dtls_new_context(void *app_data) {
4397 #ifndef WITH_CONTIKI
4398 FILE *urandom = fopen("/dev/urandom", "r");
4399 unsigned char buf[sizeof(unsigned long)];
4400 #endif /* WITH_CONTIKI */
4404 /* FIXME: need something better to init PRNG here */
4405 dtls_prng_init(now);
4406 #else /* WITH_CONTIKI */
4408 dtls_emerg("cannot initialize PRNG\n");
4412 if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
4413 dtls_emerg("cannot initialize PRNG\n");
4418 dtls_prng_init((unsigned long)*buf);
4419 #endif /* WITH_CONTIKI */
4421 c = malloc_context();
4425 memset(c, 0, sizeof(dtls_context_t));
4428 LIST_STRUCT_INIT(c, sendqueue);
4431 LIST_STRUCT_INIT(c, peers);
4432 /* LIST_STRUCT_INIT(c, key_store); */
4434 process_start(&dtls_retransmit_process, (char *)c);
4435 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
4436 /* the retransmit timer must be initialized to some large value */
4437 etimer_set(&c->retransmit_timer, 0xFFFF);
4438 PROCESS_CONTEXT_END(&coap_retransmit_process);
4439 #endif /* WITH_CONTIKI */
4441 if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
4442 c->cookie_secret_age = now;
4449 dtls_alert("cannot create DTLS context\n");
4451 dtls_free_context(c);
4456 dtls_free_context(dtls_context_t *ctx) {
4463 #ifndef WITH_CONTIKI
4467 HASH_ITER(hh, ctx->peers, p, tmp) {
4468 dtls_destroy_peer(ctx, p, 1);
4471 #else /* WITH_CONTIKI */
4472 for (p = list_head(ctx->peers); p; p = list_item_next(p))
4473 dtls_destroy_peer(ctx, p, 1);
4474 #endif /* WITH_CONTIKI */
4480 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
4487 /* check if the same peer is already in our list */
4488 if (peer == dtls_get_peer(ctx, &peer->session)) {
4489 dtls_debug("found peer, try to re-connect\n");
4490 return dtls_renegotiate(ctx, &peer->session);
4493 /* set local peer role to client, remote is server */
4494 peer->role = DTLS_CLIENT;
4496 dtls_add_peer(ctx, peer);
4498 /* send ClientHello with empty Cookie */
4499 peer->handshake_params = dtls_handshake_new();
4500 if (!peer->handshake_params)
4503 peer->handshake_params->hs_state.mseq_r = 0;
4504 peer->handshake_params->hs_state.mseq_s = 0;
4505 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4506 res = dtls_send_client_hello(ctx, peer, NULL, 0);
4508 dtls_warn("cannot send ClientHello\n");
4510 peer->state = DTLS_STATE_CLIENTHELLO;
4516 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
4520 peer = dtls_get_peer(ctx, dst);
4523 peer = dtls_new_peer(dst);
4526 dtls_crit("cannot create new peer\n");
4530 res = dtls_connect_peer(ctx, peer);
4532 /* Invoke event callback to indicate connection attempt or
4533 * re-negotiation. */
4535 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
4536 } else if (res == 0) {
4537 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
4544 dtls_retransmit(dtls_context_t *context, netq_t *node) {
4545 if (!context || !node)
4548 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
4549 if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
4550 unsigned char sendbuf[DTLS_MAX_BUF];
4551 size_t len = sizeof(sendbuf);
4553 unsigned char *data = node->data;
4554 size_t length = node->length;
4556 dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
4559 node->retransmit_cnt++;
4560 node->t = now + (node->timeout << node->retransmit_cnt);
4561 netq_insert_node(context->sendqueue, node);
4563 if (node->type == DTLS_CT_HANDSHAKE) {
4564 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4566 dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
4567 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4569 dtls_debug("** retransmit packet\n");
4572 err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
4575 dtls_warn("can not retransmit packet, err: %i\n", err);
4578 dtls_debug_hexdump("retransmit header", sendbuf,
4579 sizeof(dtls_record_header_t));
4580 dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
4582 (void)CALL(context, write, &node->peer->session, sendbuf, len);
4586 /* no more retransmissions, remove node from system */
4588 dtls_debug("** removed transaction\n");
4590 /* And finally delete the node */
4591 netq_node_free(node);
4595 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4597 node = list_head(context->sendqueue);
4600 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4602 node = list_item_next(node);
4603 list_remove(context->sendqueue, tmp);
4604 netq_node_free(tmp);
4606 node = list_item_next(node);
4611 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
4613 netq_t *node = netq_head(context->sendqueue);
4616 while (node && node->t <= now) {
4617 netq_pop_first(context->sendqueue);
4618 dtls_retransmit(context, node);
4619 node = netq_head(context->sendqueue);
4627 dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
4628 const uint8_t* label, const uint32_t labellen,
4629 const uint8_t* random1, const uint32_t random1len,
4630 const uint8_t* random2, const uint32_t random2len,
4631 uint8_t* buf, const uint32_t buflen) {
4632 dtls_peer_t *peer = NULL;
4633 dtls_security_parameters_t *security = NULL;
4636 if(!ctx || !session || !label || !buf || labellen == 0 || buflen == 0) {
4637 dtls_warn("dtls_prf_with_current_keyblock(): invalid parameter\n");
4641 peer = dtls_get_peer(ctx, session);
4643 dtls_warn("dtls_prf_with_current_keyblock(): cannot find peer\n");
4647 security = dtls_security_params(peer);
4649 dtls_crit("dtls_prf_with_current_keyblock(): peer has empty security parameters\n");
4653 /* note that keysize should never be zero as bad things will happen */
4654 keysize = dtls_kb_size(security, peer->role);
4655 assert(keysize > 0);
4657 return dtls_prf(security->key_block, keysize,
4659 random1, random1len,
4660 random2, random2len,
4665 /*---------------------------------------------------------------------------*/
4666 /* message retransmission */
4667 /*---------------------------------------------------------------------------*/
4668 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4675 dtls_debug("Started DTLS retransmit process\r\n");
4679 if (ev == PROCESS_EVENT_TIMER) {
4680 if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4682 node = list_head(the_dtls_context.sendqueue);
4685 if (node && node->t <= now) {
4686 dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
4687 node = list_head(the_dtls_context.sendqueue);
4690 /* need to set timer to some value even if no nextpdu is available */
4692 etimer_set(&the_dtls_context.retransmit_timer,
4693 node->t <= now ? 1 : node->t - now);
4695 etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4703 #endif /* WITH_CONTIKI */