1 /* dtls -- a very basic DTLS implementation
3 * Copyright (C) 2011--2012 Olaf Bergmann <bergmann@tzi.org>
4 * Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
7 * Modified source code for micro-ecc porting,
9 * Following functions are removed:
10 * - dtls_ec_key_to_uint32
11 * - dtls_ec_key_from_uint32
12 * Following functions are modified:
13 * - dtls_ecdh_pre_master_secret
14 * - dtls_ecdsa_generate_key
15 * - dtls_ecdsa_create_sig_hash
16 * - dtls_ecdsa_verify_sig_hash
18 * Permission is hereby granted, free of charge, to any person
19 * obtaining a copy of this software and associated documentation
20 * files (the "Software"), to deal in the Software without
21 * restriction, including without limitation the rights to use, copy,
22 * modify, merge, publish, distribute, sublicense, and/or sell copies
23 * of the Software, and to permit persons to whom the Software is
24 * furnished to do so, subject to the following conditions:
26 * The above copyright notice and this permission notice shall be
27 * included in all copies or substantial portions of the Software.
29 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
33 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
34 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
35 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
42 #include "dtls_config.h"
57 #include "aes/rijndael.h"
58 #include "sha2/sha2.h"
63 #if !defined(WITH_CONTIKI) && !defined(_WIN32)
67 #define HMAC_UPDATE_SEED(Context,Seed,Length) \
68 if (Seed) dtls_hmac_update(Context, (Seed), (Length))
70 static struct dtls_cipher_context_t cipher_context;
71 #if !defined(WITH_CONTIKI) && !defined(_WIN32)
72 static pthread_mutex_t cipher_context_mutex = PTHREAD_MUTEX_INITIALIZER;
75 static struct dtls_cipher_context_t *dtls_cipher_context_get(void)
77 #if !defined(WITH_CONTIKI) && !defined(_WIN32)
78 pthread_mutex_lock(&cipher_context_mutex);
80 return &cipher_context;
83 static void dtls_cipher_context_release(void)
85 #if !defined(WITH_CONTIKI) && !defined(_WIN32)
86 pthread_mutex_unlock(&cipher_context_mutex);
95 static dtls_handshake_parameters_t *dtls_handshake_malloc() {
96 return malloc(sizeof(dtls_handshake_parameters_t));
99 static void dtls_handshake_dealloc(dtls_handshake_parameters_t *handshake) {
103 static dtls_security_parameters_t *dtls_security_malloc() {
104 return malloc(sizeof(dtls_security_parameters_t));
107 static void dtls_security_dealloc(dtls_security_parameters_t *security) {
110 #else /* WITH_CONTIKI */
113 MEMB(handshake_storage, dtls_handshake_parameters_t, DTLS_HANDSHAKE_MAX);
114 MEMB(security_storage, dtls_security_parameters_t, DTLS_SECURITY_MAX);
117 memb_init(&handshake_storage);
118 memb_init(&security_storage);
121 static dtls_handshake_parameters_t *dtls_handshake_malloc() {
122 return memb_alloc(&handshake_storage);
125 static void dtls_handshake_dealloc(dtls_handshake_parameters_t *handshake) {
126 memb_free(&handshake_storage, handshake);
129 static dtls_security_parameters_t *dtls_security_malloc() {
130 return memb_alloc(&security_storage);
133 static void dtls_security_dealloc(dtls_security_parameters_t *security) {
134 memb_free(&security_storage, security);
136 #endif /* WITH_CONTIKI */
138 dtls_handshake_parameters_t *dtls_handshake_new()
140 dtls_handshake_parameters_t *handshake;
142 handshake = dtls_handshake_malloc();
144 dtls_crit("can not allocate a handshake struct\n");
148 memset(handshake, 0, sizeof(*handshake));
151 /* initialize the handshake hash wrt. the hard-coded DTLS version */
152 dtls_debug("DTLSv12: initialize HASH_SHA256\n");
153 /* TLS 1.2: PRF(secret, label, seed) = P_<hash>(secret, label + seed) */
154 /* FIXME: we use the default SHA256 here, might need to support other
155 hash functions as well */
156 dtls_hash_init(&handshake->hs_state.hs_hash);
161 void dtls_handshake_free(dtls_handshake_parameters_t *handshake)
166 netq_delete_all(handshake->reorder_queue);
167 dtls_handshake_dealloc(handshake);
170 dtls_security_parameters_t *dtls_security_new()
172 dtls_security_parameters_t *security;
174 security = dtls_security_malloc();
176 dtls_crit("can not allocate a security struct\n");
180 memset(security, 0, sizeof(*security));
183 security->cipher = TLS_NULL_WITH_NULL_NULL;
184 security->compression = TLS_COMPRESSION_NULL;
189 void dtls_security_free(dtls_security_parameters_t *security)
194 dtls_security_dealloc(security);
198 dtls_p_hash(dtls_hashfunc_t h,
199 const unsigned char *key, size_t keylen,
200 const unsigned char *label, size_t labellen,
201 const unsigned char *random1, size_t random1len,
202 const unsigned char *random2, size_t random2len,
203 unsigned char *buf, size_t buflen) {
204 dtls_hmac_context_t *hmac_a, *hmac_p;
206 unsigned char A[DTLS_HMAC_DIGEST_SIZE];
207 unsigned char tmp[DTLS_HMAC_DIGEST_SIZE];
208 size_t dlen; /* digest length */
209 size_t len = 0; /* result length */
211 hmac_a = dtls_hmac_new(key, keylen);
215 /* calculate A(1) from A(0) == seed */
216 HMAC_UPDATE_SEED(hmac_a, label, labellen);
217 HMAC_UPDATE_SEED(hmac_a, random1, random1len);
218 HMAC_UPDATE_SEED(hmac_a, random2, random2len);
220 dlen = dtls_hmac_finalize(hmac_a, A);
222 hmac_p = dtls_hmac_new(key, keylen);
226 while (len + dlen < buflen) {
228 /* FIXME: rewrite loop to avoid superflous call to dtls_hmac_init() */
229 dtls_hmac_init(hmac_p, key, keylen);
230 dtls_hmac_update(hmac_p, A, dlen);
232 HMAC_UPDATE_SEED(hmac_p, label, labellen);
233 HMAC_UPDATE_SEED(hmac_p, random1, random1len);
234 HMAC_UPDATE_SEED(hmac_p, random2, random2len);
236 len += dtls_hmac_finalize(hmac_p, tmp);
237 memcpy(buf, tmp, dlen);
240 /* calculate A(i+1) */
241 dtls_hmac_init(hmac_a, key, keylen);
242 dtls_hmac_update(hmac_a, A, dlen);
243 dtls_hmac_finalize(hmac_a, A);
246 dtls_hmac_init(hmac_p, key, keylen);
247 dtls_hmac_update(hmac_p, A, dlen);
249 HMAC_UPDATE_SEED(hmac_p, label, labellen);
250 HMAC_UPDATE_SEED(hmac_p, random1, random1len);
251 HMAC_UPDATE_SEED(hmac_p, random2, random2len);
253 dtls_hmac_finalize(hmac_p, tmp);
254 memcpy(buf, tmp, buflen - len);
257 dtls_hmac_free(hmac_a);
258 dtls_hmac_free(hmac_p);
264 dtls_prf(const unsigned char *key, size_t keylen,
265 const unsigned char *label, size_t labellen,
266 const unsigned char *random1, size_t random1len,
267 const unsigned char *random2, size_t random2len,
268 unsigned char *buf, size_t buflen) {
270 /* Clear the result buffer */
271 memset(buf, 0, buflen);
272 return dtls_p_hash(HASH_SHA256,
281 dtls_mac(dtls_hmac_context_t *hmac_ctx,
282 const unsigned char *record,
283 const unsigned char *packet, size_t length,
284 unsigned char *buf) {
286 dtls_int_to_uint16(L, length);
289 dtls_hmac_update(hmac_ctx, record +3, sizeof(uint16) + sizeof(uint48));
290 dtls_hmac_update(hmac_ctx, record, sizeof(uint8) + sizeof(uint16));
291 dtls_hmac_update(hmac_ctx, L, sizeof(uint16));
292 dtls_hmac_update(hmac_ctx, packet, length);
294 dtls_hmac_finalize(hmac_ctx, buf);
298 dtls_ccm_encrypt(aes128_t *ccm_ctx, const unsigned char *src, size_t srclen,
300 unsigned char *nounce,
301 const unsigned char *aad, size_t la) {
306 len = dtls_ccm_encrypt_message(&ccm_ctx->ctx, 8 /* M */,
307 max(2, 15 - DTLS_CCM_NONCE_SIZE),
315 dtls_ccm_decrypt(aes128_t *ccm_ctx, const unsigned char *src,
316 size_t srclen, unsigned char *buf,
317 unsigned char *nounce,
318 const unsigned char *aad, size_t la) {
323 len = dtls_ccm_decrypt_message(&ccm_ctx->ctx, 8 /* M */,
324 max(2, 15 - DTLS_CCM_NONCE_SIZE),
332 dtls_cbc_encrypt(aes128_t *aes_ctx,
333 unsigned char *mac_key, size_t mac_keylen,
334 const unsigned char *iv,
335 const unsigned char *src, size_t srclen,
336 unsigned char *buf) {
338 unsigned char cbc[DTLS_BLK_LENGTH];
339 unsigned char tmp[DTLS_BLK_LENGTH];
341 const unsigned char *dtls_hdr = NULL;
344 dtls_hmac_context_t* hmac_ctx = NULL;
349 dtls_hdr = src - DTLS_CBC_IV_LENGTH - sizeof(dtls_record_header_t);
351 //Calculate MAC : Append the MAC code to end of content
352 hmac_ctx = dtls_hmac_new(mac_key, mac_keylen);
357 dtls_hmac_free(hmac_ctx);
359 dtls_debug_dump("[MAC]",
361 DTLS_HMAC_DIGEST_SIZE);
363 paddinglen = DTLS_BLK_LENGTH - ((srclen + DTLS_HMAC_DIGEST_SIZE) % DTLS_BLK_LENGTH);
366 memset(buf + (srclen + DTLS_HMAC_DIGEST_SIZE), paddinglen - 1, paddinglen);
368 memcpy(cbc, iv, DTLS_BLK_LENGTH);
369 blocks = (srclen + DTLS_HMAC_DIGEST_SIZE + paddinglen) / DTLS_BLK_LENGTH;
371 for (i = 0; i < blocks; i++) {
372 for (j = 0; j < DTLS_BLK_LENGTH; j++) {
376 rijndael_encrypt(&aes_ctx->ctx, cbc, tmp);
377 memcpy(cbc, tmp, DTLS_BLK_LENGTH);
378 memcpy(pos, cbc, DTLS_BLK_LENGTH);
379 pos += DTLS_BLK_LENGTH;
382 dtls_debug_dump("[Encrypted Data]",
384 srclen + DTLS_HMAC_DIGEST_SIZE + paddinglen);
386 return srclen + DTLS_HMAC_DIGEST_SIZE + paddinglen;
391 dtls_cbc_decrypt(aes128_t *aes_ctx,
392 unsigned char *mac_key, size_t mac_keylen,
393 const unsigned char *iv,
394 const unsigned char *src, size_t srclen,
395 unsigned char *buf) {
397 unsigned char cbc[DTLS_BLK_LENGTH];
398 unsigned char tmp[DTLS_BLK_LENGTH];
399 unsigned char tmp2[DTLS_BLK_LENGTH];
400 unsigned char mac_buf[DTLS_HMAC_DIGEST_SIZE] = {0,};
401 const unsigned char *dtls_hdr = NULL;
405 int depaddinglen = 0;
406 uint8_t wrongpadding_flag = 0;
407 dtls_hmac_context_t* hmac_ctx = NULL;
411 dtls_hdr = src - DTLS_CBC_IV_LENGTH - sizeof(dtls_record_header_t);
413 memcpy(cbc, iv, DTLS_BLK_LENGTH);
414 blocks = srclen / DTLS_BLK_LENGTH;
416 for (i = 0; i < blocks; i++)
418 memcpy(tmp, pos, DTLS_BLK_LENGTH);
419 rijndael_decrypt(&aes_ctx->ctx, pos, tmp2);
420 memcpy(pos, tmp2, DTLS_BLK_LENGTH);
422 for (j = 0; j < DTLS_BLK_LENGTH; j++) {
426 memcpy(cbc, tmp, DTLS_BLK_LENGTH);
427 pos += DTLS_BLK_LENGTH;
431 depaddinglen = buf[srclen -1];
434 * message validation check in case of wrong key.
435 * In case of wrong padding legnth was detected
436 * set depadding length to zero in order to resist the padding oracle attack
437 * and prevent invalid memory access.
439 if(srclen <= DTLS_HMAC_DIGEST_SIZE + depaddinglen + 1) {
441 wrongpadding_flag = 1;
445 hmac_ctx = dtls_hmac_new(mac_key, mac_keylen);
449 dtls_mac(hmac_ctx, dtls_hdr, buf,
450 srclen - DTLS_HMAC_DIGEST_SIZE - depaddinglen - 1,
452 dtls_hmac_free(hmac_ctx);
454 dtls_debug_dump("[MAC]",
456 DTLS_HMAC_DIGEST_SIZE);
457 dtls_debug_dump("[Decrypted data]",
459 srclen - DTLS_HMAC_DIGEST_SIZE - depaddinglen - 1);
463 buf + (srclen - DTLS_HMAC_DIGEST_SIZE - depaddinglen - 1),
464 DTLS_HMAC_DIGEST_SIZE) != 0 || wrongpadding_flag)
466 dtls_crit("Failed to verification of MAC\n");
470 //verify the padding bytes
471 for (i =0; i < depaddinglen; i++)
473 if (buf[srclen - depaddinglen - 1 + i] != depaddinglen)
475 dtls_crit("Failed to verify padding bytes\n");
480 return srclen - DTLS_HMAC_DIGEST_SIZE - depaddinglen - 1;
485 dtls_psk_pre_master_secret(unsigned char *key, size_t keylen,
486 unsigned char *result, size_t result_len) {
487 unsigned char *p = result;
489 if (result_len < (2 * (sizeof(uint16) + keylen))) {
493 dtls_int_to_uint16(p, keylen);
496 memset(p, 0, keylen);
499 memcpy(p, result, sizeof(uint16));
502 memcpy(p, key, keylen);
504 return 2 * (sizeof(uint16) + keylen);
506 #endif /* DTLS_PSK */
508 #if defined(DTLS_ECC) || defined(DTLS_X509)
510 int dtls_ec_key_from_uint32_asn1(const uint32_t *key, size_t key_size,
511 unsigned char *buf) {
513 unsigned char *buf_orig = buf;
516 for (i = (key_size / sizeof(uint32_t)) - 1; i >= 0 ; i--) {
519 /* the first bit has to be set to zero, to indicate a poritive integer */
520 if (first && key[i] & 0x80000000) {
523 dtls_int_to_uint32(buf, key[i]);
525 } else if (first && !(key[i] & 0xFF800000)) {
526 buf[0] = (key[i] >> 16) & 0xff;
527 buf[1] = (key[i] >> 8) & 0xff;
528 buf[2] = key[i] & 0xff;
530 } else if (first && !(key[i] & 0xFFFF8000)) {
531 buf[0] = (key[i] >> 8) & 0xff;
532 buf[1] = key[i] & 0xff;
534 } else if (first && !(key[i] & 0xFFFFFF80)) {
535 buf[0] = key[i] & 0xff;
538 dtls_int_to_uint32(buf, key[i]);
543 return buf - buf_orig;
546 int dtls_ecdh_pre_master_secret(unsigned char *priv_key,
547 unsigned char *pub_key_x,
548 unsigned char *pub_key_y,
550 unsigned char *result,
553 uint8_t publicKey[64];
554 uint8_t privateKey[32];
556 if (result_len < key_size) {
561 memcpy(publicKey, pub_key_x, 32);
562 memcpy(publicKey + 32, pub_key_y, 32);
563 memcpy(privateKey, priv_key, 32);
564 uECC_shared_secret(publicKey, privateKey, result);
570 dtls_ecdsa_generate_key(unsigned char *priv_key,
571 unsigned char *pub_key_x,
572 unsigned char *pub_key_y,
575 uint8_t publicKey[64];
576 uint8_t privateKey[32];
578 uECC_make_key(publicKey, privateKey);
579 memcpy(pub_key_x, publicKey, 32);
580 memcpy(pub_key_y, publicKey + 32, 32);
581 memcpy(priv_key, privateKey, 32);
585 /* rfc4492#section-5.4 */
587 dtls_ecdsa_create_sig_hash(const unsigned char *priv_key, size_t key_size,
588 const unsigned char *sign_hash, size_t sign_hash_size,
589 uint32_t point_r[9], uint32_t point_s[9])
594 if (priv_key == NULL || key_size < 32)
596 if (sign_hash == NULL || sign_hash_size < 32)
599 uECC_sign(priv_key, sign_hash, sign);
602 for (i = 0; i < 32; i++)
604 ((uint8_t *) point_r)[i] = sign[31 - i];
605 ((uint8_t *) point_s)[i] = sign[63 - i];
610 dtls_ecdsa_create_sig(const unsigned char *priv_key, size_t key_size,
611 const unsigned char *client_random, size_t client_random_size,
612 const unsigned char *server_random, size_t server_random_size,
613 const unsigned char *keyx_params, size_t keyx_params_size,
614 uint32_t point_r[9], uint32_t point_s[9]) {
616 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
618 dtls_hash_init(&data);
619 dtls_hash_update(&data, client_random, client_random_size);
620 dtls_hash_update(&data, server_random, server_random_size);
621 dtls_hash_update(&data, keyx_params, keyx_params_size);
622 dtls_hash_finalize(sha256hash, &data);
624 dtls_ecdsa_create_sig_hash(priv_key, key_size, sha256hash,
625 sizeof(sha256hash), point_r, point_s);
628 /* rfc4492#section-5.4 */
630 dtls_ecdsa_verify_sig_hash(const unsigned char *pub_key_x,
631 const unsigned char *pub_key_y, size_t key_size,
632 const unsigned char *sign_hash, size_t sign_hash_size,
633 unsigned char *result_r, unsigned char *result_s)
635 uint8_t publicKey[64];
639 if (pub_key_x == NULL || pub_key_y == NULL || key_size < 32)
641 if (sign_hash == NULL || sign_hash_size < 32)
643 if (result_r == NULL || result_s == NULL)
646 // Copy the public key into a single buffer
647 memcpy(publicKey, pub_key_x, 32);
648 memcpy(publicKey + 32, pub_key_y, 32);
650 // Copy the signature into a single buffer
651 memcpy(sign, result_r, 32);
652 memcpy(sign + 32, result_s, 32);
654 return uECC_verify(publicKey, sign_hash, sign);
658 dtls_ecdsa_verify_sig(const unsigned char *pub_key_x,
659 const unsigned char *pub_key_y, size_t key_size,
660 const unsigned char *client_random, size_t client_random_size,
661 const unsigned char *server_random, size_t server_random_size,
662 const unsigned char *keyx_params, size_t keyx_params_size,
663 unsigned char *result_r, unsigned char *result_s) {
665 unsigned char sha256hash[DTLS_HMAC_DIGEST_SIZE];
667 dtls_hash_init(&data);
668 dtls_hash_update(&data, client_random, client_random_size);
669 dtls_hash_update(&data, server_random, server_random_size);
670 dtls_hash_update(&data, keyx_params, keyx_params_size);
671 dtls_hash_finalize(sha256hash, &data);
673 return dtls_ecdsa_verify_sig_hash(pub_key_x, pub_key_y, key_size, sha256hash,
674 sizeof(sha256hash), result_r, result_s);
676 #endif /* DTLS_ECC */
678 #if defined(DTLS_PSK) && defined(DTLS_ECC)
679 int dtls_ecdhe_psk_pre_master_secret(unsigned char *psk, size_t psklen,
680 unsigned char *ecc_priv_key,
681 unsigned char *ecc_pub_key_x,
682 unsigned char *ecc_pub_key_y,
684 unsigned char *result,
687 uint8_t eccPublicKey[64];
688 uint8_t eccPrivateKey[32];
689 unsigned char *p = result;
691 if (result_len < uECC_BYTES + psklen + (sizeof(uint16) * 2)) {
695 dtls_int_to_uint16(p, uECC_BYTES);
698 memcpy(eccPublicKey, ecc_pub_key_x, 32);
699 memcpy(eccPublicKey + 32, ecc_pub_key_y, 32);
700 memcpy(eccPrivateKey, ecc_priv_key, 32);
701 uECC_shared_secret(eccPublicKey, eccPrivateKey, p);
704 dtls_int_to_uint16(p, psklen);
707 memcpy(p, psk, psklen);
709 return uECC_BYTES + psklen + (sizeof(uint16) * 2);
711 #endif /* defined(DTLS_PSK) && defined(DTLS_ECC) */
714 dtls_encrypt(const unsigned char *src, size_t length,
716 unsigned char *nounce,
717 unsigned char *write_key, size_t write_keylen,
718 unsigned char *mac_key, size_t mac_keylen,
719 const unsigned char *aad, size_t la,
720 const dtls_cipher_t cipher)
723 struct dtls_cipher_context_t *ctx = dtls_cipher_context_get();
725 if(cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ||
726 cipher == TLS_PSK_WITH_AES_128_CCM_8) {
727 ret = rijndael_set_key_enc_only(&ctx->data.ctx, write_key, 8 * write_keylen);
729 /* cleanup everything in case the key has the wrong size */
730 dtls_warn("cannot set rijndael key\n");
735 memmove(buf, src, length);
736 ret = dtls_ccm_encrypt(&ctx->data, src, length, buf, nounce, aad, la);
738 if(cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 ||
739 cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256) {
740 ret = rijndael_set_key(&ctx->data.ctx, write_key, 8 * write_keylen);
742 /* cleanup everything in case the key has the wrong size */
743 dtls_warn("cannot set rijndael key\n");
748 memmove(buf, src, length);
749 ret = dtls_cbc_encrypt(&ctx->data, mac_key, mac_keylen, nounce, src, length, buf);
753 dtls_cipher_context_release();
758 dtls_decrypt(const unsigned char *src, size_t length,
760 unsigned char *nounce,
761 unsigned char *read_key, size_t read_keylen,
762 unsigned char *mac_key, size_t mac_keylen,
763 const unsigned char *aad, size_t la,
764 const dtls_cipher_t cipher)
767 struct dtls_cipher_context_t *ctx = dtls_cipher_context_get();
769 if(cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ||
770 cipher == TLS_PSK_WITH_AES_128_CCM_8) {
771 ret = rijndael_set_key_enc_only(&ctx->data.ctx, read_key, 8 * read_keylen);
773 /* cleanup everything in case the key has the wrong size */
774 dtls_warn("cannot set rijndael key\n");
779 memmove(buf, src, length);
780 ret = dtls_ccm_decrypt(&ctx->data, src, length, buf, nounce, aad, la);
783 if(cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 ||
784 cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256) {
785 ret = rijndael_set_key(&ctx->data.ctx, read_key, 8 * read_keylen);
787 /* cleanup everything in case the key has the wrong size */
788 dtls_warn("cannot set rijndael key\n");
793 memmove(buf, src, length);
794 ret = dtls_cbc_decrypt(&ctx->data, mac_key, mac_keylen, nounce, src, length, buf);
798 dtls_cipher_context_release();