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)
482 #if defined(DTLS_ECC) || defined(DTLS_X509)
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 x509 */
543 static inline int is_x509_supported(dtls_context_t *ctx, int is_client)
546 return ctx && ctx->h && ((!is_client && ctx->h->get_x509_cert) ||
547 (is_client && ctx->h->verify_x509_cert));
550 #endif /* DTLS_X509 */
553 /** Returns true if the application is configured for ecdhe_ecdsa with
554 * client authentication */
555 static inline int is_ecdsa_client_auth_supported(dtls_context_t *ctx)
558 return ctx && ctx->h && ctx->h->get_ecdsa_key && ctx->h->verify_ecdsa_key;
561 #endif /* DTLS_ECC */
564 /** Returns true if the application is configured for x509 with
565 * client authentication */
566 static inline int is_x509_client_auth_supported(dtls_context_t *ctx)
569 return ctx && ctx->h && ctx->h->get_x509_cert && ctx->h->verify_x509_cert;
572 #endif /* DTLS_X509 */
575 /** returns true if ecdh_anon_with_aes_128_cbc_sha is supported */
576 static inline int is_ecdh_anon_supported(dtls_context_t *ctx)
579 return ctx && (ctx->is_anon_ecdh_eabled == DTLS_CIPHER_ENABLE);
585 /** returns true if ecdhe_psk_with_aes_128_cbc_sha_256 is supported */
586 static inline int is_ecdhe_psk_supported(dtls_context_t *ctx)
588 #if defined(DTLS_ECC) && defined(DTLS_PSK)
589 return is_psk_supported(ctx);
592 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
597 * Returns @c 1 if @p code is a cipher suite other than @c
598 * TLS_NULL_WITH_NULL_NULL that we recognize.
600 * @param ctx The current DTLS context
601 * @param code The cipher suite identifier to check
602 * @param is_client 1 for a dtls client, 0 for server
603 * @return @c 1 iff @p code is recognized,
606 known_cipher(dtls_context_t *ctx, dtls_cipher_t code, int is_client) {
613 psk = is_psk_supported(ctx);
614 ecdsa = is_ecdsa_supported(ctx, is_client);
615 ecdh_anon = is_ecdh_anon_supported(ctx);
616 ecdhe_psk = is_ecdhe_psk_supported(ctx);
617 x509 = is_x509_supported(ctx, is_client);
619 return (psk && is_tls_psk_with_aes_128_ccm_8(code)) ||
620 (ecdsa && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code)) ||
621 (ecdh_anon && is_tls_ecdh_anon_with_aes_128_cbc_sha_256(code)) ||
622 (ecdhe_psk && is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(code)) ||
623 (x509 && is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(code));
627 * This method detects if we already have a established DTLS session with
628 * peer and the peer is attempting to perform a fresh handshake by sending
629 * messages with epoch = 0. This is to handle situations mentioned in
630 * RFC 6347 - section 4.2.8.
632 * @param msg The packet received from Client
633 * @param msglen Packet length
634 * @param peer peer who is the sender for this packet
635 * @return @c 1 if this is a rehandshake attempt by
639 hs_attempt_with_existing_peer(uint8_t *msg, size_t msglen,
642 if ((peer) && (peer->state == DTLS_STATE_CONNECTED)) {
643 if (msg[0] == DTLS_CT_HANDSHAKE) {
644 uint16_t msg_epoch = dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
645 if (msg_epoch == 0) {
646 dtls_handshake_header_t * hs_header = DTLS_HANDSHAKE_HEADER(msg + DTLS_RH_LENGTH);
647 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
648 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
657 /** Dump out the cipher keys and IVs used for the symetric cipher. */
658 static void dtls_debug_keyblock(dtls_security_parameters_t *config)
660 dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
661 dtls_debug_dump(" client_MAC_secret",
662 dtls_kb_client_mac_secret(config, peer->role),
663 dtls_kb_mac_secret_size(config, peer->role));
665 dtls_debug_dump(" server_MAC_secret",
666 dtls_kb_server_mac_secret(config, peer->role),
667 dtls_kb_mac_secret_size(config, peer->role));
669 dtls_debug_dump(" client_write_key",
670 dtls_kb_client_write_key(config, peer->role),
671 dtls_kb_key_size(config, peer->role));
673 dtls_debug_dump(" server_write_key",
674 dtls_kb_server_write_key(config, peer->role),
675 dtls_kb_key_size(config, peer->role));
677 dtls_debug_dump(" client_IV",
678 dtls_kb_client_iv(config, peer->role),
679 dtls_kb_iv_size(config, peer->role));
681 dtls_debug_dump(" server_IV",
682 dtls_kb_server_iv(config, peer->role),
683 dtls_kb_iv_size(config, peer->role));
686 /** returns the name of the goven handshake type number.
687 * see IANA for a full list of types:
688 * https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-7
690 static char *dtls_handshake_type_to_name(int type)
693 case DTLS_HT_HELLO_REQUEST:
694 return "hello_request";
695 case DTLS_HT_CLIENT_HELLO:
696 return "client_hello";
697 case DTLS_HT_SERVER_HELLO:
698 return "server_hello";
699 case DTLS_HT_HELLO_VERIFY_REQUEST:
700 return "hello_verify_request";
701 case DTLS_HT_CERTIFICATE:
702 return "certificate";
703 case DTLS_HT_SERVER_KEY_EXCHANGE:
704 return "server_key_exchange";
705 case DTLS_HT_CERTIFICATE_REQUEST:
706 return "certificate_request";
707 case DTLS_HT_SERVER_HELLO_DONE:
708 return "server_hello_done";
709 case DTLS_HT_CERTIFICATE_VERIFY:
710 return "certificate_verify";
711 case DTLS_HT_CLIENT_KEY_EXCHANGE:
712 return "client_key_exchange";
713 case DTLS_HT_FINISHED:
721 * Calculate the pre master secret and after that calculate the master-secret.
724 calculate_key_block(dtls_context_t *ctx,
725 dtls_handshake_parameters_t *handshake,
728 dtls_peer_type role) {
729 #if defined(DTLS_PSK) && defined(DTLS_ECC)
730 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH + uECC_BYTES];
732 unsigned char pre_master_secret[MAX_KEYBLOCK_LENGTH];
733 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
734 int pre_master_len = 0;
735 dtls_security_parameters_t *security = dtls_security_params_next(peer);
736 uint8 master_secret[DTLS_MASTER_SECRET_LENGTH];
739 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
742 switch (handshake->cipher) {
744 case TLS_PSK_WITH_AES_128_CCM_8: {
745 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
748 len = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
749 handshake->keyx.psk.identity,
750 handshake->keyx.psk.id_length,
751 psk, DTLS_PSK_MAX_KEY_LEN);
753 dtls_crit("no psk key for session available\n");
756 /* Temporarily use the key_block storage space for the pre master secret. */
757 pre_master_len = dtls_psk_pre_master_secret(psk, len,
759 MAX_KEYBLOCK_LENGTH);
761 dtls_debug_hexdump("psk", psk, len);
763 memset(psk, 0, DTLS_PSK_MAX_KEY_LEN);
764 if (pre_master_len < 0) {
765 dtls_crit("the psk was too long, for the pre master secret\n");
766 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
771 #endif /* DTLS_PSK */
772 #if defined(DTLS_ECC) || defined(DTLS_X509)
773 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
774 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
775 pre_master_len = dtls_ecdh_pre_master_secret(handshake->keyx.ecc.own_eph_priv,
776 handshake->keyx.ecc.other_eph_pub_x,
777 handshake->keyx.ecc.other_eph_pub_y,
778 sizeof(handshake->keyx.ecc.own_eph_priv),
780 MAX_KEYBLOCK_LENGTH);
781 if (pre_master_len < 0) {
782 dtls_crit("the curve was too long, for the pre master secret\n");
783 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
787 #endif /* DTLS_ECC */
788 #if defined(DTLS_PSK) && defined(DTLS_ECC)
789 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
790 unsigned char psk[DTLS_PSK_MAX_KEY_LEN];
793 psklen = CALL(ctx, get_psk_info, session, DTLS_PSK_KEY,
794 handshake->keyx.psk.identity,
795 handshake->keyx.psk.id_length,
796 psk, DTLS_PSK_MAX_KEY_LEN);
798 dtls_crit("no psk key for session available\n");
802 pre_master_len = dtls_ecdhe_psk_pre_master_secret(psk, psklen,
803 handshake->keyx.ecc.own_eph_priv,
804 handshake->keyx.ecc.other_eph_pub_x,
805 handshake->keyx.ecc.other_eph_pub_y,
806 sizeof(handshake->keyx.ecc.own_eph_priv),
808 MAX_KEYBLOCK_LENGTH + uECC_BYTES);
810 if (pre_master_len < 0) {
811 dtls_crit("the curve was too long, for the pre master secret\n");
812 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
816 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
818 dtls_crit("calculate_key_block: unknown cipher\n");
819 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
822 dtls_debug_dump("client_random", handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
823 dtls_debug_dump("server_random", handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
824 dtls_debug_dump("pre_master_secret", pre_master_secret, pre_master_len);
826 dtls_prf(pre_master_secret, pre_master_len,
827 PRF_LABEL(master), PRF_LABEL_SIZE(master),
828 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
829 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
831 DTLS_MASTER_SECRET_LENGTH);
833 dtls_debug_dump("master_secret", master_secret, DTLS_MASTER_SECRET_LENGTH);
835 /* create key_block from master_secret
836 * key_block = PRF(master_secret,
837 "key expansion" + tmp.random.server + tmp.random.client) */
839 dtls_prf(master_secret,
840 DTLS_MASTER_SECRET_LENGTH,
841 PRF_LABEL(key), PRF_LABEL_SIZE(key),
842 handshake->tmp.random.server, DTLS_RANDOM_LENGTH,
843 handshake->tmp.random.client, DTLS_RANDOM_LENGTH,
845 dtls_kb_size(security, role));
847 memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
848 dtls_debug_keyblock(security);
850 security->cipher = handshake->cipher;
851 security->compression = handshake->compression;
857 /* TODO: add a generic method which iterates over a list and searches for a specific key */
858 static int verify_ext_eliptic_curves(uint8 *data, size_t data_length) {
861 /* length of curve list */
862 i = dtls_uint16_to_int(data);
863 data += sizeof(uint16);
864 if (i + sizeof(uint16) != data_length) {
865 dtls_warn("the list of the supported elliptic curves should be tls extension length - 2\n");
866 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
869 for (i = data_length - sizeof(uint16); i > 0; i -= sizeof(uint16)) {
870 /* check if this curve is supported */
871 curve_name = dtls_uint16_to_int(data);
872 data += sizeof(uint16);
874 if (curve_name == TLS_EXT_ELLIPTIC_CURVES_SECP256R1)
878 dtls_warn("no supported elliptic curve found\n");
879 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
882 static int verify_ext_cert_type(uint8 *data, size_t data_length) {
885 /* length of cert type list */
886 i = dtls_uint8_to_int(data);
887 data += sizeof(uint8);
888 if (i + sizeof(uint8) != data_length) {
889 dtls_warn("the list of the supported certificate types should be tls extension length - 1\n");
890 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
893 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
894 /* check if this cert type is supported */
895 cert_type = dtls_uint8_to_int(data);
896 data += sizeof(uint8);
899 if (cert_type == TLS_CERT_TYPE_RAW_PUBLIC_KEY)
902 if (cert_type == TLS_CERT_TYPE_X509)
907 dtls_warn("no supported certificate type found\n");
908 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
911 static int verify_ext_ec_point_formats(uint8 *data, size_t data_length) {
914 /* length of ec_point_formats list */
915 i = dtls_uint8_to_int(data);
916 data += sizeof(uint8);
917 if (i + sizeof(uint8) != data_length) {
918 dtls_warn("the list of the supported ec_point_formats should be tls extension length - 1\n");
919 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
922 for (i = data_length - sizeof(uint8); i > 0; i -= sizeof(uint8)) {
923 /* check if this ec_point_format is supported */
924 cert_type = dtls_uint8_to_int(data);
925 data += sizeof(uint8);
927 if (cert_type == TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED)
931 dtls_warn("no supported ec_point_format found\n");
932 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
936 * Check for some TLS Extensions used by the ECDHE_ECDSA cipher.
939 dtls_check_tls_extension(dtls_peer_t *peer,
940 uint8 *data, size_t data_length, int client_hello)
943 int ext_elliptic_curve = 0;
944 int ext_client_cert_type = 0;
945 int ext_server_cert_type = 0;
946 int ext_ec_point_formats = 0;
947 dtls_handshake_parameters_t *handshake = peer->handshake_params;
949 if (data_length < sizeof(uint16)) {
950 /* no tls extensions specified */
951 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher)) {
957 /* get the length of the tls extension list */
958 j = dtls_uint16_to_int(data);
959 data += sizeof(uint16);
960 data_length -= sizeof(uint16);
965 /* check for TLS extensions needed for this cipher */
966 while (data_length) {
967 if (data_length < sizeof(uint16) * 2)
970 /* get the tls extension type */
971 i = dtls_uint16_to_int(data);
972 data += sizeof(uint16);
973 data_length -= sizeof(uint16);
975 /* get the length of the tls extension */
976 j = dtls_uint16_to_int(data);
977 data += sizeof(uint16);
978 data_length -= sizeof(uint16);
984 case TLS_EXT_ELLIPTIC_CURVES:
985 ext_elliptic_curve = 1;
986 if (verify_ext_eliptic_curves(data, j))
989 case TLS_EXT_CLIENT_CERTIFICATE_TYPE:
990 ext_client_cert_type = 1;
992 if (verify_ext_cert_type(data, j))
996 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
998 if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
999 (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1004 case TLS_EXT_SERVER_CERTIFICATE_TYPE:
1005 ext_server_cert_type = 1;
1007 if (verify_ext_cert_type(data, j))
1011 if (dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY)
1013 if ((dtls_uint8_to_int(data) != TLS_CERT_TYPE_RAW_PUBLIC_KEY) &&
1014 (dtls_uint8_to_int(data) != TLS_CERT_TYPE_X509))
1019 case TLS_EXT_EC_POINT_FORMATS:
1020 ext_ec_point_formats = 1;
1021 if (verify_ext_ec_point_formats(data, j))
1024 case TLS_EXT_ENCRYPT_THEN_MAC:
1025 /* As only AEAD cipher suites are currently available, this
1026 * extension can be skipped.
1028 dtls_info("skipped encrypt-then-mac extension\n");
1031 dtls_warn("unsupported tls extension: %i\n", i);
1037 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && client_hello) {
1038 if (!ext_elliptic_curve || !ext_client_cert_type || !ext_server_cert_type
1039 || !ext_ec_point_formats) {
1040 dtls_warn("not all required tls extensions found in client hello\n");
1043 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && !client_hello) {
1044 if (!ext_client_cert_type || !ext_server_cert_type) {
1045 dtls_warn("not all required tls extensions found in server hello\n");
1052 if (client_hello && peer->state == DTLS_STATE_CONNECTED) {
1053 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1055 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1060 * Parses the ClientHello from the client and updates the internal handshake
1061 * parameters with the new data for the given \p peer. When the ClientHello
1062 * handshake message in \p data does not contain a cipher suite or
1063 * compression method, it is copied from the the current security parameters.
1065 * \param ctx The current DTLS context.
1066 * \param peer The remote peer whose security parameters are about to change.
1067 * \param data The handshake message with a ClientHello.
1068 * \param data_length The actual size of \p data.
1069 * \return \c -Something if an error occurred, \c 0 on success.
1072 dtls_update_parameters(dtls_context_t *ctx,
1074 uint8 *data, size_t data_length) {
1077 dtls_handshake_parameters_t *config = peer->handshake_params;
1078 dtls_security_parameters_t *security = dtls_security_params(peer);
1081 assert(data_length > DTLS_HS_LENGTH + DTLS_CH_LENGTH);
1083 /* skip the handshake header and client version information */
1084 data += DTLS_HS_LENGTH + sizeof(uint16);
1085 data_length -= DTLS_HS_LENGTH + sizeof(uint16);
1087 /* store client random in config */
1088 memcpy(config->tmp.random.client, data, DTLS_RANDOM_LENGTH);
1089 data += DTLS_RANDOM_LENGTH;
1090 data_length -= DTLS_RANDOM_LENGTH;
1092 /* Caution: SKIP_VAR_FIELD may jump to error: */
1093 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
1094 SKIP_VAR_FIELD(data, data_length, uint8); /* skip cookie */
1096 i = dtls_uint16_to_int(data);
1097 if (data_length < i + sizeof(uint16)) {
1098 /* Looks like we do not have a cipher nor compression. This is ok
1099 * for renegotiation, but not for the initial handshake. */
1101 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL)
1104 config->cipher = security->cipher;
1105 config->compression = security->compression;
1110 data += sizeof(uint16);
1111 data_length -= sizeof(uint16) + i;
1115 config->cipher = dtls_uint16_to_int(data);
1116 ok = known_cipher(ctx, config->cipher, 0);
1117 i -= sizeof(uint16);
1118 data += sizeof(uint16);
1121 /* skip remaining ciphers */
1125 /* reset config cipher to a well-defined value */
1126 config->cipher = TLS_NULL_WITH_NULL_NULL;
1127 dtls_warn("No matching cipher found\n");
1131 if (data_length < sizeof(uint8)) {
1132 /* no compression specified, take the current compression method */
1134 config->compression = security->compression;
1136 config->compression = TLS_COMPRESSION_NULL;
1140 i = dtls_uint8_to_int(data);
1141 if (data_length < i + sizeof(uint8))
1144 data += sizeof(uint8);
1145 data_length -= sizeof(uint8) + i;
1149 for (j = 0; j < sizeof(compression_methods) / sizeof(uint8); ++j)
1150 if (dtls_uint8_to_int(data) == compression_methods[j]) {
1151 config->compression = compression_methods[j];
1155 data += sizeof(uint8);
1159 /* reset config cipher to a well-defined value */
1163 return dtls_check_tls_extension(peer, data, data_length, 1);
1165 if (peer->state == DTLS_STATE_CONNECTED) {
1166 return dtls_alert_create(DTLS_ALERT_LEVEL_WARNING, DTLS_ALERT_NO_RENEGOTIATION);
1168 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1173 * Parse the ClientKeyExchange and update the internal handshake state with
1177 check_client_keyexchange(dtls_context_t *ctx,
1178 dtls_handshake_parameters_t *handshake,
1179 uint8 *data, size_t length) {
1181 #if defined(DTLS_ECC) || defined(DTLS_X509)
1182 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) ||
1183 is_tls_ecdh_anon_with_aes_128_cbc_sha_256(handshake->cipher) ) {
1185 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1186 dtls_debug("The client key exchange is too short\n");
1187 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1189 data += DTLS_HS_LENGTH;
1191 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1192 dtls_alert("expected 65 bytes long public point\n");
1193 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1195 data += sizeof(uint8);
1197 if (dtls_uint8_to_int(data) != 4) {
1198 dtls_alert("expected uncompressed public point\n");
1199 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1201 data += sizeof(uint8);
1203 memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1204 sizeof(handshake->keyx.ecc.other_eph_pub_x));
1205 data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1207 memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1208 sizeof(handshake->keyx.ecc.other_eph_pub_y));
1209 data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1211 #endif /* DTLS_ECC */
1212 #if defined(DTLS_PSK) && defined(DTLS_ECC)
1213 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(handshake->cipher)) {
1216 if (length < DTLS_HS_LENGTH + DTLS_CKXEC_LENGTH) {
1217 dtls_debug("The client key exchange is too short\n");
1218 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1220 data += DTLS_HS_LENGTH;
1223 id_length = dtls_uint16_to_int(data);
1224 data += sizeof(uint16);
1226 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + DTLS_CKXEC_LENGTH + id_length != length) {
1227 dtls_debug("The identity has a wrong length\n");
1228 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1231 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1232 dtls_warn("please use a smaller client identity\n");
1233 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1236 handshake->keyx.psk.id_length = id_length;
1237 memcpy(handshake->keyx.psk.identity, data, id_length);
1241 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
1242 dtls_alert("expected 65 bytes long public point\n");
1243 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1245 data += sizeof(uint8);
1247 if (dtls_uint8_to_int(data) != 4) {
1248 dtls_alert("expected uncompressed public point\n");
1249 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1251 data += sizeof(uint8);
1253 memcpy(handshake->keyx.ecc.other_eph_pub_x, data,
1254 sizeof(handshake->keyx.ecc.other_eph_pub_x));
1255 data += sizeof(handshake->keyx.ecc.other_eph_pub_x);
1257 memcpy(handshake->keyx.ecc.other_eph_pub_y, data,
1258 sizeof(handshake->keyx.ecc.other_eph_pub_y));
1259 data += sizeof(handshake->keyx.ecc.other_eph_pub_y);
1261 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
1263 if (is_tls_psk_with_aes_128_ccm_8(handshake->cipher)) {
1266 if (length < DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN) {
1267 dtls_debug("The client key exchange is too short\n");
1268 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1270 data += DTLS_HS_LENGTH;
1272 id_length = dtls_uint16_to_int(data);
1273 data += sizeof(uint16);
1275 if (DTLS_HS_LENGTH + DTLS_CKXPSK_LENGTH_MIN + id_length != length) {
1276 dtls_debug("The identity has a wrong length\n");
1277 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1280 if (id_length > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
1281 dtls_warn("please use a smaller client identity\n");
1282 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1285 handshake->keyx.psk.id_length = id_length;
1286 memcpy(handshake->keyx.psk.identity, data, id_length);
1288 #endif /* DTLS_PSK */
1293 update_hs_hash(dtls_peer_t *peer, uint8 *data, size_t length) {
1294 dtls_debug_dump("add MAC data", data, length);
1295 dtls_hash_update(&peer->handshake_params->hs_state.hs_hash, data, length);
1299 copy_hs_hash(dtls_peer_t *peer, dtls_hash_ctx *hs_hash) {
1300 memcpy(hs_hash, &peer->handshake_params->hs_state.hs_hash,
1301 sizeof(peer->handshake_params->hs_state.hs_hash));
1304 static inline size_t
1305 finalize_hs_hash(dtls_peer_t *peer, uint8 *buf) {
1306 return dtls_hash_finalize(buf, &peer->handshake_params->hs_state.hs_hash);
1310 clear_hs_hash(dtls_peer_t *peer) {
1312 dtls_debug("clear MAC\n");
1313 dtls_hash_init(&peer->handshake_params->hs_state.hs_hash);
1317 * Checks if \p record + \p data contain a Finished message with valid
1320 * \param ctx The current DTLS context.
1321 * \param peer The remote peer of the security association.
1322 * \param data The cleartext payload of the message.
1323 * \param data_length Actual length of \p data.
1324 * \return \c 0 if the Finished message is valid, \c negative number otherwise.
1327 check_finished(dtls_context_t *ctx, dtls_peer_t *peer,
1328 uint8 *data, size_t data_length) {
1329 size_t digest_length, label_size;
1330 const unsigned char *label;
1331 unsigned char buf[DTLS_HMAC_MAX];
1333 if (data_length < DTLS_HS_LENGTH + DTLS_FIN_LENGTH)
1334 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1336 /* Use a union here to ensure that sufficient stack space is
1337 * reserved. As statebuf and verify_data are not used at the same
1338 * time, we can re-use the storage safely.
1341 unsigned char statebuf[DTLS_HASH_CTX_SIZE];
1342 unsigned char verify_data[DTLS_FIN_LENGTH];
1345 /* temporarily store hash status for roll-back after finalize */
1346 memcpy(b.statebuf, &peer->handshake_params->hs_state.hs_hash, DTLS_HASH_CTX_SIZE);
1348 digest_length = finalize_hs_hash(peer, buf);
1351 /* restore hash status */
1352 memcpy(&peer->handshake_params->hs_state.hs_hash, b.statebuf, DTLS_HASH_CTX_SIZE);
1354 if (peer->role == DTLS_CLIENT) {
1355 label = PRF_LABEL(server);
1356 label_size = PRF_LABEL_SIZE(server);
1357 } else { /* server */
1358 label = PRF_LABEL(client);
1359 label_size = PRF_LABEL_SIZE(client);
1362 dtls_prf(peer->handshake_params->tmp.master_secret,
1363 DTLS_MASTER_SECRET_LENGTH,
1365 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
1367 b.verify_data, sizeof(b.verify_data));
1369 dtls_debug_dump("d:", data + DTLS_HS_LENGTH, sizeof(b.verify_data));
1370 dtls_debug_dump("v:", b.verify_data, sizeof(b.verify_data));
1372 /* compare verify data and create DTLS alert code when they differ */
1373 return equals(data + DTLS_HS_LENGTH, b.verify_data, sizeof(b.verify_data))
1375 : dtls_alert_create(DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_HANDSHAKE_FAILURE);
1379 * Prepares the payload given in \p data for sending with
1380 * dtls_send(). The \p data is encrypted and compressed according to
1381 * the current security parameters of \p peer. The result of this
1382 * operation is put into \p sendbuf with a prepended record header of
1383 * type \p type ready for sending. As some cipher suites add a MAC
1384 * before encryption, \p data must be large enough to hold this data
1385 * as well (usually \c dtls_kb_digest_size(CURRENT_CONFIG(peer)).
1387 * \param peer The remote peer the packet will be sent to.
1388 * \param security The encryption paramater used to encrypt
1389 * \param type The content type of this record.
1390 * \param data_array Array with payloads in correct order.
1391 * \param data_len_array sizes of the payloads in correct order.
1392 * \param data_array_len The number of payloads given.
1393 * \param sendbuf The output buffer where the encrypted record
1395 * \param rlen This parameter must be initialized with the
1396 * maximum size of \p sendbuf and will be updated
1397 * to hold the actual size of the stored packet
1398 * on success. On error, the value of \p rlen is
1400 * \return Less than zero on error, or greater than zero success.
1403 dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
1405 uint8 *data_array[], size_t data_len_array[],
1406 size_t data_array_len,
1407 uint8 *sendbuf, size_t *rlen) {
1412 if (*rlen < DTLS_RH_LENGTH) {
1413 dtls_alert("The sendbuf (%zu bytes) is too small\n", *rlen);
1414 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1417 p = dtls_set_record_header(type, security, sendbuf);
1420 if (!security || security->cipher == TLS_NULL_WITH_NULL_NULL) {
1421 /* no cipher suite */
1424 for (i = 0; i < data_array_len; i++) {
1425 /* check the minimum that we need for packets that are not encrypted */
1426 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1427 dtls_debug("dtls_prepare_record: send buffer too small\n");
1428 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1431 memcpy(p, data_array[i], data_len_array[i]);
1432 p += data_len_array[i];
1433 res += data_len_array[i];
1435 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
1436 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
1438 unsigned char nonce[DTLS_CBC_IV_LENGTH];
1440 /** Add IV into body of packet in case of AES CBC mode according to RFC 5246, Section 6.2.3.2
1442 * opaque IV[SecurityParameters.record_iv_length];
1443 * block-ciphered struct {
1444 * opaque content[TLSCompressed.length];
1445 * opaque MAC[SecurityParameters.mac_length];
1446 * uint8 padding[GenericBlockCipher.padding_length];
1447 * uint8 padding_length;
1453 dtls_prng(nonce, DTLS_CBC_IV_LENGTH);
1454 memcpy(p , nonce, DTLS_CBC_IV_LENGTH);
1455 p += DTLS_CBC_IV_LENGTH;
1456 res += DTLS_CBC_IV_LENGTH;
1458 for (i = 0; i < data_array_len; i++) {
1459 /* check the minimum that we need for packets that are not encrypted */
1460 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1461 dtls_debug("dtls_prepare_record: send buffer too small\n");
1462 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1465 memcpy(p, data_array[i], data_len_array[i]);
1466 p += data_len_array[i];
1467 res += data_len_array[i];
1470 res = dtls_encrypt(start + DTLS_CBC_IV_LENGTH, res - DTLS_CBC_IV_LENGTH,
1471 start + DTLS_CBC_IV_LENGTH, nonce,
1472 dtls_kb_local_write_key(security, peer->role),
1473 dtls_kb_key_size(security, peer->role),
1479 res += DTLS_CBC_IV_LENGTH;
1481 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
1483 * length of additional_data for the AEAD cipher which consists of
1484 * seq_num(2+6) + type(1) + version(2) + length(2)
1486 #define A_DATA_LEN 13
1487 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
1488 unsigned char A_DATA[A_DATA_LEN];
1490 if (is_tls_psk_with_aes_128_ccm_8(security->cipher)) {
1491 dtls_debug("dtls_prepare_record(): encrypt using TLS_PSK_WITH_AES_128_CCM_8\n");
1492 } else if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(security->cipher)) {
1493 dtls_debug("dtls_prepare_record(): encrypt using TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n");
1495 dtls_debug("dtls_prepare_record(): encrypt using unknown cipher\n");
1500 The "nonce" input to the AEAD algorithm is exactly that of [RFC5288]:
1501 the "nonce" SHALL be 12 bytes long and is constructed as follows:
1502 (this is an example of a "partially explicit" nonce; see Section
1503 3.2.1 in [RFC5116]).
1507 opaque nonce_explicit[8];
1512 In DTLS, the 64-bit seq_num is the 16-bit epoch concatenated with the
1515 When the nonce_explicit is equal to the sequence number, the CCMNonce
1516 will have the structure of the CCMNonceExample given below.
1519 uint32 client_write_IV; // low order 32-bits
1520 uint64 seq_num; // TLS sequence number
1525 uint32 server_write_IV; // low order 32-bits
1526 uint64 seq_num; // TLS sequence number
1538 memcpy(p, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8);
1542 for (i = 0; i < data_array_len; i++) {
1543 /* check the minimum that we need for packets that are not encrypted */
1544 if (*rlen < res + DTLS_RH_LENGTH + data_len_array[i]) {
1545 dtls_debug("dtls_prepare_record: send buffer too small\n");
1546 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
1549 memcpy(p, data_array[i], data_len_array[i]);
1550 p += data_len_array[i];
1551 res += data_len_array[i];
1554 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
1555 memcpy(nonce, dtls_kb_local_iv(security, peer->role),
1556 dtls_kb_iv_size(security, peer->role));
1557 memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
1559 dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
1560 dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
1561 dtls_kb_key_size(security, peer->role));
1563 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
1565 * additional_data = seq_num + TLSCompressed.type +
1566 * TLSCompressed.version + TLSCompressed.length;
1568 memcpy(A_DATA, &DTLS_RECORD_HEADER(sendbuf)->epoch, 8); /* epoch and seq_num */
1569 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(sendbuf)->content_type, 3); /* type and version */
1570 dtls_int_to_uint16(A_DATA + 11, res - 8); /* length */
1572 res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
1573 dtls_kb_local_write_key(security, peer->role),
1574 dtls_kb_key_size(security, peer->role),
1581 res += 8; /* increment res by size of nonce_explicit */
1582 dtls_debug_dump("message:", start, res);
1585 /* fix length of fragment in sendbuf */
1586 dtls_int_to_uint16(sendbuf + 11, res);
1588 *rlen = DTLS_RH_LENGTH + res;
1593 dtls_send_handshake_msg_hash(dtls_context_t *ctx,
1597 uint8 *data, size_t data_length,
1600 uint8 buf[DTLS_HS_LENGTH];
1601 uint8 *data_array[2];
1602 size_t data_len_array[2];
1604 dtls_security_parameters_t *security = peer ? dtls_security_params(peer) : NULL;
1606 dtls_set_handshake_header(header_type, peer, data_length, 0,
1610 update_hs_hash(peer, buf, sizeof(buf));
1612 data_array[i] = buf;
1613 data_len_array[i] = sizeof(buf);
1618 update_hs_hash(peer, data, data_length);
1620 data_array[i] = data;
1621 data_len_array[i] = data_length;
1624 dtls_debug("send handshake packet of type: %s (%i)\n",
1625 dtls_handshake_type_to_name(header_type), header_type);
1626 return dtls_send_multi(ctx, peer, security, session, DTLS_CT_HANDSHAKE,
1627 data_array, data_len_array, i);
1631 dtls_send_handshake_msg(dtls_context_t *ctx,
1634 uint8 *data, size_t data_length)
1636 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
1637 header_type, data, data_length, 1);
1641 * Returns true if the message @p Data is a handshake message that
1642 * must be included in the calculation of verify_data in the Finished
1645 * @param Type The message type. Only handshake messages but the initial
1646 * Client Hello and Hello Verify Request are included in the hash,
1647 * @param Data The PDU to examine.
1648 * @param Length The length of @p Data.
1650 * @return @c 1 if @p Data must be included in hash, @c 0 otherwise.
1654 #define MUST_HASH(Type, Data, Length) \
1655 ((Type) == DTLS_CT_HANDSHAKE && \
1656 ((Data) != NULL) && ((Length) > 0) && \
1657 ((Data)[0] != DTLS_HT_HELLO_VERIFY_REQUEST) && \
1658 ((Data)[0] != DTLS_HT_CLIENT_HELLO || \
1659 ((Length) >= HS_HDR_LENGTH && \
1660 (dtls_uint16_to_int(DTLS_RECORD_HEADER(Data)->epoch > 0) || \
1661 (dtls_uint16_to_int(HANDSHAKE(Data)->message_seq) > 0)))))
1664 * Sends the data passed in @p buf as a DTLS record of type @p type to
1665 * the given peer. The data will be encrypted and compressed according
1666 * to the security parameters for @p peer.
1668 * @param ctx The DTLS context in effect.
1669 * @param peer The remote party where the packet is sent.
1670 * @param type The content type of this record.
1671 * @param buf The data to send.
1672 * @param buflen The number of bytes to send from @p buf.
1673 * @return Less than zero in case of an error or the number of
1674 * bytes that have been sent otherwise.
1677 dtls_send_multi(dtls_context_t *ctx, dtls_peer_t *peer,
1678 dtls_security_parameters_t *security , session_t *session,
1679 unsigned char type, uint8 *buf_array[],
1680 size_t buf_len_array[], size_t buf_array_len)
1682 /* We cannot use ctx->sendbuf here as it is reserved for collecting
1683 * the input for this function, i.e. buf == ctx->sendbuf.
1685 * TODO: check if we can use the receive buf here. This would mean
1686 * that we might not be able to handle multiple records stuffed in
1687 * one UDP datagram */
1688 unsigned char sendbuf[DTLS_MAX_BUF];
1689 size_t len = sizeof(sendbuf);
1692 size_t overall_len = 0;
1694 res = dtls_prepare_record(peer, security, type, buf_array, buf_len_array, buf_array_len, sendbuf, &len);
1699 /* if (peer && MUST_HASH(peer, type, buf, buflen)) */
1700 /* update_hs_hash(peer, buf, buflen); */
1702 dtls_debug_hexdump("send header", sendbuf, sizeof(dtls_record_header_t));
1703 for (i = 0; i < buf_array_len; i++) {
1704 dtls_debug_hexdump("send unencrypted", buf_array[i], buf_len_array[i]);
1705 overall_len += buf_len_array[i];
1708 if ((type == DTLS_CT_HANDSHAKE && buf_array[0][0] != DTLS_HT_HELLO_VERIFY_REQUEST) ||
1709 type == DTLS_CT_CHANGE_CIPHER_SPEC) {
1710 /* copy handshake messages other than HelloVerify into retransmit buffer */
1711 netq_t *n = netq_node_new(overall_len);
1715 n->t = now + 2 * CLOCK_SECOND;
1716 n->retransmit_cnt = 0;
1717 n->timeout = 2 * CLOCK_SECOND;
1719 n->epoch = (security) ? security->epoch : 0;
1722 for (i = 0; i < buf_array_len; i++) {
1723 memcpy(n->data + n->length, buf_array[i], buf_len_array[i]);
1724 n->length += buf_len_array[i];
1727 if (!netq_insert_node(ctx->sendqueue, n)) {
1728 dtls_warn("cannot add packet to retransmit buffer\n");
1732 /* must set timer within the context of the retransmit process */
1733 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
1734 etimer_set(&ctx->retransmit_timer, n->timeout);
1735 PROCESS_CONTEXT_END(&dtls_retransmit_process);
1736 #else /* WITH_CONTIKI */
1737 dtls_debug("copied to sendqueue\n");
1738 #endif /* WITH_CONTIKI */
1741 dtls_warn("retransmit buffer full\n");
1744 /* FIXME: copy to peer's sendqueue (after fragmentation if
1745 * necessary) and initialize retransmit timer */
1746 res = CALL(ctx, write, session, sendbuf, len);
1748 /* Guess number of bytes application data actually sent:
1749 * dtls_prepare_record() tells us in len the number of bytes to
1750 * send, res will contain the bytes actually sent. */
1751 return res <= 0 ? res : overall_len - (len - res);
1755 dtls_send_alert(dtls_context_t *ctx, dtls_peer_t *peer, dtls_alert_level_t level,
1756 dtls_alert_t description) {
1757 uint8_t msg[] = { level, description };
1759 dtls_send(ctx, peer, DTLS_CT_ALERT, msg, sizeof(msg));
1764 dtls_close(dtls_context_t *ctx, const session_t *remote) {
1768 peer = dtls_get_peer(ctx, remote);
1771 res = dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
1772 /* indicate tear down */
1773 peer->state = DTLS_STATE_CLOSING;
1778 static void dtls_destroy_peer(dtls_context_t *ctx, dtls_peer_t *peer, int unlink)
1780 if (peer->state != DTLS_STATE_CLOSED && peer->state != DTLS_STATE_CLOSING)
1781 dtls_close(ctx, &peer->session);
1783 #ifndef WITH_CONTIKI
1784 HASH_DEL_PEER(ctx->peers, peer);
1785 #else /* WITH_CONTIKI */
1786 list_remove(ctx->peers, peer);
1787 #endif /* WITH_CONTIKI */
1789 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "removed peer", &peer->session);
1791 dtls_free_peer(peer);
1795 * Checks a received Client Hello message for a valid cookie. When the
1796 * Client Hello contains no cookie, the function fails and a Hello
1797 * Verify Request is sent to the peer (using the write callback function
1798 * registered with \p ctx). The return value is \c -1 on error, \c 0 when
1799 * undecided, and \c 1 if the Client Hello was good.
1801 * \param ctx The DTLS context.
1802 * \param peer The remote party we are talking to, if any.
1803 * \param session Transport address of the remote peer.
1804 * \param state Current state of the connection.
1805 * \param msg The received datagram.
1806 * \param msglen Length of \p msg.
1807 * \return \c 1 if msg is a Client Hello with a valid cookie, \c 0 or
1811 dtls_verify_peer(dtls_context_t *ctx,
1814 const dtls_state_t state,
1815 uint8 *data, size_t data_length)
1817 uint8 buf[DTLS_HV_LENGTH + DTLS_COOKIE_LENGTH];
1819 int len = DTLS_COOKIE_LENGTH;
1820 uint8 *cookie = NULL;
1823 #define mycookie (buf + DTLS_HV_LENGTH)
1825 /* Store cookie where we can reuse it for the HelloVerify request. */
1826 err = dtls_create_cookie(ctx, session, data, data_length, mycookie, &len);
1830 dtls_debug_dump("create cookie", mycookie, len);
1832 assert(len == DTLS_COOKIE_LENGTH);
1834 /* Perform cookie check. */
1835 len = dtls_get_cookie(data, data_length, &cookie);
1837 dtls_warn("error while fetching the cookie, err: %i\n", err);
1841 dtls_debug_dump("compare with cookie", cookie, len);
1843 /* check if cookies match */
1844 if (len == DTLS_COOKIE_LENGTH && memcmp(cookie, mycookie, len) == 0) {
1845 dtls_debug("found matching cookie\n");
1850 dtls_debug_dump("invalid cookie", cookie, len);
1852 dtls_debug("cookie len is 0!\n");
1855 /* ClientHello did not contain any valid cookie, hence we send a
1856 * HelloVerify request. */
1858 dtls_int_to_uint16(p, DTLS_VERSION);
1859 p += sizeof(uint16);
1861 dtls_int_to_uint8(p, DTLS_COOKIE_LENGTH);
1864 assert(p == mycookie);
1866 p += DTLS_COOKIE_LENGTH;
1868 /* TODO use the same record sequence number as in the ClientHello,
1869 see 4.2.1. Denial-of-Service Countermeasures */
1870 err = dtls_send_handshake_msg_hash(ctx,
1871 state == DTLS_STATE_CONNECTED ? peer : NULL,
1873 DTLS_HT_HELLO_VERIFY_REQUEST,
1876 dtls_warn("cannot send HelloVerify request\n");
1878 return err; /* HelloVerify is sent, now we cannot do anything but wait */
1883 #if defined(DTLS_ECC) || defined(DTLS_X509)
1885 dtls_check_ecdsa_signature_elem(uint8 *data, size_t data_length,
1886 unsigned char **result_r,
1887 unsigned char **result_s)
1890 uint8 *data_orig = data;
1892 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_SHA256) {
1893 dtls_alert("only sha256 is supported in certificate verify\n");
1894 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1896 data += sizeof(uint8);
1897 data_length -= sizeof(uint8);
1899 if (dtls_uint8_to_int(data) != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
1900 dtls_alert("only ecdsa signature is supported in client verify\n");
1901 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
1903 data += sizeof(uint8);
1904 data_length -= sizeof(uint8);
1906 if (data_length < dtls_uint16_to_int(data)) {
1907 dtls_alert("signature length wrong\n");
1908 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1910 data += sizeof(uint16);
1911 data_length -= sizeof(uint16);
1913 if (dtls_uint8_to_int(data) != 0x30) {
1914 dtls_alert("wrong ASN.1 struct, expected SEQUENCE\n");
1915 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1917 data += sizeof(uint8);
1918 data_length -= sizeof(uint8);
1920 if (data_length < dtls_uint8_to_int(data)) {
1921 dtls_alert("signature length wrong\n");
1922 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1924 data += sizeof(uint8);
1925 data_length -= sizeof(uint8);
1927 if (dtls_uint8_to_int(data) != 0x02) {
1928 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1929 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1931 data += sizeof(uint8);
1932 data_length -= sizeof(uint8);
1934 i = dtls_uint8_to_int(data);
1935 data += sizeof(uint8);
1936 data_length -= sizeof(uint8);
1938 /* Sometimes these values have a leeding 0 byte */
1939 *result_r = data + i - DTLS_EC_KEY_SIZE;
1944 if (dtls_uint8_to_int(data) != 0x02) {
1945 dtls_alert("wrong ASN.1 struct, expected Integer\n");
1946 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1948 data += sizeof(uint8);
1949 data_length -= sizeof(uint8);
1951 i = dtls_uint8_to_int(data);
1952 data += sizeof(uint8);
1953 data_length -= sizeof(uint8);
1955 /* Sometimes these values have a leeding 0 byte */
1956 *result_s = data + i - DTLS_EC_KEY_SIZE;
1961 return data - data_orig;
1965 check_client_certificate_verify(dtls_context_t *ctx,
1967 uint8 *data, size_t data_length)
1969 dtls_handshake_parameters_t *config = peer->handshake_params;
1971 unsigned char *result_r;
1972 unsigned char *result_s;
1973 dtls_hash_ctx hs_hash;
1974 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
1976 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
1978 data += DTLS_HS_LENGTH;
1980 if (data_length < DTLS_HS_LENGTH + DTLS_CV_LENGTH) {
1981 dtls_alert("the packet length does not match the expected\n");
1982 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
1985 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
1992 copy_hs_hash(peer, &hs_hash);
1994 dtls_hash_finalize(sha256hash, &hs_hash);
1996 ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
1997 sizeof(config->keyx.ecc.other_pub_x),
1998 sha256hash, sizeof(sha256hash),
1999 result_r, result_s);
2002 dtls_alert("wrong signature err: %i\n", ret);
2003 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2007 #endif /* DTLS_ECC */
2010 dtls_send_server_hello(dtls_context_t *ctx, dtls_peer_t *peer)
2012 /* Ensure that the largest message to create fits in our source
2013 * buffer. (The size of the destination buffer is checked by the
2014 * encoding function, so we do not need to guess.) */
2015 uint8 buf[DTLS_SH_LENGTH + 2 + 5 + 5 + 8 + 6];
2018 uint8 extension_size;
2019 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2022 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher);
2024 extension_size = (ecdsa) ? 2 + 5 + 5 + 6 : 0;
2026 /* Handshake header */
2030 dtls_int_to_uint16(p, DTLS_VERSION);
2031 p += sizeof(uint16);
2033 /* Set server random: First 4 bytes are the server's Unix timestamp,
2034 * followed by 28 bytes of generate random data. */
2036 dtls_int_to_uint32(handshake->tmp.random.server, now / CLOCK_SECOND);
2037 dtls_prng(handshake->tmp.random.server + 4, 28);
2039 memcpy(p, handshake->tmp.random.server, DTLS_RANDOM_LENGTH);
2040 p += DTLS_RANDOM_LENGTH;
2042 *p++ = 0; /* no session id */
2044 if (handshake->cipher != TLS_NULL_WITH_NULL_NULL) {
2045 /* selected cipher suite */
2046 dtls_int_to_uint16(p, handshake->cipher);
2047 p += sizeof(uint16);
2049 /* selected compression method */
2050 *p++ = compression_methods[handshake->compression];
2053 if (extension_size) {
2054 /* length of the extensions */
2055 dtls_int_to_uint16(p, extension_size - 2);
2056 p += sizeof(uint16);
2060 /* client certificate type extension */
2061 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2062 p += sizeof(uint16);
2064 /* length of this extension type */
2065 dtls_int_to_uint16(p, 1);
2066 p += sizeof(uint16);
2068 if (CALL(ctx, is_x509_active) == 0)
2069 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2071 #endif /* DTLS_X509 */
2072 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2076 /* client certificate type extension */
2077 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2078 p += sizeof(uint16);
2080 /* length of this extension type */
2081 dtls_int_to_uint16(p, 1);
2082 p += sizeof(uint16);
2085 if (CALL(ctx, is_x509_active) == 0)
2086 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2088 #endif /* DTLS_X509 */
2089 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2093 /* ec_point_formats */
2094 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2095 p += sizeof(uint16);
2097 /* length of this extension type */
2098 dtls_int_to_uint16(p, 2);
2099 p += sizeof(uint16);
2101 /* number of supported formats */
2102 dtls_int_to_uint8(p, 1);
2105 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2109 assert(p - buf <= sizeof(buf));
2111 /* TODO use the same record sequence number as in the ClientHello,
2112 see 4.2.1. Denial-of-Service Countermeasures */
2113 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO,
2118 #define DTLS_EC_SUBJECTPUBLICKEY_SIZE (2 * DTLS_EC_KEY_SIZE + sizeof(cert_asn1_header))
2121 dtls_send_certificate_ecdsa(dtls_context_t *ctx, dtls_peer_t *peer,
2122 const dtls_ecc_key_t *key)
2124 uint8 buf[DTLS_CE_LENGTH];
2129 * Start message construction at beginning of buffer. */
2132 /* length of this certificate */
2133 dtls_int_to_uint24(p, DTLS_EC_SUBJECTPUBLICKEY_SIZE);
2134 p += sizeof(uint24);
2136 memcpy(p, &cert_asn1_header, sizeof(cert_asn1_header));
2137 p += sizeof(cert_asn1_header);
2139 memcpy(p, key->pub_key_x, DTLS_EC_KEY_SIZE);
2140 p += DTLS_EC_KEY_SIZE;
2142 memcpy(p, key->pub_key_y, DTLS_EC_KEY_SIZE);
2143 p += DTLS_EC_KEY_SIZE;
2145 assert(p - buf <= sizeof(buf));
2147 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2150 #endif /* DTLS_ECC */
2154 dtls_send_certificate_x509(dtls_context_t *ctx, dtls_peer_t *peer)
2156 uint8 buf[DTLS_MAX_CERT_SIZE];
2159 unsigned char *cert;
2162 dtls_info("\n dtls_send_certificate_ecdsa\n");
2163 ret = CALL(ctx, get_x509_cert, &peer->session,
2164 (const unsigned char **)&cert, &cert_size);
2167 dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2173 * Start message construction at beginning of buffer. */
2176 dtls_int_to_uint24(p, cert_size); /* certificates length */
2177 p += sizeof(uint24);
2179 memcpy(p, cert, cert_size);
2182 assert(p - buf <= sizeof(buf));
2184 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE,
2187 #endif /* DTLS_X509 */
2189 #if defined(DTLS_X509) || defined(DTLS_ECC)
2191 dtls_add_ecdsa_signature_elem(uint8 *p, uint32_t *point_r, uint32_t *point_s)
2196 #define R_KEY_OFFSET (1 + 1 + 2 + 1 + 1 + 1 + 1)
2197 #define S_KEY_OFFSET(len_s) (R_KEY_OFFSET + (len_s) + 1 + 1)
2198 /* store the pointer to the r component of the signature and make space */
2199 len_r = dtls_ec_key_from_uint32_asn1(point_r, DTLS_EC_KEY_SIZE, p + R_KEY_OFFSET);
2200 len_s = dtls_ec_key_from_uint32_asn1(point_s, DTLS_EC_KEY_SIZE, p + S_KEY_OFFSET(len_r));
2206 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2210 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2213 /* length of signature */
2214 dtls_int_to_uint16(p, len_r + len_s + 2 + 2 + 2);
2215 p += sizeof(uint16);
2217 /* ASN.1 SEQUENCE */
2218 dtls_int_to_uint8(p, 0x30);
2221 dtls_int_to_uint8(p, len_r + len_s + 2 + 2);
2224 /* ASN.1 Integer r */
2225 dtls_int_to_uint8(p, 0x02);
2228 dtls_int_to_uint8(p, len_r);
2231 /* the pint r was added here */
2234 /* ASN.1 Integer s */
2235 dtls_int_to_uint8(p, 0x02);
2238 dtls_int_to_uint8(p, len_s);
2241 /* the pint s was added here */
2248 dtls_send_server_key_exchange_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2249 const dtls_ecc_key_t *key)
2251 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2252 * 33 bytes long add space for that */
2253 uint8 buf[DTLS_SKEXEC_LENGTH + 2];
2256 uint8 *ephemeral_pub_x;
2257 uint8 *ephemeral_pub_y;
2258 uint32_t point_r[9];
2259 uint32_t point_s[9];
2261 dtls_handshake_parameters_t *config = peer->handshake_params;
2263 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2264 /* ServerKeyExchange
2266 * Start message construction at beginning of buffer. */
2270 /* ECCurveType curve_type: named_curve */
2271 dtls_int_to_uint8(p, 3);
2274 /* NamedCurve namedcurve: secp256r1 */
2275 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2276 p += sizeof(uint16);
2278 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2281 /* This should be an uncompressed point, but I do not have access to the spec. */
2282 dtls_int_to_uint8(p, 4);
2285 /* store the pointer to the x component of the pub key and make space */
2286 ephemeral_pub_x = p;
2287 p += DTLS_EC_KEY_SIZE;
2289 /* store the pointer to the y component of the pub key and make space */
2290 ephemeral_pub_y = p;
2291 p += DTLS_EC_KEY_SIZE;
2293 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2294 ephemeral_pub_x, ephemeral_pub_y,
2297 /* sign the ephemeral and its paramaters */
2298 dtls_ecdsa_create_sig(key->priv_key, DTLS_EC_KEY_SIZE,
2299 config->tmp.random.client, DTLS_RANDOM_LENGTH,
2300 config->tmp.random.server, DTLS_RANDOM_LENGTH,
2301 key_params, p - key_params,
2304 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2307 assert(p - buf <= sizeof(buf));
2309 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2312 #endif /* defined(DTLS_X509) || defined(DTLS_ECC) */
2314 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2315 static int dtls_send_server_key_exchange_ecdhe_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2316 const unsigned char *psk_hint, size_t psk_hint_len)
2318 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2319 * 33 bytes long add space for that */
2320 uint8 buf[DTLS_SKEXEC_LENGTH + DTLS_SKEXECPSK_LENGTH_MAX + 2];
2322 uint8 *ephemeral_pub_x;
2323 uint8 *ephemeral_pub_y;
2324 dtls_handshake_parameters_t *config = peer->handshake_params;
2326 /* ServerKeyExchange
2327 * Please see Session 2, RFC 5489.
2330 select (KeyExchangeAlgorithm) {
2331 //other cases for rsa, diffie_hellman, etc.
2332 case ec_diffie_hellman_psk: // NEW
2333 opaque psk_identity_hint<0..2^16-1>;
2334 ServerECDHParams params;
2336 } ServerKeyExchange; */
2339 assert(psk_hint_len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2340 if (psk_hint_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2341 // should never happen
2342 dtls_warn("psk identity hint is too long\n");
2343 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2346 // psk_identity_hint
2347 dtls_int_to_uint16(p, psk_hint_len);
2348 p += sizeof(uint16);
2350 memcpy(p, psk_hint, psk_hint_len);
2353 /* ServerECDHParams. */
2354 /* ECCurveType curve_type: named_curve */
2355 dtls_int_to_uint8(p, TLS_EC_CURVE_TYPE_NAMED_CURVE);
2358 /* NamedCurve namedcurve: secp256r1 */
2359 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2360 p += sizeof(uint16);
2362 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2365 /* This should be an uncompressed point, but I do not have access to the spec. */
2366 dtls_int_to_uint8(p, 4);
2369 /* store the pointer to the x component of the pub key and make space */
2370 ephemeral_pub_x = p;
2371 p += DTLS_EC_KEY_SIZE;
2373 /* store the pointer to the y component of the pub key and make space */
2374 ephemeral_pub_y = p;
2375 p += DTLS_EC_KEY_SIZE;
2377 dtls_ecdsa_generate_key(config->keyx.ecc.own_eph_priv,
2378 ephemeral_pub_x, ephemeral_pub_y,
2381 assert(p - buf <= sizeof(buf));
2383 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2386 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2390 dtls_send_server_key_exchange_psk(dtls_context_t *ctx, dtls_peer_t *peer,
2391 const unsigned char *psk_hint, size_t len)
2393 uint8 buf[DTLS_SKEXECPSK_LENGTH_MAX];
2398 assert(len <= DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2399 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
2400 /* should never happen */
2401 dtls_warn("psk identity hint is too long\n");
2402 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2405 dtls_int_to_uint16(p, len);
2406 p += sizeof(uint16);
2408 memcpy(p, psk_hint, len);
2411 assert(p - buf <= sizeof(buf));
2413 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_KEY_EXCHANGE,
2416 #endif /* DTLS_PSK */
2418 #if defined(DTLS_ECC) || defined(DTLS_X509)
2420 dtls_send_server_certificate_request(dtls_context_t *ctx, dtls_peer_t *peer)
2427 * Start message construction at beginning of buffer. */
2430 /* certificate_types */
2431 dtls_int_to_uint8(p, 1);
2435 dtls_int_to_uint8(p, TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN);
2438 /* supported_signature_algorithms */
2439 dtls_int_to_uint16(p, 2);
2440 p += sizeof(uint16);
2443 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_SHA256);
2447 dtls_int_to_uint8(p, TLS_EXT_SIG_HASH_ALGO_ECDSA);
2450 /* certificate_authoritiess */
2451 dtls_int_to_uint16(p, 0);
2452 p += sizeof(uint16);
2454 assert(p - buf <= sizeof(buf));
2456 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_REQUEST,
2459 #endif /* DTLS_ECC */
2462 dtls_send_server_hello_done(dtls_context_t *ctx, dtls_peer_t *peer)
2467 * Start message construction at beginning of buffer. */
2469 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_SERVER_HELLO_DONE,
2474 dtls_send_server_hello_msgs(dtls_context_t *ctx, dtls_peer_t *peer)
2481 res = dtls_send_server_hello(ctx, peer);
2484 dtls_debug("dtls_server_hello: cannot prepare ServerHello record\n");
2488 ecdsa = is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher);
2489 ecdh_anon = is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2490 ecdhe_psk = is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher);
2492 #if defined(DTLS_ECC) || defined(DTLS_X509)
2494 res = dtls_send_server_key_exchange_ecdh(ctx, peer, NULL);
2497 dtls_debug("dtls_server_hello(with ECDH): cannot prepare Server Key Exchange record\n");
2502 const dtls_ecc_key_t *ecdsa_key;
2505 if (CALL(ctx, is_x509_active) == 0)
2506 res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
2508 #endif /* DTLS_X509 */
2509 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
2512 dtls_debug("no ecdsa key to send\n");
2517 if (CALL(ctx, is_x509_active) == 0)
2518 res = dtls_send_certificate_x509(ctx, peer);
2520 #endif /* DTLS_X509 */
2521 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
2524 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
2528 res = dtls_send_server_key_exchange_ecdh(ctx, peer, ecdsa_key);
2531 dtls_debug("dtls_server_hello: cannot prepare Server Key Exchange record\n");
2535 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
2536 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx)))) {
2537 res = dtls_send_server_certificate_request(ctx, peer);
2539 dtls_debug("dtls_server_hello(with ECDSA): cannot prepare certificate Request record\n");
2544 #endif /* DTLS_ECC */
2545 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2546 else if(ecdhe_psk) {
2547 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2550 /* The identity hint is optional, therefore we ignore the result
2551 * and check psk only. */
2552 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2553 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2556 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2561 res = dtls_send_server_key_exchange_ecdhe_psk(ctx, peer, psk_hint, (size_t)psk_len);
2564 dtls_debug("dtls_server_hello(with ECDHE): cannot prepare Server Key Exchange record\n");
2569 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2571 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
2572 unsigned char psk_hint[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2575 /* The identity hint is optional, therefore we ignore the result
2576 * and check psk only. */
2577 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_HINT,
2578 NULL, 0, psk_hint, DTLS_PSK_MAX_CLIENT_IDENTITY_LEN);
2581 dtls_debug("dtls_server_hello: cannot create ServerKeyExchange\n");
2586 res = dtls_send_server_key_exchange_psk(ctx, peer, psk_hint, (size_t)len);
2589 dtls_debug("dtls_server_key_exchange_psk: cannot send server key exchange record\n");
2594 #endif /* DTLS_PSK */
2596 res = dtls_send_server_hello_done(ctx, peer);
2599 dtls_debug("dtls_server_hello: cannot prepare ServerHelloDone record\n");
2606 dtls_send_ccs(dtls_context_t *ctx, dtls_peer_t *peer) {
2609 return dtls_send(ctx, peer, DTLS_CT_CHANGE_CIPHER_SPEC, buf, 1);
2614 dtls_send_client_key_exchange(dtls_context_t *ctx, dtls_peer_t *peer)
2616 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2617 uint8 buf[DTLS_CKXEC_LENGTH + 2 + DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2619 uint8 buf[DTLS_CKXEC_LENGTH];
2620 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2621 uint8 client_id[DTLS_PSK_MAX_CLIENT_IDENTITY_LEN];
2623 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2627 switch (handshake->cipher) {
2629 case TLS_PSK_WITH_AES_128_CCM_8: {
2632 len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2637 dtls_crit("no psk identity set in kx\n");
2641 if (len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2642 dtls_warn("the psk identity is too long\n");
2643 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2646 dtls_int_to_uint16(p, len);
2647 p += sizeof(uint16);
2649 memcpy(p, client_id, len);
2654 #endif /* DTLS_PSK */
2655 #if defined(DTLS_ECC) || defined(DTLS_X509)
2656 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2657 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256: {
2658 uint8 *ephemeral_pub_x;
2659 uint8 *ephemeral_pub_y;
2661 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2664 /* This should be an uncompressed point, but I do not have access to the spec. */
2665 dtls_int_to_uint8(p, 4);
2668 ephemeral_pub_x = p;
2669 p += DTLS_EC_KEY_SIZE;
2670 ephemeral_pub_y = p;
2671 p += DTLS_EC_KEY_SIZE;
2673 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2674 ephemeral_pub_x, ephemeral_pub_y,
2679 #endif /* DTLS_ECC */
2680 #if defined(DTLS_PSK) && defined(DTLS_ECC)
2681 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256: {
2683 uint8 *ephemeral_pub_x;
2684 uint8 *ephemeral_pub_y;
2686 /* Please see Session 2, RFC 5489.
2688 select (KeyExchangeAlgorithm) {
2689 // other cases for rsa, diffie_hellman, etc.
2690 case ec_diffie_hellman_psk:
2691 opaque psk_identity<0..2^16-1>;
2692 ClientECDiffieHellmanPublic public;
2694 } ClientKeyExchange;
2697 psk_len = CALL(ctx, get_psk_info, &peer->session, DTLS_PSK_IDENTITY,
2702 dtls_crit("no psk identity set in kx\n");
2706 if (psk_len + sizeof(uint16) > DTLS_CKXEC_LENGTH) {
2707 dtls_warn("the psk identity is too long\n");
2708 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2711 dtls_int_to_uint16(p, psk_len);
2712 p += sizeof(uint16);
2714 memcpy(p, client_id, psk_len);
2717 dtls_int_to_uint8(p, 1 + 2 * DTLS_EC_KEY_SIZE);
2720 dtls_int_to_uint8(p, 4);
2723 ephemeral_pub_x = p;
2724 p += DTLS_EC_KEY_SIZE;
2725 ephemeral_pub_y = p;
2726 p += DTLS_EC_KEY_SIZE;
2728 dtls_ecdsa_generate_key(peer->handshake_params->keyx.ecc.own_eph_priv,
2729 ephemeral_pub_x, ephemeral_pub_y,
2733 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
2735 dtls_crit("cipher not supported\n");
2736 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
2739 assert(p - buf <= sizeof(buf));
2741 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CLIENT_KEY_EXCHANGE,
2745 #if defined(DTLS_ECC) || defined(DTLS_X509)
2747 dtls_send_certificate_verify_ecdh(dtls_context_t *ctx, dtls_peer_t *peer,
2748 const dtls_ecc_key_t *key)
2750 /* The ASN.1 Integer representation of an 32 byte unsigned int could be
2751 * 33 bytes long add space for that */
2752 uint8 buf[DTLS_CV_LENGTH + 2];
2754 uint32_t point_r[9];
2755 uint32_t point_s[9];
2756 dtls_hash_ctx hs_hash;
2757 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
2759 /* ServerKeyExchange
2761 * Start message construction at beginning of buffer. */
2764 copy_hs_hash(peer, &hs_hash);
2766 dtls_hash_finalize(sha256hash, &hs_hash);
2768 /* sign the ephemeral and its paramaters */
2769 dtls_ecdsa_create_sig_hash(key->priv_key, DTLS_EC_KEY_SIZE,
2770 sha256hash, sizeof(sha256hash),
2773 p = dtls_add_ecdsa_signature_elem(p, point_r, point_s);
2775 assert(p - buf <= sizeof(buf));
2777 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_CERTIFICATE_VERIFY,
2780 #endif /* DTLS_ECC */
2783 dtls_send_finished(dtls_context_t *ctx, dtls_peer_t *peer,
2784 const unsigned char *label, size_t labellen)
2787 uint8 hash[DTLS_HMAC_MAX];
2788 uint8 buf[DTLS_FIN_LENGTH];
2789 dtls_hash_ctx hs_hash;
2792 copy_hs_hash(peer, &hs_hash);
2794 length = dtls_hash_finalize(hash, &hs_hash);
2796 dtls_prf(peer->handshake_params->tmp.master_secret,
2797 DTLS_MASTER_SECRET_LENGTH,
2799 PRF_LABEL(finished), PRF_LABEL_SIZE(finished),
2801 p, DTLS_FIN_LENGTH);
2803 dtls_debug_dump("server finished MAC", p, DTLS_FIN_LENGTH);
2805 p += DTLS_FIN_LENGTH;
2807 assert(p - buf <= sizeof(buf));
2809 return dtls_send_handshake_msg(ctx, peer, DTLS_HT_FINISHED,
2814 dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
2815 uint8 cookie[], size_t cookie_length) {
2816 uint8 buf[DTLS_CH_LENGTH_MAX];
2818 uint8_t cipher_size;
2819 uint8_t extension_size;
2825 dtls_handshake_parameters_t *handshake = peer->handshake_params;
2828 switch(ctx->selected_cipher)
2830 case TLS_PSK_WITH_AES_128_CCM_8:
2831 psk = is_psk_supported(ctx);
2833 case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
2834 ecdsa = is_ecdsa_supported(ctx, 1);
2835 x509 = is_x509_supported(ctx, 1);
2837 case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
2838 ecdh_anon = is_ecdh_anon_supported(ctx);
2840 case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
2841 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2844 psk = is_psk_supported(ctx);
2845 ecdsa = is_ecdsa_supported(ctx, 1);
2846 ecdh_anon = is_ecdh_anon_supported(ctx);
2847 ecdhe_psk = is_ecdhe_psk_supported(ctx);
2848 x509 = is_x509_supported(ctx, 1);
2852 cipher_size = 2 + ((ecdsa || x509) ? 2 : 0) + (psk ? 2 : 0) + (ecdh_anon ? 2 : 0) + (ecdhe_psk ? 2 : 0);
2853 extension_size = (ecdsa || x509) ? (2 + 6 + 6 + 8 + 6) : 0;
2855 if (cipher_size == 0) {
2856 dtls_crit("no cipher callbacks implemented\n");
2859 dtls_int_to_uint16(p, DTLS_VERSION);
2860 p += sizeof(uint16);
2862 if (cookie_length > DTLS_COOKIE_LENGTH_MAX) {
2863 dtls_warn("the cookie is too long\n");
2864 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
2867 if (cookie_length == 0) {
2868 /* Set client random: First 4 bytes are the client's Unix timestamp,
2869 * followed by 28 bytes of generate random data. */
2871 dtls_int_to_uint32(handshake->tmp.random.client, now / CLOCK_SECOND);
2872 dtls_prng(handshake->tmp.random.client + sizeof(uint32),
2873 DTLS_RANDOM_LENGTH - sizeof(uint32));
2875 /* we must use the same Client Random as for the previous request */
2876 memcpy(p, handshake->tmp.random.client, DTLS_RANDOM_LENGTH);
2877 p += DTLS_RANDOM_LENGTH;
2879 /* session id (length 0) */
2880 dtls_int_to_uint8(p, 0);
2884 dtls_int_to_uint8(p, cookie_length);
2886 if (cookie_length != 0) {
2887 memcpy(p, cookie, cookie_length);
2891 /* add known cipher(s) */
2892 dtls_int_to_uint16(p, cipher_size - 2);
2893 p += sizeof(uint16);
2896 dtls_int_to_uint16(p, TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256);
2897 p += sizeof(uint16);
2900 dtls_int_to_uint16(p, TLS_PSK_WITH_AES_128_CCM_8);
2901 p += sizeof(uint16);
2903 if (ecdsa || x509) {
2904 dtls_int_to_uint16(p, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
2905 p += sizeof(uint16);
2908 dtls_int_to_uint16(p, TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
2909 p += sizeof(uint16);
2912 /* compression method */
2913 dtls_int_to_uint8(p, 1);
2916 dtls_int_to_uint8(p, TLS_COMPRESSION_NULL);
2919 if (extension_size) {
2920 /* length of the extensions */
2921 dtls_int_to_uint16(p, extension_size - 2);
2922 p += sizeof(uint16);
2925 if (ecdsa || x509) {
2926 /* client certificate type extension */
2927 dtls_int_to_uint16(p, TLS_EXT_CLIENT_CERTIFICATE_TYPE);
2928 p += sizeof(uint16);
2930 /* length of this extension type */
2931 dtls_int_to_uint16(p, 2);
2932 p += sizeof(uint16);
2934 /* length of the list */
2935 dtls_int_to_uint8(p, 1);
2939 if (CALL(ctx, is_x509_active) == 0)
2940 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2942 #endif /* DTLS_X509 */
2943 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2947 /* client certificate type extension */
2948 dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
2949 p += sizeof(uint16);
2951 /* length of this extension type */
2952 dtls_int_to_uint16(p, 2);
2953 p += sizeof(uint16);
2955 /* length of the list */
2956 dtls_int_to_uint8(p, 1);
2960 if (CALL(ctx, is_x509_active) == 0)
2961 dtls_int_to_uint8(p, TLS_CERT_TYPE_X509);
2963 #endif /* DTLS_X509 */
2964 dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
2968 /* elliptic_curves */
2969 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
2970 p += sizeof(uint16);
2972 /* length of this extension type */
2973 dtls_int_to_uint16(p, 4);
2974 p += sizeof(uint16);
2976 /* length of the list */
2977 dtls_int_to_uint16(p, 2);
2978 p += sizeof(uint16);
2980 dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES_SECP256R1);
2981 p += sizeof(uint16);
2983 /* ec_point_formats */
2984 dtls_int_to_uint16(p, TLS_EXT_EC_POINT_FORMATS);
2985 p += sizeof(uint16);
2987 /* length of this extension type */
2988 dtls_int_to_uint16(p, 2);
2989 p += sizeof(uint16);
2991 /* number of supported formats */
2992 dtls_int_to_uint8(p, 1);
2995 dtls_int_to_uint8(p, TLS_EXT_EC_POINT_FORMATS_UNCOMPRESSED);
2999 assert(p - buf <= sizeof(buf));
3001 if (cookie_length != 0)
3002 clear_hs_hash(peer);
3004 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3005 DTLS_HT_CLIENT_HELLO,
3006 buf, p - buf, cookie_length != 0);
3010 check_server_hello(dtls_context_t *ctx,
3012 uint8 *data, size_t data_length)
3014 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3016 /* This function is called when we expect a ServerHello (i.e. we
3017 * have sent a ClientHello). We might instead receive a HelloVerify
3018 * request containing a cookie. If so, we must repeat the
3019 * ClientHello with the given Cookie.
3021 if (data_length < DTLS_HS_LENGTH + DTLS_HS_LENGTH)
3022 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3024 update_hs_hash(peer, data, data_length);
3026 /* FIXME: check data_length before accessing fields */
3028 /* Get the server's random data and store selected cipher suite
3029 * and compression method (like dtls_update_parameters().
3030 * Then calculate master secret and wait for ServerHelloDone. When received,
3031 * send ClientKeyExchange (?) and ChangeCipherSpec + ClientFinished. */
3033 /* check server version */
3034 data += DTLS_HS_LENGTH;
3035 data_length -= DTLS_HS_LENGTH;
3037 if (dtls_uint16_to_int(data) != DTLS_VERSION) {
3038 dtls_alert("unknown DTLS version\n");
3039 return dtls_alert_fatal_create(DTLS_ALERT_PROTOCOL_VERSION);
3042 data += sizeof(uint16); /* skip version field */
3043 data_length -= sizeof(uint16);
3045 /* store server random data */
3046 memcpy(handshake->tmp.random.server, data, DTLS_RANDOM_LENGTH);
3047 /* skip server random */
3048 data += DTLS_RANDOM_LENGTH;
3049 data_length -= DTLS_RANDOM_LENGTH;
3051 SKIP_VAR_FIELD(data, data_length, uint8); /* skip session id */
3053 /* Check cipher suite. As we offer all we have, it is sufficient
3054 * to check if the cipher suite selected by the server is in our
3055 * list of known cipher suites. Subsets are not supported. */
3056 handshake->cipher = dtls_uint16_to_int(data);
3057 if (!known_cipher(ctx, handshake->cipher, 1)) {
3058 dtls_alert("unsupported cipher 0x%02x 0x%02x\n",
3060 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3062 data += sizeof(uint16);
3063 data_length -= sizeof(uint16);
3065 /* Check if NULL compression was selected. We do not know any other. */
3066 if (dtls_uint8_to_int(data) != TLS_COMPRESSION_NULL) {
3067 dtls_alert("unsupported compression method 0x%02x\n", data[0]);
3068 return dtls_alert_fatal_create(DTLS_ALERT_INSUFFICIENT_SECURITY);
3070 data += sizeof(uint8);
3071 data_length -= sizeof(uint8);
3073 return dtls_check_tls_extension(peer, data, data_length, 0);
3076 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3080 check_server_hello_verify_request(dtls_context_t *ctx,
3082 uint8 *data, size_t data_length)
3084 dtls_hello_verify_t *hv;
3087 if (data_length < DTLS_HS_LENGTH + DTLS_HV_LENGTH)
3088 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3090 hv = (dtls_hello_verify_t *)(data + DTLS_HS_LENGTH);
3092 res = dtls_send_client_hello(ctx, peer, hv->cookie, hv->cookie_length);
3095 dtls_warn("cannot send ClientHello\n");
3103 check_peer_certificate(dtls_context_t *ctx,
3105 uint8 *data, size_t data_length)
3108 dtls_handshake_parameters_t *config = peer->handshake_params;
3110 update_hs_hash(peer, data, data_length);
3112 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3114 data += DTLS_HS_LENGTH;
3116 if (dtls_uint24_to_int(data) != DTLS_EC_SUBJECTPUBLICKEY_SIZE) {
3117 dtls_alert("expect length of %d bytes for certificate\n",
3118 DTLS_EC_SUBJECTPUBLICKEY_SIZE);
3119 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3121 data += sizeof(uint24);
3123 if (memcmp(data, cert_asn1_header, sizeof(cert_asn1_header))) {
3124 dtls_alert("got an unexpected Subject public key format\n");
3125 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3127 data += sizeof(cert_asn1_header);
3129 memcpy(config->keyx.ecc.other_pub_x, data,
3130 sizeof(config->keyx.ecc.other_pub_x));
3131 data += sizeof(config->keyx.ecc.other_pub_x);
3133 memcpy(config->keyx.ecc.other_pub_y, data,
3134 sizeof(config->keyx.ecc.other_pub_y));
3135 data += sizeof(config->keyx.ecc.other_pub_y);
3137 err = CALL(ctx, verify_ecdsa_key, &peer->session,
3138 config->keyx.ecc.other_pub_x,
3139 config->keyx.ecc.other_pub_y,
3140 sizeof(config->keyx.ecc.other_pub_x));
3142 dtls_warn("The certificate was not accepted\n");
3148 #endif /* DTLS_ECC */
3152 check_peer_certificate_x509(dtls_context_t *ctx,
3154 uint8 *data, size_t data_length)
3157 dtls_handshake_parameters_t *config = peer->handshake_params;
3160 dtls_info("\n check_peer_certificate_x509\n");
3161 update_hs_hash(peer, data, data_length);
3163 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3165 data += DTLS_HS_LENGTH;
3167 cert_length = dtls_uint24_to_int(data);
3168 data += sizeof(uint24);
3170 ret = CALL(ctx, verify_x509_cert, &peer->session, data, cert_length,
3171 config->keyx.ecc.other_pub_x, sizeof(config->keyx.ecc.other_pub_x),
3172 config->keyx.ecc.other_pub_y, sizeof(config->keyx.ecc.other_pub_y));
3174 dtls_warn("The certificate was not accepted\n");
3180 #endif /* DTLS_X509 */
3182 #if defined(DTLS_X509) || defined(DTLS_ECC)
3184 check_server_key_exchange_ecdsa(dtls_context_t *ctx,
3186 uint8 *data, size_t data_length)
3188 dtls_handshake_parameters_t *config = peer->handshake_params;
3190 unsigned char *result_r;
3191 unsigned char *result_s;
3192 unsigned char *key_params;
3194 update_hs_hash(peer, data, data_length);
3196 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(config->cipher));
3198 data += DTLS_HS_LENGTH;
3200 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_LENGTH) {
3201 dtls_alert("the packet length does not match the expected\n");
3202 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3206 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3207 dtls_alert("Only named curves supported\n");
3208 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3210 data += sizeof(uint8);
3211 data_length -= sizeof(uint8);
3213 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3214 dtls_alert("secp256r1 supported\n");
3215 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3217 data += sizeof(uint16);
3218 data_length -= sizeof(uint16);
3220 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3221 dtls_alert("expected 65 bytes long public point\n");
3222 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3224 data += sizeof(uint8);
3225 data_length -= sizeof(uint8);
3227 if (dtls_uint8_to_int(data) != 4) {
3228 dtls_alert("expected uncompressed public point\n");
3229 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3231 data += sizeof(uint8);
3232 data_length -= sizeof(uint8);
3234 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3235 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3236 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3238 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3239 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3240 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3242 ret = dtls_check_ecdsa_signature_elem(data, data_length, &result_r, &result_s);
3249 ret = dtls_ecdsa_verify_sig(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
3250 sizeof(config->keyx.ecc.other_pub_x),
3251 config->tmp.random.client, DTLS_RANDOM_LENGTH,
3252 config->tmp.random.server, DTLS_RANDOM_LENGTH,
3254 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
3255 result_r, result_s);
3258 dtls_alert("wrong signature\n");
3259 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3265 check_server_key_exchange_ecdh(dtls_context_t *ctx,
3267 uint8 *data, size_t data_length)
3269 dtls_handshake_parameters_t *config = peer->handshake_params;
3271 update_hs_hash(peer, data, data_length);
3273 assert(is_tls_ecdh_anon_with_aes_128_cbc_sha_256(config->cipher));
3275 data += DTLS_HS_LENGTH;
3277 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3278 dtls_alert("the packet length does not match the expected\n");
3279 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3282 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3283 dtls_alert("Only named curves supported\n");
3284 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3286 data += sizeof(uint8);
3287 data_length -= sizeof(uint8);
3289 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3290 dtls_alert("secp256r1 supported\n");
3291 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3293 data += sizeof(uint16);
3294 data_length -= sizeof(uint16);
3296 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3297 dtls_alert("expected 65 bytes long public point\n");
3298 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3300 data += sizeof(uint8);
3301 data_length -= sizeof(uint8);
3303 if (dtls_uint8_to_int(data) != 4) {
3304 dtls_alert("expected uncompressed public point\n");
3305 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3307 data += sizeof(uint8);
3308 data_length -= sizeof(uint8);
3310 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3311 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3312 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3314 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3315 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3316 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3320 #endif /* DTLS_ECC */
3321 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3322 check_server_key_exchange_ecdhe_psk(dtls_context_t *ctx,
3324 uint8 *data, size_t data_length)
3326 dtls_handshake_parameters_t *config = peer->handshake_params;
3327 uint16_t psk_len = 0;
3329 /* ServerKeyExchange
3330 * Please see Session 2, RFC 5489.
3333 select (KeyExchangeAlgorithm) {
3334 //other cases for rsa, diffie_hellman, etc.
3335 case ec_diffie_hellman_psk: // NEW
3336 opaque psk_identity_hint<0..2^16-1>;
3337 ServerECDHParams params;
3339 } ServerKeyExchange; */
3341 update_hs_hash(peer, data, data_length);
3343 assert(is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(config->cipher));
3345 data += DTLS_HS_LENGTH;
3347 psk_len = dtls_uint16_to_int(data);
3348 data += sizeof(uint16);
3350 if (psk_len != data_length - DTLS_HS_LENGTH - DTLS_SKEXEC_ECDH_ANON_LENGTH - sizeof(uint16)) {
3351 dtls_warn("the length of the server identity hint is worng\n");
3352 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3355 if (psk_len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3356 dtls_warn("please use a smaller server identity hint\n");
3357 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3360 // store the psk_identity_hint in config->keyx.psk for later use
3361 config->keyx.psk.id_length = psk_len;
3362 memcpy(config->keyx.psk.identity, data, psk_len);
3365 data_length -= psk_len;
3367 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXEC_ECDH_ANON_LENGTH) {
3368 dtls_alert("the packet length does not match the expected\n");
3369 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3372 if (dtls_uint8_to_int(data) != TLS_EC_CURVE_TYPE_NAMED_CURVE) {
3373 dtls_alert("Only named curves supported\n");
3374 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3376 data += sizeof(uint8);
3377 data_length -= sizeof(uint8);
3379 if (dtls_uint16_to_int(data) != TLS_EXT_ELLIPTIC_CURVES_SECP256R1) {
3380 dtls_alert("secp256r1 supported\n");
3381 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3383 data += sizeof(uint16);
3384 data_length -= sizeof(uint16);
3386 if (dtls_uint8_to_int(data) != 1 + 2 * DTLS_EC_KEY_SIZE) {
3387 dtls_alert("expected 65 bytes long public point\n");
3388 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3390 data += sizeof(uint8);
3391 data_length -= sizeof(uint8);
3393 if (dtls_uint8_to_int(data) != 4) {
3394 dtls_alert("expected uncompressed public point\n");
3395 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3397 data += sizeof(uint8);
3398 data_length -= sizeof(uint8);
3400 memcpy(config->keyx.ecc.other_eph_pub_x, data, sizeof(config->keyx.ecc.other_eph_pub_x));
3401 data += sizeof(config->keyx.ecc.other_eph_pub_x);
3402 data_length -= sizeof(config->keyx.ecc.other_eph_pub_x);
3404 memcpy(config->keyx.ecc.other_eph_pub_y, data, sizeof(config->keyx.ecc.other_eph_pub_y));
3405 data += sizeof(config->keyx.ecc.other_eph_pub_y);
3406 data_length -= sizeof(config->keyx.ecc.other_eph_pub_y);
3410 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
3414 check_server_key_exchange_psk(dtls_context_t *ctx,
3416 uint8 *data, size_t data_length)
3418 dtls_handshake_parameters_t *config = peer->handshake_params;
3421 update_hs_hash(peer, data, data_length);
3423 assert(is_tls_psk_with_aes_128_ccm_8(config->cipher));
3425 data += DTLS_HS_LENGTH;
3427 if (data_length < DTLS_HS_LENGTH + DTLS_SKEXECPSK_LENGTH_MIN) {
3428 dtls_alert("the packet length does not match the expected\n");
3429 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3432 len = dtls_uint16_to_int(data);
3433 data += sizeof(uint16);
3435 if (len != data_length - DTLS_HS_LENGTH - sizeof(uint16)) {
3436 dtls_warn("the length of the server identity hint is worng\n");
3437 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3440 if (len > DTLS_PSK_MAX_CLIENT_IDENTITY_LEN) {
3441 dtls_warn("please use a smaller server identity hint\n");
3442 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
3445 /* store the psk_identity_hint in config->keyx.psk for later use */
3446 config->keyx.psk.id_length = len;
3447 memcpy(config->keyx.psk.identity, data, len);
3450 #endif /* DTLS_PSK */
3453 check_certificate_request(dtls_context_t *ctx,
3455 uint8 *data, size_t data_length)
3462 update_hs_hash(peer, data, data_length);
3464 assert(is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher));
3466 data += DTLS_HS_LENGTH;
3468 if (data_length < DTLS_HS_LENGTH + 5) {
3469 dtls_alert("the packet length does not match the expected\n");
3470 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3473 i = dtls_uint8_to_int(data);
3474 data += sizeof(uint8);
3475 if (i + 1 > data_length) {
3476 dtls_alert("the cerfificate types are too long\n");
3477 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3481 for (; i > 0 ; i -= sizeof(uint8)) {
3482 if (dtls_uint8_to_int(data) == TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN
3484 auth_alg = dtls_uint8_to_int(data);
3485 data += sizeof(uint8);
3488 if (auth_alg != TLS_CLIENT_CERTIFICATE_TYPE_ECDSA_SIGN) {
3489 dtls_alert("the request authentication algorithm is not supproted\n");
3490 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3493 i = dtls_uint16_to_int(data);
3494 data += sizeof(uint16);
3495 if (i + 1 > data_length) {
3496 dtls_alert("the signature and hash algorithm list is too long\n");
3497 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
3502 for (; i > 0 ; i -= sizeof(uint16)) {
3503 int current_hash_alg;
3504 int current_sig_alg;
3506 current_hash_alg = dtls_uint8_to_int(data);
3507 data += sizeof(uint8);
3508 current_sig_alg = dtls_uint8_to_int(data);
3509 data += sizeof(uint8);
3511 if (current_hash_alg == TLS_EXT_SIG_HASH_ALGO_SHA256 && hash_alg == 0 &&
3512 current_sig_alg == TLS_EXT_SIG_HASH_ALGO_ECDSA && sig_alg == 0) {
3513 hash_alg = current_hash_alg;
3514 sig_alg = current_sig_alg;
3518 if (hash_alg != TLS_EXT_SIG_HASH_ALGO_SHA256 ||
3519 sig_alg != TLS_EXT_SIG_HASH_ALGO_ECDSA) {
3520 dtls_alert("no supported hash and signature algorithem\n");
3521 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
3524 /* common names are ignored */
3526 peer->handshake_params->do_client_auth = 1;
3531 check_server_hellodone(dtls_context_t *ctx,
3533 uint8 *data, size_t data_length)
3537 const dtls_ecc_key_t *ecdsa_key;
3539 unsigned char *cert;
3541 #endif /* DTLS_X509 */
3542 #endif /* DTLS_ECC */
3544 dtls_handshake_parameters_t *handshake = peer->handshake_params;
3546 /* calculate master key, send CCS */
3548 update_hs_hash(peer, data, data_length);
3550 #if defined(DTLS_ECC) || defined(DTLS_X509)
3551 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3553 if (CALL(ctx, is_x509_active) == 0)
3554 res = CALL(ctx, get_x509_key, &peer->session, &ecdsa_key);
3556 #endif /* DTLS_X509 */
3557 res = CALL(ctx, get_ecdsa_key, &peer->session, &ecdsa_key);
3559 dtls_crit("no ecdsa key to use\n");
3564 if (CALL(ctx, is_x509_active) == 0)
3565 res = dtls_send_certificate_x509(ctx, peer);
3567 #endif /* DTLS_X509 */
3568 res = dtls_send_certificate_ecdsa(ctx, peer, ecdsa_key);
3571 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3575 #endif /* DTLS_ECC */
3577 /* send ClientKeyExchange */
3578 res = dtls_send_client_key_exchange(ctx, peer);
3581 dtls_debug("cannot send KeyExchange message\n");
3586 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(handshake->cipher) && handshake->do_client_auth) {
3587 res = dtls_send_certificate_verify_ecdh(ctx, peer, ecdsa_key);
3590 dtls_debug("dtls_server_hello: cannot prepare Certificate record\n");
3594 #endif /* DTLS_ECC */
3596 res = calculate_key_block(ctx, handshake, peer,
3597 &peer->session, peer->role);
3602 res = dtls_send_ccs(ctx, peer);
3604 dtls_debug("cannot send CCS message\n");
3608 /* and switch cipher suite */
3609 dtls_security_params_switch(peer);
3611 /* Client Finished */
3612 return dtls_send_finished(ctx, peer, PRF_LABEL(client), PRF_LABEL_SIZE(client));
3616 decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
3619 dtls_record_header_t *header = DTLS_RECORD_HEADER(packet);
3620 dtls_security_parameters_t *security = dtls_security_params_epoch(peer, dtls_get_epoch(header));
3623 *cleartext = (uint8 *)packet + sizeof(dtls_record_header_t);
3624 clen = length - sizeof(dtls_record_header_t);
3627 dtls_alert("No security context for epoch: %i\n", dtls_get_epoch(header));
3631 if (security->cipher == TLS_NULL_WITH_NULL_NULL) {
3632 /* no cipher suite selected */
3634 } else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(security->cipher) ||
3635 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(security->cipher)) {
3637 unsigned char nonce[DTLS_CBC_IV_LENGTH];
3639 if (clen < (DTLS_CBC_IV_LENGTH + DTLS_HMAC_DIGEST_SIZE)) /* need at least IV and MAC */
3642 memcpy(nonce, *cleartext , DTLS_CBC_IV_LENGTH);
3643 clen -= DTLS_CBC_IV_LENGTH;
3644 *cleartext += DTLS_CBC_IV_LENGTH ;
3646 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3647 dtls_kb_remote_write_key(security, peer->role),
3648 dtls_kb_key_size(security, peer->role),
3652 } else { /* TLS_PSK_WITH_AES_128_CCM_8 or TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
3654 * length of additional_data for the AEAD cipher which consists of
3655 * seq_num(2+6) + type(1) + version(2) + length(2)
3657 #define A_DATA_LEN 13
3658 unsigned char nonce[DTLS_CCM_BLOCKSIZE];
3659 unsigned char A_DATA[A_DATA_LEN];
3661 if (clen < 16) /* need at least IV and MAC */
3664 memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
3665 memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
3666 dtls_kb_iv_size(security, peer->role));
3668 /* read epoch and seq_num from message */
3669 memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
3673 dtls_debug_dump("nonce", nonce, DTLS_CCM_BLOCKSIZE);
3674 dtls_debug_dump("key", dtls_kb_remote_write_key(security, peer->role),
3675 dtls_kb_key_size(security, peer->role));
3676 dtls_debug_dump("ciphertext", *cleartext, clen);
3678 /* re-use N to create additional data according to RFC 5246, Section 6.2.3.3:
3680 * additional_data = seq_num + TLSCompressed.type +
3681 * TLSCompressed.version + TLSCompressed.length;
3683 memcpy(A_DATA, &DTLS_RECORD_HEADER(packet)->epoch, 8); /* epoch and seq_num */
3684 memcpy(A_DATA + 8, &DTLS_RECORD_HEADER(packet)->content_type, 3); /* type and version */
3685 dtls_int_to_uint16(A_DATA + 11, clen - 8); /* length without nonce_explicit */
3687 clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
3688 dtls_kb_remote_write_key(security, peer->role),
3689 dtls_kb_key_size(security, peer->role),
3695 dtls_warn("decryption failed\n");
3698 dtls_debug("decrypt_verify(): found %i bytes cleartext\n", clen);
3700 dtls_security_params_free_other(peer);
3701 dtls_debug_dump("cleartext", *cleartext, clen);
3708 dtls_send_hello_request(dtls_context_t *ctx, dtls_peer_t *peer)
3710 return dtls_send_handshake_msg_hash(ctx, peer, &peer->session,
3711 DTLS_HT_HELLO_REQUEST,
3716 dtls_renegotiate(dtls_context_t *ctx, const session_t *dst)
3718 dtls_peer_t *peer = NULL;
3721 peer = dtls_get_peer(ctx, dst);
3726 if (peer->state != DTLS_STATE_CONNECTED)
3729 peer->handshake_params = dtls_handshake_new();
3730 if (!peer->handshake_params)
3733 peer->handshake_params->hs_state.mseq_r = 0;
3734 peer->handshake_params->hs_state.mseq_s = 0;
3736 if (peer->role == DTLS_CLIENT) {
3737 /* send ClientHello with empty Cookie */
3738 err = dtls_send_client_hello(ctx, peer, NULL, 0);
3740 dtls_warn("cannot send ClientHello\n");
3742 peer->state = DTLS_STATE_CLIENTHELLO;
3744 } else if (peer->role == DTLS_SERVER) {
3745 return dtls_send_hello_request(ctx, peer);
3752 handle_handshake_msg(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
3753 const dtls_peer_type role, const dtls_state_t state,
3754 uint8 *data, size_t data_length) {
3758 /* This will clear the retransmission buffer if we get an expected
3759 * handshake message. We have to make sure that no handshake message
3760 * should get expected when we still should retransmit something, when
3761 * we do everything accordingly to the DTLS 1.2 standard this should
3762 * not be a problem. */
3764 dtls_stop_retransmission(ctx, peer);
3767 /* The following switch construct handles the given message with
3768 * respect to the current internal state for this peer. In case of
3769 * error, it is left with return 0. */
3771 dtls_debug("handle handshake packet of type: %s (%i)\n",
3772 dtls_handshake_type_to_name(data[0]), data[0]);
3775 /************************************************************************
3777 ************************************************************************/
3778 case DTLS_HT_HELLO_VERIFY_REQUEST:
3780 if (state != DTLS_STATE_CLIENTHELLO) {
3781 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3784 err = check_server_hello_verify_request(ctx, peer, data, data_length);
3786 dtls_warn("error in check_server_hello_verify_request err: %i\n", err);
3791 case DTLS_HT_SERVER_HELLO:
3793 if (state != DTLS_STATE_CLIENTHELLO) {
3794 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3797 err = check_server_hello(ctx, peer, data, data_length);
3799 dtls_warn("error in check_server_hello err: %i\n", err);
3802 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher))
3803 peer->state = DTLS_STATE_WAIT_SERVERCERTIFICATE; //ecdsa
3804 else if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher) ||
3805 is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher))
3806 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE; //ecdh
3808 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE; //psk
3809 /* update_hs_hash(peer, data, data_length); */
3813 #if defined(DTLS_ECC) || defined(DTLS_X509)
3814 case DTLS_HT_CERTIFICATE:
3816 if ((role == DTLS_CLIENT && state != DTLS_STATE_WAIT_SERVERCERTIFICATE) ||
3817 (role == DTLS_SERVER && state != DTLS_STATE_WAIT_CLIENTCERTIFICATE)) {
3818 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3821 if (CALL(ctx, is_x509_active) == 0)
3822 err = check_peer_certificate_x509(ctx, peer, data, data_length);
3824 #endif /* DTLS_X509 */
3825 err = check_peer_certificate(ctx, peer, data, data_length);
3827 dtls_warn("error in check_peer_certificate err: %i\n", err);
3830 if (role == DTLS_CLIENT) {
3831 peer->state = DTLS_STATE_WAIT_SERVERKEYEXCHANGE;
3832 } else if (role == DTLS_SERVER){
3833 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE;
3835 /* update_hs_hash(peer, data, data_length); */
3838 #endif /* DTLS_ECC */
3840 case DTLS_HT_SERVER_KEY_EXCHANGE:
3842 #if defined(DTLS_ECC) || defined(DTLS_X509)
3843 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3844 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3845 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3847 err = check_server_key_exchange_ecdsa(ctx, peer, data, data_length);
3850 if (is_tls_ecdh_anon_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3851 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3852 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3854 err = check_server_key_exchange_ecdh(ctx, peer, data, data_length);
3856 #endif /* DTLS_ECC */
3858 #if defined(DTLS_PSK) && defined(DTLS_ECC)
3859 if (is_tls_ecdhe_psk_with_aes_128_cbc_sha_256(peer->handshake_params->cipher)) {
3860 if (state != DTLS_STATE_WAIT_SERVERKEYEXCHANGE) {
3861 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3863 err = check_server_key_exchange_ecdhe_psk(ctx, peer, data, data_length);
3865 #endif defined(DTLS_PSK) && defined(DTLS_ECC)
3868 if (is_tls_psk_with_aes_128_ccm_8(peer->handshake_params->cipher)) {
3869 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3870 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3872 err = check_server_key_exchange_psk(ctx, peer, data, data_length);
3874 #endif /* DTLS_PSK */
3877 dtls_warn("error in check_server_key_exchange err: %i\n", err);
3880 peer->state = DTLS_STATE_WAIT_SERVERHELLODONE;
3881 /* update_hs_hash(peer, data, data_length); */
3885 case DTLS_HT_SERVER_HELLO_DONE:
3887 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3888 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3891 err = check_server_hellodone(ctx, peer, data, data_length);
3893 dtls_warn("error in check_server_hellodone err: %i\n", err);
3896 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3897 /* update_hs_hash(peer, data, data_length); */
3901 case DTLS_HT_CERTIFICATE_REQUEST:
3903 if (state != DTLS_STATE_WAIT_SERVERHELLODONE) {
3904 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3907 err = check_certificate_request(ctx, peer, data, data_length);
3909 dtls_warn("error in check_certificate_request err: %i\n", err);
3915 case DTLS_HT_FINISHED:
3916 /* expect a Finished message from server */
3918 if (state != DTLS_STATE_WAIT_FINISHED) {
3919 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3922 err = check_finished(ctx, peer, data, data_length);
3924 dtls_warn("error in check_finished err: %i\n", err);
3927 if (role == DTLS_SERVER) {
3928 /* send ServerFinished */
3929 update_hs_hash(peer, data, data_length);
3931 /* send change cipher spec message and switch to new configuration */
3932 err = dtls_send_ccs(ctx, peer);
3934 dtls_warn("cannot send CCS message\n");
3938 dtls_security_params_switch(peer);
3940 err = dtls_send_finished(ctx, peer, PRF_LABEL(server), PRF_LABEL_SIZE(server));
3942 dtls_warn("sending server Finished failed\n");
3946 dtls_handshake_free(peer->handshake_params);
3947 peer->handshake_params = NULL;
3948 dtls_debug("Handshake complete\n");
3950 peer->state = DTLS_STATE_CONNECTED;
3952 /* return here to not increase the message receive counter */
3955 /************************************************************************
3957 ************************************************************************/
3959 case DTLS_HT_CLIENT_KEY_EXCHANGE:
3960 /* handle ClientHello, update msg and msglen and goto next if not finished */
3962 if (state != DTLS_STATE_WAIT_CLIENTKEYEXCHANGE) {
3963 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3966 err = check_client_keyexchange(ctx, peer->handshake_params, data, data_length);
3968 dtls_warn("error in check_client_keyexchange err: %i\n", err);
3971 update_hs_hash(peer, data, data_length);
3973 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
3974 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
3975 peer->state = DTLS_STATE_WAIT_CERTIFICATEVERIFY; //ecdsa
3977 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC; //psk || ecdh_anon
3980 #if defined(DTLS_ECC) || defined(DTLS_X509)
3981 case DTLS_HT_CERTIFICATE_VERIFY:
3983 if (state != DTLS_STATE_WAIT_CERTIFICATEVERIFY) {
3984 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
3987 err = check_client_certificate_verify(ctx, peer, data, data_length);
3989 dtls_warn("error in check_client_certificate_verify err: %i\n", err);
3993 update_hs_hash(peer, data, data_length);
3994 peer->state = DTLS_STATE_WAIT_CHANGECIPHERSPEC;
3996 #endif /* DTLS_ECC */
3998 case DTLS_HT_CLIENT_HELLO:
4000 if ((peer && state != DTLS_STATE_CONNECTED && state != DTLS_STATE_WAIT_CLIENTHELLO) ||
4001 (!peer && state != DTLS_STATE_WAIT_CLIENTHELLO)) {
4002 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4005 /* When no DTLS state exists for this peer, we only allow a
4006 Client Hello message with
4008 a) a valid cookie, or
4011 Anything else will be rejected. Fragementation is not allowed
4012 here as it would require peer state as well.
4014 err = dtls_verify_peer(ctx, peer, session, state, data, data_length);
4016 dtls_warn("error in dtls_verify_peer err: %i\n", err);
4021 dtls_debug("server hello verify was sent\n");
4025 /* At this point, we have a good relationship with this peer. This
4026 * state is left for re-negotiation of key material. */
4027 /* As per RFC 6347 - section 4.2.8 if this is an attempt to
4028 * rehandshake, we can delete the existing key material
4029 * as the client has demonstrated reachibility by completing
4030 * the cookie exchange */
4031 if (peer && state == DTLS_STATE_WAIT_CLIENTHELLO) {
4032 dtls_debug("removing the peer\n");
4033 #ifndef WITH_CONTIKI
4034 HASH_DEL_PEER(ctx->peers, peer);
4035 #else /* WITH_CONTIKI */
4036 list_remove(ctx->peers, peer);
4037 #endif /* WITH_CONTIKI */
4039 dtls_free_peer(peer);
4043 dtls_debug("creating new peer\n");
4044 dtls_security_parameters_t *security;
4046 /* msg contains a Client Hello with a valid cookie, so we can
4047 * safely create the server state machine and continue with
4049 peer = dtls_new_peer(session);
4051 dtls_alert("cannot create peer\n");
4052 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4054 peer->role = DTLS_SERVER;
4056 /* Initialize record sequence number to 1 for new peers. The first
4057 * record with sequence number 0 is a stateless Hello Verify Request.
4059 security = dtls_security_params(peer);
4061 dtls_add_peer(ctx, peer);
4063 if (peer && !peer->handshake_params) {
4064 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4066 peer->handshake_params = dtls_handshake_new();
4067 if (!peer->handshake_params)
4068 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4070 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4071 peer->handshake_params->hs_state.mseq_r = dtls_uint16_to_int(hs_header->message_seq);
4072 peer->handshake_params->hs_state.mseq_s = 1;
4075 clear_hs_hash(peer);
4077 /* First negotiation step: check for PSK
4079 * Note that we already have checked that msg is a Handshake
4080 * message containing a ClientHello. dtls_get_cipher() therefore
4081 * does not check again.
4083 err = dtls_update_parameters(ctx, peer, data, data_length);
4085 dtls_warn("error updating security parameters\n");
4089 /* update finish MAC */
4090 update_hs_hash(peer, data, data_length);
4092 err = dtls_send_server_hello_msgs(ctx, peer);
4096 if (is_tls_ecdhe_ecdsa_with_aes_128_ccm_8(peer->handshake_params->cipher) &&
4097 (is_ecdsa_client_auth_supported(ctx) || (is_x509_client_auth_supported(ctx))))
4098 peer->state = DTLS_STATE_WAIT_CLIENTCERTIFICATE; //ecdhe
4100 peer->state = DTLS_STATE_WAIT_CLIENTKEYEXCHANGE; //psk, ecdh_anon
4102 /* after sending the ServerHelloDone, we expect the
4103 * ClientKeyExchange (possibly containing the PSK id),
4104 * followed by a ChangeCipherSpec and an encrypted Finished.
4109 case DTLS_HT_HELLO_REQUEST:
4111 if (state != DTLS_STATE_CONNECTED) {
4112 /* we should just ignore such packets when in handshake */
4116 if (peer && !peer->handshake_params) {
4117 peer->handshake_params = dtls_handshake_new();
4118 if (!peer->handshake_params)
4119 return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
4121 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4122 peer->handshake_params->hs_state.mseq_r = 0;
4123 peer->handshake_params->hs_state.mseq_s = 0;
4126 /* send ClientHello with empty Cookie */
4127 err = dtls_send_client_hello(ctx, peer, NULL, 0);
4129 dtls_warn("cannot send ClientHello\n");
4132 peer->state = DTLS_STATE_CLIENTHELLO;
4136 dtls_crit("unhandled message %d\n", data[0]);
4137 return dtls_alert_fatal_create(DTLS_ALERT_UNEXPECTED_MESSAGE);
4140 if (peer && peer->handshake_params && err >= 0) {
4141 peer->handshake_params->hs_state.mseq_r++;
4148 handle_handshake(dtls_context_t *ctx, dtls_peer_t *peer, session_t *session,
4149 const dtls_peer_type role, const dtls_state_t state,
4150 uint8 *data, size_t data_length)
4152 dtls_handshake_header_t *hs_header;
4155 if (data_length < DTLS_HS_LENGTH) {
4156 dtls_warn("handshake message too short\n");
4157 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4159 hs_header = DTLS_HANDSHAKE_HEADER(data);
4161 dtls_debug("received handshake packet of type: %s (%i)\n",
4162 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4164 if (!peer || !peer->handshake_params) {
4165 /* This is the initial ClientHello */
4166 if (hs_header->msg_type != DTLS_HT_CLIENT_HELLO && !peer) {
4167 dtls_warn("If there is no peer only ClientHello is allowed\n");
4168 return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
4171 /* This is a ClientHello or Hello Request send when doing TLS renegotiation */
4172 if (hs_header->msg_type == DTLS_HT_CLIENT_HELLO ||
4173 hs_header->msg_type == DTLS_HT_HELLO_REQUEST) {
4174 return handle_handshake_msg(ctx, peer, session, role, state, data,
4177 dtls_warn("ignore unexpected handshake message\n");
4182 if (dtls_uint16_to_int(hs_header->message_seq) < peer->handshake_params->hs_state.mseq_r) {
4183 dtls_warn("The message sequence number is too small, expected %i, got: %i\n",
4184 peer->handshake_params->hs_state.mseq_r, dtls_uint16_to_int(hs_header->message_seq));
4186 } else if (dtls_uint16_to_int(hs_header->message_seq) > peer->handshake_params->hs_state.mseq_r) {
4187 /* A packet in between is missing, buffer this packet. */
4190 /* TODO: only add packet that are not too new. */
4191 if (data_length > DTLS_MAX_BUF) {
4192 dtls_warn("the packet is too big to buffer for reoder\n");
4196 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4198 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4199 if (dtls_uint16_to_int(node_header->message_seq) == dtls_uint16_to_int(hs_header->message_seq)) {
4200 dtls_warn("a packet with this sequence number is already stored\n");
4203 node = netq_next(node);
4206 n = netq_node_new(data_length);
4208 dtls_warn("no space in reoder buffer\n");
4213 n->length = data_length;
4214 memcpy(n->data, data, data_length);
4216 if (!netq_insert_node(peer->handshake_params->reorder_queue, n)) {
4217 dtls_warn("cannot add packet to reoder buffer\n");
4220 dtls_info("Added packet for reordering\n");
4222 } else if (dtls_uint16_to_int(hs_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4223 /* Found the expected packet, use this and all the buffered packet */
4226 res = handle_handshake_msg(ctx, peer, session, role, state, data, data_length);
4230 /* We do not know in which order the packet are in the list just search the list for every packet. */
4231 while (next && peer->handshake_params) {
4233 netq_t *node = netq_head(peer->handshake_params->reorder_queue);
4235 dtls_handshake_header_t *node_header = DTLS_HANDSHAKE_HEADER(node->data);
4237 if (dtls_uint16_to_int(node_header->message_seq) == peer->handshake_params->hs_state.mseq_r) {
4238 netq_remove(peer->handshake_params->reorder_queue, node);
4240 res = handle_handshake_msg(ctx, peer, session, role, peer->state, node->data, node->length);
4247 node = netq_next(node);
4258 handle_ccs(dtls_context_t *ctx, dtls_peer_t *peer,
4259 uint8 *record_header, uint8 *data, size_t data_length)
4262 dtls_handshake_parameters_t *handshake = peer->handshake_params;
4264 /* A CCS message is handled after a KeyExchange message was
4265 * received from the client. When security parameters have been
4266 * updated successfully and a ChangeCipherSpec message was sent
4267 * by ourself, the security context is switched and the record
4268 * sequence number is reset. */
4270 if (!peer || peer->state != DTLS_STATE_WAIT_CHANGECIPHERSPEC) {
4271 dtls_warn("expected ChangeCipherSpec during handshake\n");
4275 if (data_length < 1 || data[0] != 1)
4276 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4278 /* Just change the cipher when we are on the same epoch */
4279 if (peer->role == DTLS_SERVER) {
4280 err = calculate_key_block(ctx, handshake, peer,
4281 &peer->session, peer->role);
4287 peer->state = DTLS_STATE_WAIT_FINISHED;
4293 * Handles incoming Alert messages. This function returns \c 1 if the
4294 * connection should be closed and the peer is to be invalidated.
4297 handle_alert(dtls_context_t *ctx, dtls_peer_t *peer,
4298 uint8 *record_header, uint8 *data, size_t data_length) {
4299 int free_peer = 0; /* indicates whether to free peer */
4301 if (data_length < 2)
4302 return dtls_alert_fatal_create(DTLS_ALERT_DECODE_ERROR);
4304 dtls_info("** Alert: level %d, description %d\n", data[0], data[1]);
4307 dtls_warn("got an alert for an unknown peer, we probably already removed it, ignore it\n");
4311 /* The peer object is invalidated for FATAL alerts and close
4312 * notifies. This is done in two steps.: First, remove the object
4313 * from our list of peers. After that, the event handler callback is
4314 * invoked with the still existing peer object. Finally, the storage
4315 * used by peer is released.
4317 if (data[0] == DTLS_ALERT_LEVEL_FATAL || data[1] == DTLS_ALERT_CLOSE_NOTIFY) {
4318 dtls_alert("%d invalidate peer\n", data[1]);
4320 #ifndef WITH_CONTIKI
4321 HASH_DEL_PEER(ctx->peers, peer);
4322 #else /* WITH_CONTIKI */
4323 list_remove(ctx->peers, peer);
4326 PRINTF("removed peer [");
4327 PRINT6ADDR(&peer->session.addr);
4328 PRINTF("]:%d\n", uip_ntohs(peer->session.port));
4330 #endif /* WITH_CONTIKI */
4336 (void)CALL(ctx, event, &peer->session,
4337 (dtls_alert_level_t)data[0], (unsigned short)data[1]);
4339 case DTLS_ALERT_CLOSE_NOTIFY:
4340 /* If state is DTLS_STATE_CLOSING, we have already sent a
4341 * close_notify so, do not send that again. */
4342 if (peer->state != DTLS_STATE_CLOSING) {
4343 peer->state = DTLS_STATE_CLOSING;
4344 dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_CLOSE_NOTIFY);
4346 peer->state = DTLS_STATE_CLOSED;
4353 dtls_stop_retransmission(ctx, peer);
4354 dtls_destroy_peer(ctx, peer, 0);
4360 static int dtls_alert_send_from_err(dtls_context_t *ctx, dtls_peer_t *peer,
4361 session_t *session, int err)
4366 if (err < -(1 << 8) && err > -(3 << 8)) {
4367 level = ((-err) & 0xff00) >> 8;
4368 desc = (-err) & 0xff;
4370 peer = dtls_get_peer(ctx, session);
4373 peer->state = DTLS_STATE_CLOSING;
4374 return dtls_send_alert(ctx, peer, level, desc);
4376 } else if (err == -1) {
4378 peer = dtls_get_peer(ctx, session);
4381 peer->state = DTLS_STATE_CLOSING;
4382 return dtls_send_alert(ctx, peer, DTLS_ALERT_LEVEL_FATAL, DTLS_ALERT_INTERNAL_ERROR);
4389 * Handles incoming data as DTLS message from given peer.
4392 dtls_handle_message(dtls_context_t *ctx,
4394 uint8 *msg, int msglen) {
4395 dtls_peer_t *peer = NULL;
4396 unsigned int rlen; /* record length */
4397 uint8 *data; /* (decrypted) payload */
4398 int data_length; /* length of decrypted payload
4399 (without MAC and padding) */
4402 /* check if we have DTLS state for addr/port/ifindex */
4403 peer = dtls_get_peer(ctx, session);
4406 dtls_debug("dtls_handle_message: PEER NOT FOUND\n");
4407 dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer addr", session);
4409 dtls_debug("dtls_handle_message: FOUND PEER\n");
4412 while ((rlen = is_record(msg,msglen))) {
4413 dtls_peer_type role;
4416 dtls_debug("got packet %d (%d bytes)\n", msg[0], rlen);
4418 data_length = decrypt_verify(peer, msg, rlen, &data);
4419 if (data_length < 0) {
4420 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4421 data = msg + DTLS_RH_LENGTH;
4422 data_length = rlen - DTLS_RH_LENGTH;
4423 state = DTLS_STATE_WAIT_CLIENTHELLO;
4426 int err = dtls_alert_fatal_create(DTLS_ALERT_DECRYPT_ERROR);
4427 dtls_info("decrypt_verify() failed\n");
4428 if (peer->state < DTLS_STATE_CONNECTED) {
4429 dtls_alert_send_from_err(ctx, peer, &peer->session, err);
4430 peer->state = DTLS_STATE_CLOSED;
4431 /* dtls_stop_retransmission(ctx, peer); */
4432 dtls_destroy_peer(ctx, peer, 1);
4438 state = peer->state;
4441 /* is_record() ensures that msg contains at least a record header */
4442 data = msg + DTLS_RH_LENGTH;
4443 data_length = rlen - DTLS_RH_LENGTH;
4444 state = DTLS_STATE_WAIT_CLIENTHELLO;
4448 dtls_debug_hexdump("receive header", msg, sizeof(dtls_record_header_t));
4449 dtls_debug_hexdump("receive unencrypted", data, data_length);
4451 /* Handle received record according to the first byte of the
4452 * message, i.e. the subprotocol. We currently do not support
4453 * combining multiple fragments of one type into a single
4458 case DTLS_CT_CHANGE_CIPHER_SPEC:
4460 dtls_stop_retransmission(ctx, peer);
4462 err = handle_ccs(ctx, peer, msg, data, data_length);
4464 dtls_warn("error while handling ChangeCipherSpec message\n");
4465 dtls_alert_send_from_err(ctx, peer, session, err);
4467 /* invalidate peer */
4468 dtls_destroy_peer(ctx, peer, 1);
4477 dtls_stop_retransmission(ctx, peer);
4479 err = handle_alert(ctx, peer, msg, data, data_length);
4480 if (err < 0 || err == 1) {
4481 dtls_warn("received alert, peer has been invalidated\n");
4482 /* handle alert has invalidated peer */
4484 return err < 0 ?err:-1;
4488 case DTLS_CT_HANDSHAKE:
4489 /* Handshake messages other than Finish must use the current
4490 * epoch, Finish has epoch + 1. */
4493 uint16_t expected_epoch = dtls_security_params(peer)->epoch;
4494 uint16_t msg_epoch =
4495 dtls_uint16_to_int(DTLS_RECORD_HEADER(msg)->epoch);
4497 /* The new security parameters must be used for all messages
4498 * that are sent after the ChangeCipherSpec message. This
4499 * means that the client's Finished message uses epoch + 1
4500 * while the server is still in the old epoch.
4502 if (role == DTLS_SERVER && state == DTLS_STATE_WAIT_FINISHED) {
4506 if (expected_epoch != msg_epoch) {
4507 if (hs_attempt_with_existing_peer(msg, rlen, peer)) {
4508 state = DTLS_STATE_WAIT_CLIENTHELLO;
4511 dtls_warn("Wrong epoch, expected %i, got: %i\n",
4512 expected_epoch, msg_epoch);
4518 err = handle_handshake(ctx, peer, session, role, state, data, data_length);
4520 dtls_warn("error while handling handshake packet\n");
4521 dtls_alert_send_from_err(ctx, peer, session, err);
4524 if (peer && peer->state == DTLS_STATE_CONNECTED) {
4525 /* stop retransmissions */
4526 dtls_stop_retransmission(ctx, peer);
4527 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECTED);
4531 case DTLS_CT_APPLICATION_DATA:
4532 dtls_info("** application data:\n");
4534 dtls_warn("no peer available, send an alert\n");
4535 // TODO: should we send a alert here?
4538 dtls_stop_retransmission(ctx, peer);
4539 CALL(ctx, read, &peer->session, data, data_length);
4542 dtls_info("dropped unknown message of type %d\n",msg[0]);
4545 /* advance msg by length of ciphertext */
4554 dtls_new_context(void *app_data) {
4557 #ifndef WITH_CONTIKI
4558 FILE *urandom = fopen("/dev/urandom", "r");
4559 unsigned char buf[sizeof(unsigned long)];
4560 #endif /* WITH_CONTIKI */
4564 /* FIXME: need something better to init PRNG here */
4565 dtls_prng_init(now);
4566 #else /* WITH_CONTIKI */
4568 dtls_emerg("cannot initialize PRNG\n");
4572 if (fread(buf, 1, sizeof(buf), urandom) != sizeof(buf)) {
4573 dtls_emerg("cannot initialize PRNG\n");
4578 dtls_prng_init((unsigned long)*buf);
4579 #endif /* WITH_CONTIKI */
4581 c = malloc_context();
4585 memset(c, 0, sizeof(dtls_context_t));
4588 LIST_STRUCT_INIT(c, sendqueue);
4591 LIST_STRUCT_INIT(c, peers);
4592 /* LIST_STRUCT_INIT(c, key_store); */
4594 process_start(&dtls_retransmit_process, (char *)c);
4595 PROCESS_CONTEXT_BEGIN(&dtls_retransmit_process);
4596 /* the retransmit timer must be initialized to some large value */
4597 etimer_set(&c->retransmit_timer, 0xFFFF);
4598 PROCESS_CONTEXT_END(&coap_retransmit_process);
4599 #endif /* WITH_CONTIKI */
4601 if (dtls_prng(c->cookie_secret, DTLS_COOKIE_SECRET_LENGTH))
4602 c->cookie_secret_age = now;
4609 dtls_alert("cannot create DTLS context\n");
4611 dtls_free_context(c);
4616 dtls_free_context(dtls_context_t *ctx) {
4623 #ifndef WITH_CONTIKI
4627 HASH_ITER(hh, ctx->peers, p, tmp) {
4628 dtls_destroy_peer(ctx, p, 1);
4631 #else /* WITH_CONTIKI */
4632 for (p = list_head(ctx->peers); p; p = list_item_next(p))
4633 dtls_destroy_peer(ctx, p, 1);
4634 #endif /* WITH_CONTIKI */
4640 dtls_connect_peer(dtls_context_t *ctx, dtls_peer_t *peer) {
4647 /* check if the same peer is already in our list */
4648 if (peer == dtls_get_peer(ctx, &peer->session)) {
4649 dtls_debug("found peer, try to re-connect\n");
4650 return dtls_renegotiate(ctx, &peer->session);
4653 /* set local peer role to client, remote is server */
4654 peer->role = DTLS_CLIENT;
4656 dtls_add_peer(ctx, peer);
4658 /* send ClientHello with empty Cookie */
4659 peer->handshake_params = dtls_handshake_new();
4660 if (!peer->handshake_params)
4663 peer->handshake_params->hs_state.mseq_r = 0;
4664 peer->handshake_params->hs_state.mseq_s = 0;
4665 LIST_STRUCT_INIT(peer->handshake_params, reorder_queue);
4666 res = dtls_send_client_hello(ctx, peer, NULL, 0);
4668 dtls_warn("cannot send ClientHello\n");
4670 peer->state = DTLS_STATE_CLIENTHELLO;
4676 dtls_connect(dtls_context_t *ctx, const session_t *dst) {
4680 peer = dtls_get_peer(ctx, dst);
4683 peer = dtls_new_peer(dst);
4686 dtls_crit("cannot create new peer\n");
4690 res = dtls_connect_peer(ctx, peer);
4692 /* Invoke event callback to indicate connection attempt or
4693 * re-negotiation. */
4695 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_CONNECT);
4696 } else if (res == 0) {
4697 CALL(ctx, event, &peer->session, 0, DTLS_EVENT_RENEGOTIATE);
4704 dtls_retransmit(dtls_context_t *context, netq_t *node) {
4705 if (!context || !node)
4708 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
4709 if (node->retransmit_cnt < DTLS_DEFAULT_MAX_RETRANSMIT) {
4710 unsigned char sendbuf[DTLS_MAX_BUF];
4711 size_t len = sizeof(sendbuf);
4713 unsigned char *data = node->data;
4714 size_t length = node->length;
4716 dtls_security_parameters_t *security = dtls_security_params_epoch(node->peer, node->epoch);
4719 node->retransmit_cnt++;
4720 node->t = now + (node->timeout << node->retransmit_cnt);
4721 netq_insert_node(context->sendqueue, node);
4723 if (node->type == DTLS_CT_HANDSHAKE) {
4724 dtls_handshake_header_t *hs_header = DTLS_HANDSHAKE_HEADER(data);
4726 dtls_debug("** retransmit handshake packet of type: %s (%i)\n",
4727 dtls_handshake_type_to_name(hs_header->msg_type), hs_header->msg_type);
4729 dtls_debug("** retransmit packet\n");
4732 err = dtls_prepare_record(node->peer, security, node->type, &data, &length,
4735 dtls_warn("can not retransmit packet, err: %i\n", err);
4738 dtls_debug_hexdump("retransmit header", sendbuf,
4739 sizeof(dtls_record_header_t));
4740 dtls_debug_hexdump("retransmit unencrypted", node->data, node->length);
4742 (void)CALL(context, write, &node->peer->session, sendbuf, len);
4746 /* no more retransmissions, remove node from system */
4748 dtls_debug("** removed transaction\n");
4750 /* And finally delete the node */
4751 netq_node_free(node);
4755 dtls_stop_retransmission(dtls_context_t *context, dtls_peer_t *peer) {
4757 node = list_head(context->sendqueue);
4760 if (dtls_session_equals(&node->peer->session, &peer->session)) {
4762 node = list_item_next(node);
4763 list_remove(context->sendqueue, tmp);
4764 netq_node_free(tmp);
4766 node = list_item_next(node);
4771 dtls_check_retransmit(dtls_context_t *context, clock_time_t *next) {
4773 netq_t *node = netq_head(context->sendqueue);
4776 while (node && node->t <= now) {
4777 netq_pop_first(context->sendqueue);
4778 dtls_retransmit(context, node);
4779 node = netq_head(context->sendqueue);
4787 dtls_prf_with_current_keyblock(dtls_context_t *ctx, session_t *session,
4788 const uint8_t* label, const uint32_t labellen,
4789 const uint8_t* random1, const uint32_t random1len,
4790 const uint8_t* random2, const uint32_t random2len,
4791 uint8_t* buf, const uint32_t buflen) {
4792 dtls_peer_t *peer = NULL;
4793 dtls_security_parameters_t *security = NULL;
4796 if(!ctx || !session || !label || !buf || labellen == 0 || buflen == 0) {
4797 dtls_warn("dtls_prf_with_current_keyblock(): invalid parameter\n");
4801 peer = dtls_get_peer(ctx, session);
4803 dtls_warn("dtls_prf_with_current_keyblock(): cannot find peer\n");
4807 security = dtls_security_params(peer);
4809 dtls_crit("dtls_prf_with_current_keyblock(): peer has empty security parameters\n");
4813 /* note that keysize should never be zero as bad things will happen */
4814 keysize = dtls_kb_size(security, peer->role);
4815 assert(keysize > 0);
4817 return dtls_prf(security->key_block, keysize,
4819 random1, random1len,
4820 random2, random2len,
4825 /*---------------------------------------------------------------------------*/
4826 /* message retransmission */
4827 /*---------------------------------------------------------------------------*/
4828 PROCESS_THREAD(dtls_retransmit_process, ev, data)
4835 dtls_debug("Started DTLS retransmit process\r\n");
4839 if (ev == PROCESS_EVENT_TIMER) {
4840 if (etimer_expired(&the_dtls_context.retransmit_timer)) {
4842 node = list_head(the_dtls_context.sendqueue);
4845 if (node && node->t <= now) {
4846 dtls_retransmit(&the_dtls_context, list_pop(the_dtls_context.sendqueue));
4847 node = list_head(the_dtls_context.sendqueue);
4850 /* need to set timer to some value even if no nextpdu is available */
4852 etimer_set(&the_dtls_context.retransmit_timer,
4853 node->t <= now ? 1 : node->t - now);
4855 etimer_set(&the_dtls_context.retransmit_timer, 0xFFFF);
4863 #endif /* WITH_CONTIKI */