1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 */
24
25 /**
26 * @file Data Channel Cryptography mbed TLS-specific backend interface
27 */
28
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #elif defined(_MSC_VER)
32 #include "config-msvc.h"
33 #endif
34
35 #include "syshead.h"
36
37 #if defined(ENABLE_CRYPTO_MBEDTLS)
38
39 #include "errlevel.h"
40 #include "basic.h"
41 #include "buffer.h"
42 #include "crypto.h"
43 #include "integer.h"
44 #include "crypto_backend.h"
45 #include "otime.h"
46 #include "misc.h"
47
48 #include <mbedtls/base64.h>
49 #include <mbedtls/des.h>
50 #include <mbedtls/error.h>
51 #include <mbedtls/md5.h>
52 #include <mbedtls/cipher.h>
53 #include <mbedtls/havege.h>
54 #include <mbedtls/pem.h>
55
56 #include <mbedtls/entropy.h>
57 #include <mbedtls/ssl.h>
58
59
60 /*
61 *
62 * Hardware engine support. Allows loading/unloading of engines.
63 *
64 */
65
66 void
crypto_init_lib_engine(const char * engine_name)67 crypto_init_lib_engine(const char *engine_name)
68 {
69 msg(M_WARN, "Note: mbed TLS hardware crypto engine functionality is not "
70 "available");
71 }
72
73 /*
74 *
75 * Functions related to the core crypto library
76 *
77 */
78
79 void
crypto_init_lib(void)80 crypto_init_lib(void)
81 {
82 }
83
84 void
crypto_uninit_lib(void)85 crypto_uninit_lib(void)
86 {
87 }
88
89 void
crypto_clear_error(void)90 crypto_clear_error(void)
91 {
92 }
93
94 bool
mbed_log_err(unsigned int flags,int errval,const char * prefix)95 mbed_log_err(unsigned int flags, int errval, const char *prefix)
96 {
97 if (0 != errval)
98 {
99 char errstr[256];
100 mbedtls_strerror(errval, errstr, sizeof(errstr));
101
102 if (NULL == prefix)
103 {
104 prefix = "mbed TLS error";
105 }
106 msg(flags, "%s: %s", prefix, errstr);
107 }
108
109 return 0 == errval;
110 }
111
112 bool
mbed_log_func_line(unsigned int flags,int errval,const char * func,int line)113 mbed_log_func_line(unsigned int flags, int errval, const char *func,
114 int line)
115 {
116 char prefix[256];
117
118 if (!openvpn_snprintf(prefix, sizeof(prefix), "%s:%d", func, line))
119 {
120 return mbed_log_err(flags, errval, func);
121 }
122
123 return mbed_log_err(flags, errval, prefix);
124 }
125
126
127 #ifdef DMALLOC
128 void
crypto_init_dmalloc(void)129 crypto_init_dmalloc(void)
130 {
131 msg(M_ERR, "Error: dmalloc support is not available for mbed TLS.");
132 }
133 #endif /* DMALLOC */
134
135 const cipher_name_pair cipher_name_translation_table[] = {
136 { "BF-CBC", "BLOWFISH-CBC" },
137 { "BF-CFB", "BLOWFISH-CFB64" },
138 { "CAMELLIA-128-CFB", "CAMELLIA-128-CFB128" },
139 { "CAMELLIA-192-CFB", "CAMELLIA-192-CFB128" },
140 { "CAMELLIA-256-CFB", "CAMELLIA-256-CFB128" }
141 };
142 const size_t cipher_name_translation_table_count =
143 sizeof(cipher_name_translation_table) / sizeof(*cipher_name_translation_table);
144
145 void
show_available_ciphers(void)146 show_available_ciphers(void)
147 {
148 const int *ciphers = mbedtls_cipher_list();
149
150 #ifndef ENABLE_SMALL
151 printf("The following ciphers and cipher modes are available for use\n"
152 "with " PACKAGE_NAME ". Each cipher shown below may be used as a\n"
153 "parameter to the --data-ciphers (or --cipher) option. Using a\n"
154 "GCM or CBC mode is recommended. In static key mode only CBC\n"
155 "mode is allowed.\n\n");
156 #endif
157
158 while (*ciphers != 0)
159 {
160 const cipher_kt_t *info = mbedtls_cipher_info_from_type(*ciphers);
161 if (info && !cipher_kt_insecure(info)
162 && (cipher_kt_mode_aead(info) || cipher_kt_mode_cbc(info)))
163 {
164 print_cipher(info);
165 }
166 ciphers++;
167 }
168
169 printf("\nThe following ciphers have a block size of less than 128 bits, \n"
170 "and are therefore deprecated. Do not use unless you have to.\n\n");
171 ciphers = mbedtls_cipher_list();
172 while (*ciphers != 0)
173 {
174 const cipher_kt_t *info = mbedtls_cipher_info_from_type(*ciphers);
175 if (info && cipher_kt_insecure(info)
176 && (cipher_kt_mode_aead(info) || cipher_kt_mode_cbc(info)))
177 {
178 print_cipher(info);
179 }
180 ciphers++;
181 }
182 printf("\n");
183 }
184
185 void
show_available_digests(void)186 show_available_digests(void)
187 {
188 const int *digests = mbedtls_md_list();
189
190 #ifndef ENABLE_SMALL
191 printf("The following message digests are available for use with\n"
192 PACKAGE_NAME ". A message digest is used in conjunction with\n"
193 "the HMAC function, to authenticate received packets.\n"
194 "You can specify a message digest as parameter to\n"
195 "the --auth option.\n\n");
196 #endif
197
198 while (*digests != 0)
199 {
200 const mbedtls_md_info_t *info = mbedtls_md_info_from_type(*digests);
201
202 if (info)
203 {
204 printf("%s %d bit default key\n", mbedtls_md_get_name(info),
205 mbedtls_md_get_size(info) * 8);
206 }
207 digests++;
208 }
209 printf("\n");
210 }
211
212 void
show_available_engines(void)213 show_available_engines(void)
214 {
215 printf("Sorry, mbed TLS hardware crypto engine functionality is not "
216 "available\n");
217 }
218
219 bool
crypto_pem_encode(const char * name,struct buffer * dst,const struct buffer * src,struct gc_arena * gc)220 crypto_pem_encode(const char *name, struct buffer *dst,
221 const struct buffer *src, struct gc_arena *gc)
222 {
223 /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */
224 char header[1000+1] = { 0 };
225 char footer[1000+1] = { 0 };
226
227 if (!openvpn_snprintf(header, sizeof(header), "-----BEGIN %s-----\n", name))
228 {
229 return false;
230 }
231 if (!openvpn_snprintf(footer, sizeof(footer), "-----END %s-----\n", name))
232 {
233 return false;
234 }
235
236 size_t out_len = 0;
237 if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL !=
238 mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src),
239 NULL, 0, &out_len))
240 {
241 return false;
242 }
243
244 /* We set the size buf to out_len-1 to NOT include the 0 byte that
245 * mbedtls_pem_write_buffer in its length calculation */
246 *dst = alloc_buf_gc(out_len, gc);
247 if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src),
248 BPTR(dst), BCAP(dst), &out_len))
249 || !buf_inc_len(dst, out_len-1))
250 {
251 CLEAR(*dst);
252 return false;
253 }
254
255 return true;
256 }
257
258 bool
crypto_pem_decode(const char * name,struct buffer * dst,const struct buffer * src)259 crypto_pem_decode(const char *name, struct buffer *dst,
260 const struct buffer *src)
261 {
262 /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */
263 char header[1000+1] = { 0 };
264 char footer[1000+1] = { 0 };
265
266 if (!openvpn_snprintf(header, sizeof(header), "-----BEGIN %s-----", name))
267 {
268 return false;
269 }
270 if (!openvpn_snprintf(footer, sizeof(footer), "-----END %s-----", name))
271 {
272 return false;
273 }
274
275 /* mbed TLS requires the src to be null-terminated */
276 /* allocate a new buffer to avoid modifying the src buffer */
277 struct gc_arena gc = gc_new();
278 struct buffer input = alloc_buf_gc(BLEN(src) + 1, &gc);
279 buf_copy(&input, src);
280 buf_null_terminate(&input);
281
282 size_t use_len = 0;
283 mbedtls_pem_context ctx = { 0 };
284 bool ret = mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPTR(&input),
285 NULL, 0, &use_len));
286 if (ret && !buf_write(dst, ctx.buf, ctx.buflen))
287 {
288 ret = false;
289 msg(M_WARN, "PEM decode error: destination buffer too small");
290 }
291
292 mbedtls_pem_free(&ctx);
293 gc_free(&gc);
294 return ret;
295 }
296
297 /*
298 *
299 * Random number functions, used in cases where we want
300 * reasonably strong cryptographic random number generation
301 * without depleting our entropy pool. Used for random
302 * IV values and a number of other miscellaneous tasks.
303 *
304 */
305
306 /*
307 * Initialise the given ctr_drbg context, using a personalisation string and an
308 * entropy gathering function.
309 */
310 mbedtls_ctr_drbg_context *
rand_ctx_get(void)311 rand_ctx_get(void)
312 {
313 static mbedtls_entropy_context ec = {0};
314 static mbedtls_ctr_drbg_context cd_ctx = {0};
315 static bool rand_initialised = false;
316
317 if (!rand_initialised)
318 {
319 struct gc_arena gc = gc_new();
320 struct buffer pers_string = alloc_buf_gc(100, &gc);
321
322 /*
323 * Personalisation string, should be as unique as possible (see NIST
324 * 800-90 section 8.7.1). We have very little information at this stage.
325 * Include Program Name, memory address of the context and PID.
326 */
327 buf_printf(&pers_string, "OpenVPN %0u %p %s", platform_getpid(), &cd_ctx, time_string(0, 0, 0, &gc));
328
329 /* Initialise mbed TLS RNG, and built-in entropy sources */
330 mbedtls_entropy_init(&ec);
331
332 mbedtls_ctr_drbg_init(&cd_ctx);
333 if (!mbed_ok(mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, &ec,
334 BPTR(&pers_string), BLEN(&pers_string))))
335 {
336 msg(M_FATAL, "Failed to initialize random generator");
337 }
338
339 gc_free(&gc);
340 rand_initialised = true;
341 }
342
343 return &cd_ctx;
344 }
345
346 #ifdef ENABLE_PREDICTION_RESISTANCE
347 void
rand_ctx_enable_prediction_resistance(void)348 rand_ctx_enable_prediction_resistance(void)
349 {
350 mbedtls_ctr_drbg_context *cd_ctx = rand_ctx_get();
351
352 mbedtls_ctr_drbg_set_prediction_resistance(cd_ctx, 1);
353 }
354 #endif /* ENABLE_PREDICTION_RESISTANCE */
355
356 int
rand_bytes(uint8_t * output,int len)357 rand_bytes(uint8_t *output, int len)
358 {
359 mbedtls_ctr_drbg_context *rng_ctx = rand_ctx_get();
360
361 while (len > 0)
362 {
363 const size_t blen = min_int(len, MBEDTLS_CTR_DRBG_MAX_REQUEST);
364 if (0 != mbedtls_ctr_drbg_random(rng_ctx, output, blen))
365 {
366 return 0;
367 }
368
369 output += blen;
370 len -= blen;
371 }
372
373 return 1;
374 }
375
376 /*
377 *
378 * Key functions, allow manipulation of keys.
379 *
380 */
381
382
383 int
key_des_num_cblocks(const mbedtls_cipher_info_t * kt)384 key_des_num_cblocks(const mbedtls_cipher_info_t *kt)
385 {
386 int ret = 0;
387 if (kt->type == MBEDTLS_CIPHER_DES_CBC)
388 {
389 ret = 1;
390 }
391 if (kt->type == MBEDTLS_CIPHER_DES_EDE_CBC)
392 {
393 ret = 2;
394 }
395 if (kt->type == MBEDTLS_CIPHER_DES_EDE3_CBC)
396 {
397 ret = 3;
398 }
399
400 dmsg(D_CRYPTO_DEBUG, "CRYPTO INFO: n_DES_cblocks=%d", ret);
401 return ret;
402 }
403
404 bool
key_des_check(uint8_t * key,int key_len,int ndc)405 key_des_check(uint8_t *key, int key_len, int ndc)
406 {
407 int i;
408 struct buffer b;
409
410 buf_set_read(&b, key, key_len);
411
412 for (i = 0; i < ndc; ++i)
413 {
414 unsigned char *key = buf_read_alloc(&b, MBEDTLS_DES_KEY_SIZE);
415 if (!key)
416 {
417 msg(D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: insufficient key material");
418 goto err;
419 }
420 if (0 != mbedtls_des_key_check_weak(key))
421 {
422 msg(D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: weak key detected");
423 goto err;
424 }
425 if (0 != mbedtls_des_key_check_key_parity(key))
426 {
427 msg(D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: bad parity detected");
428 goto err;
429 }
430 }
431 return true;
432
433 err:
434 return false;
435 }
436
437 void
key_des_fixup(uint8_t * key,int key_len,int ndc)438 key_des_fixup(uint8_t *key, int key_len, int ndc)
439 {
440 int i;
441 struct buffer b;
442
443 buf_set_read(&b, key, key_len);
444 for (i = 0; i < ndc; ++i)
445 {
446 unsigned char *key = buf_read_alloc(&b, MBEDTLS_DES_KEY_SIZE);
447 if (!key)
448 {
449 msg(D_CRYPT_ERRORS, "CRYPTO INFO: fixup_key_DES: insufficient key material");
450 return;
451 }
452 mbedtls_des_key_set_parity(key);
453 }
454 }
455
456 /*
457 *
458 * Generic cipher key type functions
459 *
460 */
461
462
463 const mbedtls_cipher_info_t *
cipher_kt_get(const char * ciphername)464 cipher_kt_get(const char *ciphername)
465 {
466 const mbedtls_cipher_info_t *cipher = NULL;
467
468 ASSERT(ciphername);
469
470 ciphername = translate_cipher_name_from_openvpn(ciphername);
471 cipher = mbedtls_cipher_info_from_string(ciphername);
472
473 if (NULL == cipher)
474 {
475 msg(D_LOW, "Cipher algorithm '%s' not found", ciphername);
476 return NULL;
477 }
478
479 if (cipher->key_bitlen/8 > MAX_CIPHER_KEY_LENGTH)
480 {
481 msg(D_LOW, "Cipher algorithm '%s' uses a default key size (%d bytes) "
482 "which is larger than " PACKAGE_NAME "'s current maximum key size "
483 "(%d bytes)", ciphername, cipher->key_bitlen/8, MAX_CIPHER_KEY_LENGTH);
484 return NULL;
485 }
486
487 return cipher;
488 }
489
490 const char *
cipher_kt_name(const mbedtls_cipher_info_t * cipher_kt)491 cipher_kt_name(const mbedtls_cipher_info_t *cipher_kt)
492 {
493 if (NULL == cipher_kt)
494 {
495 return "[null-cipher]";
496 }
497
498 return translate_cipher_name_to_openvpn(cipher_kt->name);
499 }
500
501 int
cipher_kt_key_size(const mbedtls_cipher_info_t * cipher_kt)502 cipher_kt_key_size(const mbedtls_cipher_info_t *cipher_kt)
503 {
504 if (NULL == cipher_kt)
505 {
506 return 0;
507 }
508
509 return cipher_kt->key_bitlen/8;
510 }
511
512 int
cipher_kt_iv_size(const mbedtls_cipher_info_t * cipher_kt)513 cipher_kt_iv_size(const mbedtls_cipher_info_t *cipher_kt)
514 {
515 if (NULL == cipher_kt)
516 {
517 return 0;
518 }
519 return cipher_kt->iv_size;
520 }
521
522 int
cipher_kt_block_size(const mbedtls_cipher_info_t * cipher_kt)523 cipher_kt_block_size(const mbedtls_cipher_info_t *cipher_kt)
524 {
525 if (NULL == cipher_kt)
526 {
527 return 0;
528 }
529 return cipher_kt->block_size;
530 }
531
532 int
cipher_kt_tag_size(const mbedtls_cipher_info_t * cipher_kt)533 cipher_kt_tag_size(const mbedtls_cipher_info_t *cipher_kt)
534 {
535 if (cipher_kt && cipher_kt_mode_aead(cipher_kt))
536 {
537 return OPENVPN_AEAD_TAG_LENGTH;
538 }
539 return 0;
540 }
541
542 bool
cipher_kt_insecure(const mbedtls_cipher_info_t * cipher_kt)543 cipher_kt_insecure(const mbedtls_cipher_info_t *cipher_kt)
544 {
545 return !(cipher_kt_block_size(cipher_kt) >= 128 / 8
546 #ifdef MBEDTLS_CHACHAPOLY_C
547 || cipher_kt->type == MBEDTLS_CIPHER_CHACHA20_POLY1305
548 #endif
549 );
550 }
551
552 int
cipher_kt_mode(const mbedtls_cipher_info_t * cipher_kt)553 cipher_kt_mode(const mbedtls_cipher_info_t *cipher_kt)
554 {
555 ASSERT(NULL != cipher_kt);
556 return cipher_kt->mode;
557 }
558
559 bool
cipher_kt_mode_cbc(const cipher_kt_t * cipher)560 cipher_kt_mode_cbc(const cipher_kt_t *cipher)
561 {
562 return cipher && cipher_kt_mode(cipher) == OPENVPN_MODE_CBC;
563 }
564
565 bool
cipher_kt_mode_ofb_cfb(const cipher_kt_t * cipher)566 cipher_kt_mode_ofb_cfb(const cipher_kt_t *cipher)
567 {
568 return cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_OFB
569 || cipher_kt_mode(cipher) == OPENVPN_MODE_CFB);
570 }
571
572 bool
cipher_kt_mode_aead(const cipher_kt_t * cipher)573 cipher_kt_mode_aead(const cipher_kt_t *cipher)
574 {
575 return cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_GCM
576 #ifdef MBEDTLS_CHACHAPOLY_C
577 || cipher_kt_mode(cipher) == MBEDTLS_MODE_CHACHAPOLY
578 #endif
579 );
580 }
581
582
583 /*
584 *
585 * Generic cipher context functions
586 *
587 */
588
589 mbedtls_cipher_context_t *
cipher_ctx_new(void)590 cipher_ctx_new(void)
591 {
592 mbedtls_cipher_context_t *ctx;
593 ALLOC_OBJ(ctx, mbedtls_cipher_context_t);
594 return ctx;
595 }
596
597 void
cipher_ctx_free(mbedtls_cipher_context_t * ctx)598 cipher_ctx_free(mbedtls_cipher_context_t *ctx)
599 {
600 mbedtls_cipher_free(ctx);
601 free(ctx);
602 }
603
604 void
cipher_ctx_init(mbedtls_cipher_context_t * ctx,const uint8_t * key,int key_len,const mbedtls_cipher_info_t * kt,const mbedtls_operation_t operation)605 cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, int key_len,
606 const mbedtls_cipher_info_t *kt, const mbedtls_operation_t operation)
607 {
608 ASSERT(NULL != kt && NULL != ctx);
609
610 CLEAR(*ctx);
611
612 if (!mbed_ok(mbedtls_cipher_setup(ctx, kt)))
613 {
614 msg(M_FATAL, "mbed TLS cipher context init #1");
615 }
616
617 if (!mbed_ok(mbedtls_cipher_setkey(ctx, key, key_len*8, operation)))
618 {
619 msg(M_FATAL, "mbed TLS cipher set key");
620 }
621
622 /* make sure we used a big enough key */
623 ASSERT(ctx->key_bitlen <= key_len*8);
624 }
625
626 int
cipher_ctx_iv_length(const mbedtls_cipher_context_t * ctx)627 cipher_ctx_iv_length(const mbedtls_cipher_context_t *ctx)
628 {
629 return mbedtls_cipher_get_iv_size(ctx);
630 }
631
632 int
cipher_ctx_get_tag(cipher_ctx_t * ctx,uint8_t * tag,int tag_len)633 cipher_ctx_get_tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len)
634 {
635 if (tag_len > SIZE_MAX)
636 {
637 return 0;
638 }
639
640 if (!mbed_ok(mbedtls_cipher_write_tag(ctx, (unsigned char *) tag, tag_len)))
641 {
642 return 0;
643 }
644
645 return 1;
646 }
647
648 int
cipher_ctx_block_size(const mbedtls_cipher_context_t * ctx)649 cipher_ctx_block_size(const mbedtls_cipher_context_t *ctx)
650 {
651 return mbedtls_cipher_get_block_size(ctx);
652 }
653
654 int
cipher_ctx_mode(const mbedtls_cipher_context_t * ctx)655 cipher_ctx_mode(const mbedtls_cipher_context_t *ctx)
656 {
657 ASSERT(NULL != ctx);
658
659 return cipher_kt_mode(ctx->cipher_info);
660 }
661
662 const cipher_kt_t *
cipher_ctx_get_cipher_kt(const cipher_ctx_t * ctx)663 cipher_ctx_get_cipher_kt(const cipher_ctx_t *ctx)
664 {
665 return ctx ? ctx->cipher_info : NULL;
666 }
667
668 int
cipher_ctx_reset(mbedtls_cipher_context_t * ctx,const uint8_t * iv_buf)669 cipher_ctx_reset(mbedtls_cipher_context_t *ctx, const uint8_t *iv_buf)
670 {
671 if (!mbed_ok(mbedtls_cipher_reset(ctx)))
672 {
673 return 0;
674 }
675
676 if (!mbed_ok(mbedtls_cipher_set_iv(ctx, iv_buf, ctx->cipher_info->iv_size)))
677 {
678 return 0;
679 }
680
681 return 1;
682 }
683
684 int
cipher_ctx_update_ad(cipher_ctx_t * ctx,const uint8_t * src,int src_len)685 cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len)
686 {
687 if (src_len > SIZE_MAX)
688 {
689 return 0;
690 }
691
692 if (!mbed_ok(mbedtls_cipher_update_ad(ctx, src, src_len)))
693 {
694 return 0;
695 }
696
697 return 1;
698 }
699
700 int
cipher_ctx_update(mbedtls_cipher_context_t * ctx,uint8_t * dst,int * dst_len,uint8_t * src,int src_len)701 cipher_ctx_update(mbedtls_cipher_context_t *ctx, uint8_t *dst,
702 int *dst_len, uint8_t *src, int src_len)
703 {
704 size_t s_dst_len = *dst_len;
705
706 if (!mbed_ok(mbedtls_cipher_update(ctx, src, (size_t) src_len, dst,
707 &s_dst_len)))
708 {
709 return 0;
710 }
711
712 *dst_len = s_dst_len;
713
714 return 1;
715 }
716
717 int
cipher_ctx_final(mbedtls_cipher_context_t * ctx,uint8_t * dst,int * dst_len)718 cipher_ctx_final(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_len)
719 {
720 size_t s_dst_len = *dst_len;
721
722 if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &s_dst_len)))
723 {
724 return 0;
725 }
726
727 *dst_len = s_dst_len;
728
729 return 1;
730 }
731
732 int
cipher_ctx_final_check_tag(mbedtls_cipher_context_t * ctx,uint8_t * dst,int * dst_len,uint8_t * tag,size_t tag_len)733 cipher_ctx_final_check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst,
734 int *dst_len, uint8_t *tag, size_t tag_len)
735 {
736 size_t olen = 0;
737
738 if (MBEDTLS_DECRYPT != ctx->operation)
739 {
740 return 0;
741 }
742
743 if (tag_len > SIZE_MAX)
744 {
745 return 0;
746 }
747
748 if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &olen)))
749 {
750 msg(D_CRYPT_ERRORS, "%s: cipher_ctx_final() failed", __func__);
751 return 0;
752 }
753
754 if (olen > INT_MAX)
755 {
756 return 0;
757 }
758 *dst_len = olen;
759
760 if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (const unsigned char *) tag,
761 tag_len)))
762 {
763 return 0;
764 }
765
766 return 1;
767 }
768
769 void
cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH],unsigned char src[DES_KEY_LENGTH],unsigned char dst[DES_KEY_LENGTH])770 cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH],
771 unsigned char src[DES_KEY_LENGTH],
772 unsigned char dst[DES_KEY_LENGTH])
773 {
774 mbedtls_des_context ctx;
775
776 ASSERT(mbed_ok(mbedtls_des_setkey_enc(&ctx, key)));
777 ASSERT(mbed_ok(mbedtls_des_crypt_ecb(&ctx, src, dst)));
778 }
779
780
781
782 /*
783 *
784 * Generic message digest information functions
785 *
786 */
787
788
789 const mbedtls_md_info_t *
md_kt_get(const char * digest)790 md_kt_get(const char *digest)
791 {
792 const mbedtls_md_info_t *md = NULL;
793 ASSERT(digest);
794
795 md = mbedtls_md_info_from_string(digest);
796 if (!md)
797 {
798 msg(M_FATAL, "Message hash algorithm '%s' not found", digest);
799 }
800 if (mbedtls_md_get_size(md) > MAX_HMAC_KEY_LENGTH)
801 {
802 msg(M_FATAL, "Message hash algorithm '%s' uses a default hash size (%d bytes) which is larger than " PACKAGE_NAME "'s current maximum hash size (%d bytes)",
803 digest,
804 mbedtls_md_get_size(md),
805 MAX_HMAC_KEY_LENGTH);
806 }
807 return md;
808 }
809
810 const char *
md_kt_name(const mbedtls_md_info_t * kt)811 md_kt_name(const mbedtls_md_info_t *kt)
812 {
813 if (NULL == kt)
814 {
815 return "[null-digest]";
816 }
817 return mbedtls_md_get_name(kt);
818 }
819
820 unsigned char
md_kt_size(const mbedtls_md_info_t * kt)821 md_kt_size(const mbedtls_md_info_t *kt)
822 {
823 if (NULL == kt)
824 {
825 return 0;
826 }
827 return mbedtls_md_get_size(kt);
828 }
829
830 /*
831 *
832 * Generic message digest functions
833 *
834 */
835
836 int
md_full(const md_kt_t * kt,const uint8_t * src,int src_len,uint8_t * dst)837 md_full(const md_kt_t *kt, const uint8_t *src, int src_len, uint8_t *dst)
838 {
839 return 0 == mbedtls_md(kt, src, src_len, dst);
840 }
841
842 mbedtls_md_context_t *
md_ctx_new(void)843 md_ctx_new(void)
844 {
845 mbedtls_md_context_t *ctx;
846 ALLOC_OBJ_CLEAR(ctx, mbedtls_md_context_t);
847 return ctx;
848 }
849
850 void
md_ctx_free(mbedtls_md_context_t * ctx)851 md_ctx_free(mbedtls_md_context_t *ctx)
852 {
853 free(ctx);
854 }
855
856 void
md_ctx_init(mbedtls_md_context_t * ctx,const mbedtls_md_info_t * kt)857 md_ctx_init(mbedtls_md_context_t *ctx, const mbedtls_md_info_t *kt)
858 {
859 ASSERT(NULL != ctx && NULL != kt);
860
861 mbedtls_md_init(ctx);
862 ASSERT(0 == mbedtls_md_setup(ctx, kt, 0));
863 ASSERT(0 == mbedtls_md_starts(ctx));
864 }
865
866 void
md_ctx_cleanup(mbedtls_md_context_t * ctx)867 md_ctx_cleanup(mbedtls_md_context_t *ctx)
868 {
869 mbedtls_md_free(ctx);
870 }
871
872 int
md_ctx_size(const mbedtls_md_context_t * ctx)873 md_ctx_size(const mbedtls_md_context_t *ctx)
874 {
875 if (NULL == ctx)
876 {
877 return 0;
878 }
879 return mbedtls_md_get_size(ctx->md_info);
880 }
881
882 void
md_ctx_update(mbedtls_md_context_t * ctx,const uint8_t * src,int src_len)883 md_ctx_update(mbedtls_md_context_t *ctx, const uint8_t *src, int src_len)
884 {
885 ASSERT(0 == mbedtls_md_update(ctx, src, src_len));
886 }
887
888 void
md_ctx_final(mbedtls_md_context_t * ctx,uint8_t * dst)889 md_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst)
890 {
891 ASSERT(0 == mbedtls_md_finish(ctx, dst));
892 mbedtls_md_free(ctx);
893 }
894
895
896 /*
897 *
898 * Generic HMAC functions
899 *
900 */
901
902
903 /*
904 * TODO: re-enable dmsg for crypto debug
905 */
906
907 mbedtls_md_context_t *
hmac_ctx_new(void)908 hmac_ctx_new(void)
909 {
910 mbedtls_md_context_t *ctx;
911 ALLOC_OBJ(ctx, mbedtls_md_context_t);
912 return ctx;
913 }
914
915 void
hmac_ctx_free(mbedtls_md_context_t * ctx)916 hmac_ctx_free(mbedtls_md_context_t *ctx)
917 {
918 free(ctx);
919 }
920
921 void
hmac_ctx_init(mbedtls_md_context_t * ctx,const uint8_t * key,int key_len,const mbedtls_md_info_t * kt)922 hmac_ctx_init(mbedtls_md_context_t *ctx, const uint8_t *key, int key_len,
923 const mbedtls_md_info_t *kt)
924 {
925 ASSERT(NULL != kt && NULL != ctx);
926
927 mbedtls_md_init(ctx);
928 ASSERT(0 == mbedtls_md_setup(ctx, kt, 1));
929 ASSERT(0 == mbedtls_md_hmac_starts(ctx, key, key_len));
930
931 /* make sure we used a big enough key */
932 ASSERT(mbedtls_md_get_size(kt) <= key_len);
933 }
934
935 void
hmac_ctx_cleanup(mbedtls_md_context_t * ctx)936 hmac_ctx_cleanup(mbedtls_md_context_t *ctx)
937 {
938 mbedtls_md_free(ctx);
939 }
940
941 int
hmac_ctx_size(const mbedtls_md_context_t * ctx)942 hmac_ctx_size(const mbedtls_md_context_t *ctx)
943 {
944 if (NULL == ctx)
945 {
946 return 0;
947 }
948 return mbedtls_md_get_size(ctx->md_info);
949 }
950
951 void
hmac_ctx_reset(mbedtls_md_context_t * ctx)952 hmac_ctx_reset(mbedtls_md_context_t *ctx)
953 {
954 ASSERT(0 == mbedtls_md_hmac_reset(ctx));
955 }
956
957 void
hmac_ctx_update(mbedtls_md_context_t * ctx,const uint8_t * src,int src_len)958 hmac_ctx_update(mbedtls_md_context_t *ctx, const uint8_t *src, int src_len)
959 {
960 ASSERT(0 == mbedtls_md_hmac_update(ctx, src, src_len));
961 }
962
963 void
hmac_ctx_final(mbedtls_md_context_t * ctx,uint8_t * dst)964 hmac_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst)
965 {
966 ASSERT(0 == mbedtls_md_hmac_finish(ctx, dst));
967 }
968
969 int
memcmp_constant_time(const void * a,const void * b,size_t size)970 memcmp_constant_time(const void *a, const void *b, size_t size)
971 {
972 /* mbed TLS has a no const time memcmp function that it exposes
973 * via its APIs like OpenSSL does with CRYPTO_memcmp
974 * Adapt the function that mbedtls itself uses in
975 * mbedtls_safer_memcmp as it considers that to be safe */
976 volatile const unsigned char *A = (volatile const unsigned char *) a;
977 volatile const unsigned char *B = (volatile const unsigned char *) b;
978 volatile unsigned char diff = 0;
979
980 for (size_t i = 0; i < size; i++)
981 {
982 unsigned char x = A[i], y = B[i];
983 diff |= x ^ y;
984 }
985
986 return diff;
987 }
988 /* mbedtls-2.18.0 or newer */
989 #ifdef HAVE_MBEDTLS_SSL_TLS_PRF
990 bool
ssl_tls1_PRF(const uint8_t * seed,int seed_len,const uint8_t * secret,int secret_len,uint8_t * output,int output_len)991 ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret,
992 int secret_len, uint8_t *output, int output_len)
993 {
994 return mbed_ok(mbedtls_ssl_tls_prf(MBEDTLS_SSL_TLS_PRF_TLS1, secret,
995 secret_len, "", seed, seed_len, output,
996 output_len));
997 }
998 #else /* ifdef HAVE_MBEDTLS_SSL_TLS_PRF */
999 /*
1000 * Generate the hash required by for the \c tls1_PRF function.
1001 *
1002 * @param md_kt Message digest to use
1003 * @param sec Secret to base the hash on
1004 * @param sec_len Length of the secret
1005 * @param seed Seed to hash
1006 * @param seed_len Length of the seed
1007 * @param out Output buffer
1008 * @param olen Length of the output buffer
1009 */
1010 static void
tls1_P_hash(const md_kt_t * md_kt,const uint8_t * sec,int sec_len,const uint8_t * seed,int seed_len,uint8_t * out,int olen)1011 tls1_P_hash(const md_kt_t *md_kt, const uint8_t *sec, int sec_len,
1012 const uint8_t *seed, int seed_len, uint8_t *out, int olen)
1013 {
1014 struct gc_arena gc = gc_new();
1015 uint8_t A1[MAX_HMAC_KEY_LENGTH];
1016
1017 #ifdef ENABLE_DEBUG
1018 /* used by the D_SHOW_KEY_SOURCE, guarded with ENABLE_DEBUG to avoid unused
1019 * variables warnings if compiled with --enable-small */
1020 const int olen_orig = olen;
1021 const uint8_t *out_orig = out;
1022 #endif
1023
1024 hmac_ctx_t *ctx = hmac_ctx_new();
1025 hmac_ctx_t *ctx_tmp = hmac_ctx_new();
1026
1027 dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex(sec, sec_len, 0, &gc));
1028 dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex(seed, seed_len, 0, &gc));
1029
1030 int chunk = md_kt_size(md_kt);
1031 unsigned int A1_len = md_kt_size(md_kt);
1032
1033 hmac_ctx_init(ctx, sec, sec_len, md_kt);
1034 hmac_ctx_init(ctx_tmp, sec, sec_len, md_kt);
1035
1036 hmac_ctx_update(ctx,seed,seed_len);
1037 hmac_ctx_final(ctx, A1);
1038
1039 for (;; )
1040 {
1041 hmac_ctx_reset(ctx);
1042 hmac_ctx_reset(ctx_tmp);
1043 hmac_ctx_update(ctx, A1, A1_len);
1044 hmac_ctx_update(ctx_tmp, A1, A1_len);
1045 hmac_ctx_update(ctx, seed, seed_len);
1046
1047 if (olen > chunk)
1048 {
1049 hmac_ctx_final(ctx, out);
1050 out += chunk;
1051 olen -= chunk;
1052 hmac_ctx_final(ctx_tmp, A1); /* calc the next A1 value */
1053 }
1054 else /* last one */
1055 {
1056 hmac_ctx_final(ctx, A1);
1057 memcpy(out, A1, olen);
1058 break;
1059 }
1060 }
1061 hmac_ctx_cleanup(ctx);
1062 hmac_ctx_free(ctx);
1063 hmac_ctx_cleanup(ctx_tmp);
1064 hmac_ctx_free(ctx_tmp);
1065 secure_memzero(A1, sizeof(A1));
1066
1067 dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex(out_orig, olen_orig, 0, &gc));
1068 gc_free(&gc);
1069 }
1070
1071 /*
1072 * Use the TLS PRF function for generating data channel keys.
1073 * This code is based on the OpenSSL library.
1074 *
1075 * TLS generates keys as such:
1076 *
1077 * master_secret[48] = PRF(pre_master_secret[48], "master secret",
1078 * ClientHello.random[32] + ServerHello.random[32])
1079 *
1080 * key_block[] = PRF(SecurityParameters.master_secret[48],
1081 * "key expansion",
1082 * SecurityParameters.server_random[32] +
1083 * SecurityParameters.client_random[32]);
1084 *
1085 * Notes:
1086 *
1087 * (1) key_block contains a full set of 4 keys.
1088 * (2) The pre-master secret is generated by the client.
1089 */
1090 bool
ssl_tls1_PRF(const uint8_t * label,int label_len,const uint8_t * sec,int slen,uint8_t * out1,int olen)1091 ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec,
1092 int slen, uint8_t *out1, int olen)
1093 {
1094 struct gc_arena gc = gc_new();
1095 const md_kt_t *md5 = md_kt_get("MD5");
1096 const md_kt_t *sha1 = md_kt_get("SHA1");
1097
1098 uint8_t *out2 = (uint8_t *)gc_malloc(olen, false, &gc);
1099
1100 int len = slen/2;
1101 const uint8_t *S1 = sec;
1102 const uint8_t *S2 = &(sec[len]);
1103 len += (slen&1); /* add for odd, make longer */
1104
1105 tls1_P_hash(md5, S1, len, label, label_len, out1, olen);
1106 tls1_P_hash(sha1, S2, len, label, label_len, out2, olen);
1107
1108 for (int i = 0; i<olen; i++)
1109 {
1110 out1[i] ^= out2[i];
1111 }
1112
1113 secure_memzero(out2, olen);
1114
1115 dmsg(D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex(out1, olen, 0, &gc));
1116
1117 gc_free(&gc);
1118 return true;
1119 }
1120 #endif /* ifdef HAVE_MBEDTLS_SSL_TLS_PRF */
1121 #endif /* ENABLE_CRYPTO_MBEDTLS */
1122