OpenVPN
crypto_mbedtls.c
Go to the documentation of this file.
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-2026 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2026 Sentyron B.V. <openvpn@sentyron.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, see <https://www.gnu.org/licenses/>.
22 */
23
30#ifdef HAVE_CONFIG_H
31#include "config.h"
32#endif
33
34#include "syshead.h"
35
36#if defined(ENABLE_CRYPTO_MBEDTLS)
37
38#include "errlevel.h"
39#include "basic.h"
40#include "buffer.h"
41#include "crypto.h"
42#include "integer.h"
43#include "crypto_backend.h"
44#include "crypto_mbedtls.h"
45#include "otime.h"
46#include "misc.h"
47
48#include <psa/crypto.h>
49#include <psa/crypto_config.h>
50#include <mbedtls/constant_time.h>
51#include <mbedtls/error.h>
52#include <mbedtls/pem.h>
53
54/*
55 *
56 * Hardware engine support. Allows loading/unloading of engines.
57 *
58 */
59
60void
61crypto_init_lib_engine(const char *engine_name)
62{
63 msg(M_WARN, "Note: mbed TLS hardware crypto engine functionality is not "
64 "available");
65}
66
68crypto_load_provider(const char *provider)
69{
70 if (provider)
71 {
72 msg(M_WARN, "Note: mbed TLS provider functionality is not available");
73 }
74 return NULL;
75}
76
77void
78crypto_unload_provider(const char *provname, provider_t *provider)
79{
80}
81
82/* The library doesn't support looking up algorithms by string anymore, so here
83 * is a lookup table. */
84static const cipher_info_t cipher_info_table[] = {
85/* TODO: Complete the table. */
86
87/* AES */
88#if PSA_WANT_KEY_TYPE_AES
89#if PSA_WANT_ALG_GCM
90 { "AES-128-GCM", PSA_KEY_TYPE_AES, PSA_ALG_GCM, 128 / 8, 96 / 8, 128 / 8 },
91 { "AES-192-GCM", PSA_KEY_TYPE_AES, PSA_ALG_GCM, 192 / 8, 96 / 8, 128 / 8 },
92 { "AES-256-GCM", PSA_KEY_TYPE_AES, PSA_ALG_GCM, 256 / 8, 96 / 8, 128 / 8 },
93#endif /* PSA_WANT_ALG_GCM */
94#if PSA_WANT_ALG_CBC_PKCS7
95 { "AES-128-CBC", PSA_KEY_TYPE_AES, PSA_ALG_CBC_PKCS7, 128 / 8, 128 / 8, 128 / 8 },
96 { "AES-192-CBC", PSA_KEY_TYPE_AES, PSA_ALG_CBC_PKCS7, 192 / 8, 128 / 8, 128 / 8 },
97 { "AES-256-CBC", PSA_KEY_TYPE_AES, PSA_ALG_CBC_PKCS7, 256 / 8, 128 / 8, 128 / 8 },
98#endif /* PSA_WANT_ALG_CBC_PKCS7 */
99#if PSA_WANT_ALG_CTR
100 { "AES-128-CTR", PSA_KEY_TYPE_AES, PSA_ALG_CTR, 128 / 8, 128 / 8, 128 / 8 },
101 { "AES-192-CTR", PSA_KEY_TYPE_AES, PSA_ALG_CTR, 192 / 8, 128 / 8, 128 / 8 },
102 { "AES-256-CTR", PSA_KEY_TYPE_AES, PSA_ALG_CTR, 256 / 8, 128 / 8, 128 / 8 },
103#endif /* PSA_WANT_ALG_CTR */
104#endif /* PSA_WANT_KEY_TYPE_AES */
105
106/* Chacha-Poly */
107#if PSA_WANT_KEY_TYPE_CHACHA20 && PSA_WANT_ALG_CHACHA20_POLY1305
108 { "CHACHA20-POLY1305", PSA_KEY_TYPE_CHACHA20, PSA_ALG_CHACHA20_POLY1305, 256 / 8, 96 / 8, 1 },
109#endif
110};
111static const size_t cipher_info_table_entries = sizeof(cipher_info_table) / sizeof(cipher_info_t);
112
113static const cipher_info_t *
114cipher_get(const char *ciphername)
115{
116 for (size_t i = 0; i < cipher_info_table_entries; i++)
117 {
118 if (strcmp(ciphername, cipher_info_table[i].name) == 0)
119 {
120 return &cipher_info_table[i];
121 }
122 }
123 return NULL;
124}
125
126/* Because Mbed TLS 4 doesn't support looking up algorithms by string, there's
127 * nothing to translate. */
131
132int
133rand_bytes(uint8_t *output, int len)
134{
135 if (len < 0)
136 {
137 return 0;
138 }
139 psa_status_t result = psa_generate_random(output, (size_t)len);
140 return result == PSA_SUCCESS;
141}
142
143bool
144cipher_valid_reason(const char *ciphername, const char **reason)
145{
146 ASSERT(reason);
147
148 const cipher_info_t *cipher_info = cipher_get(ciphername);
149
150 if (cipher_info == NULL)
151 {
152 msg(D_LOW, "Cipher algorithm '%s' not found", ciphername);
153 *reason = "disabled because unknown";
154 return false;
155 }
156
158 {
159 msg(D_LOW,
160 "Cipher algorithm '%s' uses a default key size (%u bytes) "
161 "which is larger than " PACKAGE_NAME "'s current maximum key size "
162 "(%d bytes)",
164 *reason = "disabled due to key size too large";
165 return false;
166 }
167
168 *reason = NULL;
169 return true;
170}
171
172const char *
173cipher_kt_name(const char *ciphername)
174{
175 const cipher_info_t *cipher_info = cipher_get(ciphername);
176 if (cipher_info == NULL)
177 {
178 return "[null-cipher]";
179 }
180 return cipher_info->name;
181}
182
183unsigned int
184cipher_kt_key_size(const char *ciphername)
185{
186 const cipher_info_t *cipher_info = cipher_get(ciphername);
187 if (cipher_info == NULL)
188 {
189 return 0;
190 }
191 return cipher_info->key_bytes;
192}
193
194unsigned int
195cipher_kt_iv_size(const char *ciphername)
196{
197 const cipher_info_t *cipher_info = cipher_get(ciphername);
198
199 if (cipher_info == NULL)
200 {
201 return 0;
202 }
203 return cipher_info->iv_bytes;
204}
205
206unsigned int
207cipher_kt_block_size(const char *ciphername)
208{
209 const cipher_info_t *cipher_info = cipher_get(ciphername);
210 if (cipher_info == NULL)
211 {
212 return 0;
213 }
214 return cipher_info->block_size;
215}
216
217unsigned int
218cipher_kt_tag_size(const char *ciphername)
219{
220 if (cipher_kt_mode_aead(ciphername))
221 {
223 }
224 return 0;
225}
226
227bool
228cipher_kt_insecure(const char *ciphername)
229{
230 const cipher_info_t *cipher_info = cipher_get(ciphername);
231 if (cipher_info == NULL)
232 {
233 return true;
234 }
235
236 return !(cipher_info->block_size >= 128 / 8
237 || cipher_info->psa_alg == PSA_ALG_CHACHA20_POLY1305);
238}
239
240bool
241cipher_kt_mode_cbc(const char *ciphername)
242{
243 const cipher_info_t *cipher_info = cipher_get(ciphername);
244 if (cipher_info == NULL)
245 {
246 return false;
247 }
248 return cipher_info->psa_alg == PSA_ALG_CBC_PKCS7;
249}
250
251bool
252cipher_kt_mode_ofb_cfb(const char *ciphername)
253{
254 const cipher_info_t *cipher_info = cipher_get(ciphername);
255 if (cipher_info == NULL)
256 {
257 return false;
258 }
259 return cipher_info->psa_alg == PSA_ALG_OFB || cipher_info->psa_alg == PSA_ALG_CFB;
260}
261
262bool
263cipher_kt_mode_aead(const char *ciphername)
264{
265 const cipher_info_t *cipher_info = cipher_get(ciphername);
266 if (cipher_info == NULL)
267 {
268 return false;
269 }
270 return cipher_info->psa_alg == PSA_ALG_GCM || cipher_info->psa_alg == PSA_ALG_CHACHA20_POLY1305;
271}
272
274cipher_ctx_new(void)
275{
276 cipher_ctx_t *ctx;
277 /* Initializing the object with zeros ensures that it is always safe to call
278 * cipher_ctx_free. */
280 return ctx;
281}
282
283void
285{
286 if (cipher_ctx_mode_aead(ctx))
287 {
288 ASSERT(psa_aead_abort(&ctx->operation.aead) == PSA_SUCCESS);
289 }
290 else
291 {
292 ASSERT(psa_cipher_abort(&ctx->operation.cipher) == PSA_SUCCESS);
293 }
294 ASSERT(psa_destroy_key(ctx->key) == PSA_SUCCESS);
295 free(ctx);
296}
297
298void
299cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, const char *ciphername,
301{
302 ASSERT(ciphername != NULL && ctx != NULL);
303 CLEAR(*ctx);
304
305 ctx->cipher_info = cipher_get(ciphername);
306 ASSERT(ctx->cipher_info != NULL);
307
308 psa_set_key_type(&ctx->key_attributes, ctx->cipher_info->psa_key_type);
309 psa_set_key_algorithm(&ctx->key_attributes, ctx->cipher_info->psa_alg);
310 psa_set_key_bits(&ctx->key_attributes, ctx->cipher_info->key_bytes * 8);
311 psa_set_key_usage_flags(&ctx->key_attributes,
312 enc == OPENVPN_OP_ENCRYPT ? PSA_KEY_USAGE_ENCRYPT : PSA_KEY_USAGE_DECRYPT);
313
314 if (psa_import_key(&ctx->key_attributes, key, ctx->cipher_info->key_bytes, &ctx->key) != PSA_SUCCESS)
315 {
316 msg(M_FATAL, "psa_import_key failed");
317 }
318
319 /* make sure we used a big enough key */
320 ASSERT(psa_get_key_bits(&ctx->key_attributes) == (8 * ctx->cipher_info->key_bytes));
321}
322
323unsigned int
325{
326 return ctx->cipher_info->iv_bytes;
327}
328
329int
330cipher_ctx_get_tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len)
331{
332 if (!ctx->aead_finished || tag_len < OPENVPN_AEAD_TAG_LENGTH)
333 {
334 return 0;
335 }
336
337 memcpy(tag, ctx->tag, OPENVPN_AEAD_TAG_LENGTH);
338 return 1;
339}
340
341unsigned int
343{
344 return ctx->cipher_info->block_size;
345}
346
347int
349{
350 ASSERT(ctx != NULL);
351 return (int)psa_get_key_algorithm(&ctx->key_attributes);
352}
353
354bool
356{
357 return ctx != NULL && cipher_ctx_mode(ctx) == OPENVPN_MODE_CBC;
358}
359
360bool
362{
363 if (ctx == NULL)
364 {
365 return false;
366 }
367 int mode = cipher_ctx_mode(ctx);
368 return mode == OPENVPN_MODE_OFB || mode == OPENVPN_MODE_CFB;
369}
370
371bool
373{
374 if (ctx == NULL)
375 {
376 return false;
377 }
378 int mode = cipher_ctx_mode(ctx);
379 return mode == (int)PSA_ALG_GCM || mode == (int)PSA_ALG_CHACHA20_POLY1305;
380}
381
382static int
383cipher_ctx_direction(const cipher_ctx_t *ctx)
384{
385 psa_key_usage_t key_usage = psa_get_key_usage_flags(&ctx->key_attributes);
386 if (key_usage & PSA_KEY_USAGE_ENCRYPT)
387 {
388 return OPENVPN_OP_ENCRYPT;
389 }
390 else if (key_usage & PSA_KEY_USAGE_DECRYPT)
391 {
392 return OPENVPN_OP_DECRYPT;
393 }
394 else
395 {
396 return -1;
397 }
398}
399
400int
401cipher_ctx_reset(cipher_ctx_t *ctx, const uint8_t *iv_buf)
402{
403 psa_status_t status = 0;
404
405 if (cipher_ctx_mode_aead(ctx))
406 {
407 if (psa_aead_abort(&ctx->operation.aead) != PSA_SUCCESS)
408 {
409 return 0;
410 }
411
412 if (cipher_ctx_direction(ctx) == OPENVPN_OP_ENCRYPT)
413 {
414 status = psa_aead_encrypt_setup(&ctx->operation.aead, ctx->key, ctx->cipher_info->psa_alg);
415 }
416 else if (cipher_ctx_direction(ctx) == OPENVPN_OP_DECRYPT)
417 {
418 status = psa_aead_decrypt_setup(&ctx->operation.aead, ctx->key, ctx->cipher_info->psa_alg);
419 }
420 else
421 {
422 return 0;
423 }
424
425 if (status != PSA_SUCCESS)
426 {
427 return 0;
428 }
429
430 status = psa_aead_set_nonce(&ctx->operation.aead, iv_buf, ctx->cipher_info->iv_bytes);
431 if (status != PSA_SUCCESS)
432 {
433 return 0;
434 }
435 }
436 else
437 {
438 if (psa_cipher_abort(&ctx->operation.cipher) != PSA_SUCCESS)
439 {
440 return 0;
441 }
442
443 if (cipher_ctx_direction(ctx) == OPENVPN_OP_ENCRYPT)
444 {
445 status = psa_cipher_encrypt_setup(&ctx->operation.cipher, ctx->key, ctx->cipher_info->psa_alg);
446 }
447 else if (cipher_ctx_direction(ctx) == OPENVPN_OP_DECRYPT)
448 {
449 status = psa_cipher_decrypt_setup(&ctx->operation.cipher, ctx->key, ctx->cipher_info->psa_alg);
450 }
451 else
452 {
453 return 0;
454 }
455
456 if (status != PSA_SUCCESS)
457 {
458 return 0;
459 }
460
461 status = psa_cipher_set_iv(&ctx->operation.cipher, iv_buf, ctx->cipher_info->iv_bytes);
462 if (status != PSA_SUCCESS)
463 {
464 return 0;
465 }
466 }
467
468 return 1;
469}
470
471/* We rely on the caller to ensure that the destination buffer has enough room,
472 * but Mbed TLS always wants a size for the destination buffer. This function
473 * calculates the minimum necessary size for a given cipher and input length.
474 *
475 * This funcion assumes that src_len has been checked to be >= 0. */
476static size_t
477needed_dst_size(const cipher_ctx_t *ctx, int src_len)
478{
479 int mode = cipher_ctx_mode(ctx);
480 if (mode == PSA_ALG_CTR || mode == PSA_ALG_GCM || mode == PSA_ALG_CHACHA20_POLY1305)
481 {
482 /* These algorithms are based on a keystream, so the input and output
483 * length are always equal. */
484 return (size_t)src_len;
485 }
486 else
487 {
488 /* These algorithms are block-based. The number of output blocks that are
489 * produced is at most 1 + src_len / block_size. */
490 size_t block_size = (size_t)cipher_ctx_block_size(ctx);
491 size_t max_blocks = 1 + (size_t)src_len / block_size;
492 return max_blocks * block_size;
493 }
494}
495
496int
497cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len)
498{
499 if (src_len < 0 || !cipher_ctx_mode_aead(ctx))
500 {
501 return 0;
502 }
503
504 if (psa_aead_update_ad(&ctx->operation.aead, src, (size_t)src_len) != PSA_SUCCESS)
505 {
506 return 0;
507 }
508 return 1;
509}
510
511int
512cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, const uint8_t *src, int src_len)
513{
514 if (src_len < 0)
515 {
516 return 0;
517 }
518
519 size_t dst_size = needed_dst_size(ctx, src_len);
520 size_t psa_output_len = 0;
521 psa_status_t status = 0;
522
523 if (cipher_ctx_mode_aead(ctx))
524 {
525 status = psa_aead_update(&ctx->operation.aead, src, (size_t)src_len, dst, dst_size, &psa_output_len);
526 }
527 else
528 {
529 status = psa_cipher_update(&ctx->operation.cipher, src, (size_t)src_len, dst, dst_size, &psa_output_len);
530 }
531
532 if (status != PSA_SUCCESS)
533 {
534 return 0;
535 }
536
537 if (psa_output_len > INT_MAX)
538 {
539 return 0;
540 }
541 *dst_len = (int)psa_output_len;
542
543 return 1;
544}
545
546int
547cipher_ctx_final(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len)
548{
549 size_t dst_size = needed_dst_size(ctx, 0);
550 size_t psa_output_len = 0;
551 psa_status_t status = 0;
552
553 if (cipher_ctx_mode_aead(ctx))
554 {
555 size_t actual_tag_size = 0;
556 status = psa_aead_finish(&ctx->operation.aead,
557 dst,
558 dst_size,
559 &psa_output_len,
560 ctx->tag,
562 &actual_tag_size);
563 if (status != PSA_SUCCESS || psa_output_len > (size_t)INT_MAX || actual_tag_size != (size_t)OPENVPN_AEAD_TAG_LENGTH)
564 {
565 return 0;
566 }
567 ctx->aead_finished = true;
568 }
569 else
570 {
571 status = psa_cipher_finish(&ctx->operation.cipher, dst, dst_size, &psa_output_len);
572 if (status != PSA_SUCCESS || psa_output_len > (size_t)INT_MAX)
573 {
574 return 0;
575 }
576 }
577
578 *dst_len = (int)psa_output_len;
579
580 return 1;
581}
582
583int
584cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *tag, size_t tag_len)
585{
586 if (cipher_ctx_direction(ctx) != OPENVPN_OP_DECRYPT || !cipher_ctx_mode_aead(ctx))
587 {
588 return 0;
589 }
590
591 size_t psa_output_len = 0;
592 psa_status_t status = 0;
593
594 status = psa_aead_verify(&ctx->operation.aead, dst, 0, &psa_output_len, tag, tag_len);
595 if (status != PSA_SUCCESS || psa_output_len > (size_t)INT_MAX)
596 {
597 return 0;
598 }
599 *dst_len = (int)psa_output_len;
600
601 return 1;
602}
603
604static const md_info_t md_info_table[] = {
605#if defined(PSA_WANT_ALG_MD5)
606 { "MD5", PSA_ALG_MD5 },
607#endif
608#if defined(PSA_WANT_ALG_SHA_1)
609 { "SHA1", PSA_ALG_SHA_1 },
610#endif
611#if defined(PSA_WANT_ALG_SHA_224)
612 { "SHA224", PSA_ALG_SHA_224 },
613#endif
614#if defined(PSA_WANT_ALG_SHA_256)
615 { "SHA256", PSA_ALG_SHA_256 },
616#endif
617#if defined(PSA_WANT_ALG_SHA_384)
618 { "SHA384", PSA_ALG_SHA_384 },
619#endif
620#if defined(PSA_WANT_ALG_SHA_512)
621 { "SHA512", PSA_ALG_SHA_512 },
622#endif
623#if defined(PSA_WANT_ALG_SHA3_224)
624 { "SHA3-224", PSA_ALG_SHA3_224 },
625#endif
626#if defined(PSA_WANT_ALG_SHA3_256)
627 { "SHA3-256", PSA_ALG_SHA3_256 },
628#endif
629#if defined(PSA_WANT_ALG_SHA3_384)
630 { "SHA3-384", PSA_ALG_SHA3_384 },
631#endif
632#if defined(PSA_WANT_ALG_SHA3_512)
633 { "SHA3-512", PSA_ALG_SHA3_512 },
634#endif
635};
636const size_t md_info_table_entries = sizeof(md_info_table) / sizeof(md_info_t);
637
638static const md_info_t *
639md_get(const char *digest_name)
640{
641 for (size_t i = 0; i < md_info_table_entries; i++)
642 {
643 if (strcmp(digest_name, md_info_table[i].name) == 0)
644 {
645 return &md_info_table[i];
646 }
647 }
648 return NULL;
649}
650
651bool
652md_valid(const char *digest)
653{
654 const md_info_t *md = md_get(digest);
655 return md != NULL;
656}
657
658const char *
659md_kt_name(const char *mdname)
660{
661 if (strcmp("none", mdname) == 0)
662 {
663 return "[null-digest]";
664 }
665 const md_info_t *md = md_get(mdname);
666 if (md == NULL)
667 {
668 return NULL;
669 }
670 return md->name;
671}
672
673unsigned char
674md_kt_size(const char *mdname)
675{
676 if (strcmp("none", mdname) == 0)
677 {
678 return 0;
679 }
680 const md_info_t *md_info = md_get(mdname);
681 if (md_info == NULL)
682 {
683 return 0;
684 }
685 return (unsigned char)PSA_HASH_LENGTH(md_info->psa_alg);
686}
687
688md_ctx_t *
689md_ctx_new(void)
690{
691 md_ctx_t *ctx;
693 return ctx;
694}
695
696void
698{
699 free(ctx);
700}
701
702void
703md_ctx_init(md_ctx_t *ctx, const char *mdname)
704{
705 const md_info_t *md_info = md_get(mdname);
706 ASSERT(ctx != NULL && md_info != NULL);
707
708 ctx->md_info = md_info;
709 ASSERT(psa_hash_setup(&ctx->operation, md_info->psa_alg) == PSA_SUCCESS);
710}
711
712void
714{
715 ASSERT(psa_hash_abort(&ctx->operation) == PSA_SUCCESS);
716}
717
718int
719md_ctx_size(const md_ctx_t *ctx)
720{
721 if (ctx == NULL)
722 {
723 return 0;
724 }
725 return (int)PSA_HASH_LENGTH(ctx->md_info->psa_alg);
726}
727
728void
729md_ctx_update(md_ctx_t *ctx, const uint8_t *src, size_t src_len)
730{
731 ASSERT(psa_hash_update(&ctx->operation, src, src_len) == PSA_SUCCESS);
732}
733
734void
735md_ctx_final(md_ctx_t *ctx, uint8_t *dst)
736{
737 /* We depend on the caller to ensure that dst has enough room for the hash,
738 * so we just tell PSA that it can hold the appropriate amount of bytes. */
739 size_t dst_size = PSA_HASH_LENGTH(ctx->md_info->psa_alg);
740 size_t hash_length = 0;
741
742 ASSERT(psa_hash_finish(&ctx->operation, dst, dst_size, &hash_length) == PSA_SUCCESS);
743 ASSERT(hash_length == dst_size);
744}
745
747hmac_ctx_new(void)
748{
749 hmac_ctx_t *ctx;
751 return ctx;
752}
753
754void
756{
757 free(ctx);
758}
759
760static void
761hmac_ctx_init_with_arbitrary_key_length(hmac_ctx_t *ctx, const uint8_t *key, size_t key_len, const md_info_t *md_info)
762{
763 ctx->md_info = md_info;
764 psa_set_key_type(&ctx->key_attributes, PSA_KEY_TYPE_HMAC);
765 psa_set_key_algorithm(&ctx->key_attributes, PSA_ALG_HMAC(md_info->psa_alg));
766 psa_set_key_usage_flags(&ctx->key_attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
767
768 if (psa_import_key(&ctx->key_attributes, key, key_len, &ctx->key) != PSA_SUCCESS)
769 {
770 msg(M_FATAL, "psa_import_key failed");
771 }
772
773 ASSERT(psa_mac_sign_setup(&ctx->operation, ctx->key, PSA_ALG_HMAC(md_info->psa_alg)) == PSA_SUCCESS);
774}
775
776void
777hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname)
778{
779 const md_info_t *md_info = md_get(mdname);
780 ASSERT(ctx != NULL && key != NULL && md_info != NULL);
781
782 hmac_ctx_init_with_arbitrary_key_length(ctx, key, PSA_HASH_LENGTH(md_info->psa_alg), md_info);
783}
784
785void
787{
788 ASSERT(psa_mac_abort(&ctx->operation) == PSA_SUCCESS);
789 ASSERT(psa_destroy_key(ctx->key) == PSA_SUCCESS);
790}
791
792int
794{
795 return (int)PSA_HASH_LENGTH(ctx->md_info->psa_alg);
796}
797
798void
800{
801 ASSERT(psa_mac_abort(&ctx->operation) == PSA_SUCCESS);
802 ASSERT(psa_mac_sign_setup(&ctx->operation, ctx->key, PSA_ALG_HMAC(ctx->md_info->psa_alg)) == PSA_SUCCESS);
803}
804
805void
806hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
807{
808 ASSERT(src_len >= 0);
809 ASSERT(psa_mac_update(&ctx->operation, src, (size_t)src_len) == PSA_SUCCESS);
810}
811
812void
813hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
814{
815 /* We depend on the caller to ensure that dst has enough room for the hash,
816 * so we just tell PSA that it can hold the appropriate amount of bytes. */
817 size_t dst_size = PSA_HASH_LENGTH(ctx->md_info->psa_alg);
818 size_t hmac_length = 0;
819
820 ASSERT(psa_mac_sign_finish(&ctx->operation, dst, dst_size, &hmac_length) == PSA_SUCCESS);
821 ASSERT(hmac_length == dst_size);
822}
823
824/*
825 * Generate the hash required by for the \c tls1_PRF function.
826 *
827 * @param md_kt Message digest to use
828 * @param sec Secret to base the hash on
829 * @param sec_len Length of the secret
830 * @param seed Seed to hash
831 * @param seed_len Length of the seed
832 * @param out Output buffer
833 * @param olen Length of the output buffer
834 */
835static void
836tls1_P_hash(const md_info_t *md_info, const uint8_t *sec, size_t sec_len, const uint8_t *seed,
837 int seed_len, uint8_t *out, size_t olen)
838{
839 struct gc_arena gc = gc_new();
840 uint8_t A1[MAX_HMAC_KEY_LENGTH];
841
842#ifndef ENABLE_SMALL
843 /* used by the D_SHOW_KEY_SOURCE, guarded with ENABLE_SMALL to avoid unused
844 * variables warnings if compiled with --enable-small */
845 const size_t olen_orig = olen;
846 const uint8_t *out_orig = out;
847#endif
848
849 hmac_ctx_t *ctx = hmac_ctx_new();
850 hmac_ctx_t *ctx_tmp = hmac_ctx_new();
851
852 dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex(sec, sec_len, 0, &gc));
853 dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex(seed, seed_len, 0, &gc));
854
855 unsigned int chunk = (unsigned int)PSA_HASH_LENGTH(md_info->psa_alg);
856 unsigned int A1_len = (unsigned int)PSA_HASH_LENGTH(md_info->psa_alg);
857
858 /* This is the only place where we init an HMAC with a key that is not
859 * equal to its size, therefore we init the hmac ctx manually here */
860 hmac_ctx_init_with_arbitrary_key_length(ctx, sec, sec_len, md_info);
861 hmac_ctx_init_with_arbitrary_key_length(ctx_tmp, sec, sec_len, md_info);
862
863 hmac_ctx_update(ctx, seed, seed_len);
864 hmac_ctx_final(ctx, A1);
865
866 for (;;)
867 {
868 hmac_ctx_reset(ctx);
869 hmac_ctx_reset(ctx_tmp);
870 hmac_ctx_update(ctx, A1, A1_len);
871 hmac_ctx_update(ctx_tmp, A1, A1_len);
872 hmac_ctx_update(ctx, seed, (int)seed_len);
873
874 if (olen > chunk)
875 {
876 hmac_ctx_final(ctx, out);
877 out += chunk;
878 olen -= chunk;
879 hmac_ctx_final(ctx_tmp, A1); /* calc the next A1 value */
880 }
881 else /* last one */
882 {
883 hmac_ctx_final(ctx, A1);
884 memcpy(out, A1, olen);
885 break;
886 }
887 }
888 hmac_ctx_cleanup(ctx);
889 hmac_ctx_free(ctx);
890 hmac_ctx_cleanup(ctx_tmp);
891 hmac_ctx_free(ctx_tmp);
892 secure_memzero(A1, sizeof(A1));
893
894 dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex(out_orig, olen_orig, 0, &gc));
895 gc_free(&gc);
896}
897
898/*
899 * Use the TLS PRF function for generating data channel keys.
900 * This code is based on the OpenSSL library.
901 *
902 * TLS generates keys as such:
903 *
904 * master_secret[48] = PRF(pre_master_secret[48], "master secret",
905 * ClientHello.random[32] + ServerHello.random[32])
906 *
907 * key_block[] = PRF(SecurityParameters.master_secret[48],
908 * "key expansion",
909 * SecurityParameters.server_random[32] +
910 * SecurityParameters.client_random[32]);
911 *
912 * Notes:
913 *
914 * (1) key_block contains a full set of 4 keys.
915 * (2) The pre-master secret is generated by the client.
916 */
917bool
918ssl_tls1_PRF(const uint8_t *label, size_t label_len, const uint8_t *sec, size_t slen, uint8_t *out1,
919 size_t olen)
920{
921 const md_info_t *md5 = md_get("MD5");
922 const md_info_t *sha1 = md_get("SHA1");
923
924 if (label_len > (size_t)INT_MAX)
925 {
926 return false;
927 }
928
929 struct gc_arena gc = gc_new();
930
931 uint8_t *out2 = (uint8_t *)gc_malloc(olen, false, &gc);
932
933 size_t len = slen / 2;
934 const uint8_t *S1 = sec;
935 const uint8_t *S2 = &(sec[len]);
936 len += (slen & 1); /* add for odd, make longer */
937
938 tls1_P_hash(md5, S1, len, label, (int)label_len, out1, olen);
939 tls1_P_hash(sha1, S2, len, label, (int)label_len, out2, olen);
940
941 for (size_t i = 0; i < olen; i++)
942 {
943 out1[i] ^= out2[i];
944 }
945
946 secure_memzero(out2, olen);
947
948 dmsg(D_SHOW_KEY_SOURCE, "tls1_PRF out[%zu]: %s", olen, format_hex(out1, olen, 0, &gc));
949
950 gc_free(&gc);
951 return true;
952}
953
954void
955crypto_init_lib(void)
956{
957}
958
959void
961{
962}
963
964void
966{
967}
968
969bool
970mbed_log_err(unsigned int flags, int errval, const char *prefix)
971{
972 if (0 != errval)
973 {
974 char errstr[256];
975 mbedtls_strerror(errval, errstr, sizeof(errstr));
976
977 if (NULL == prefix)
978 {
979 prefix = "mbed TLS error";
980 }
981 msg(flags, "%s: %s", prefix, errstr);
982 }
983
984 return 0 == errval;
985}
986
987bool
988mbed_log_func_line(unsigned int flags, int errval, const char *func, int line)
989{
990 char prefix[256];
991
992 if (!checked_snprintf(prefix, sizeof(prefix), "%s:%d", func, line))
993 {
994 return mbed_log_err(flags, errval, func);
995 }
996
997 return mbed_log_err(flags, errval, prefix);
998}
999
1000int
1001memcmp_constant_time(const void *a, const void *b, size_t size)
1002{
1003 return mbedtls_ct_memcmp(a, b, size);
1004}
1005
1006void
1008{
1009 /* Mbed TLS 4 does not currently have a mechanism to discover available
1010 * ciphers. We instead print out the ciphers from cipher_info_table. */
1011
1012#ifndef ENABLE_SMALL
1013 printf("The following ciphers and cipher modes are available for use\n"
1014 "with " PACKAGE_NAME ". Each cipher shown below may be used as a\n"
1015 "parameter to the --data-ciphers (or --cipher) option. Using a\n"
1016 "GCM or CBC mode is recommended. In static key mode only CBC\n"
1017 "mode is allowed.\n\n");
1018#endif
1019
1020 for (size_t i = 0; i < cipher_info_table_entries; i++)
1021 {
1022 const cipher_info_t *info = &cipher_info_table[i];
1023 const char *name = info->name;
1024 if (!cipher_kt_insecure(name) && (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(name)))
1025 {
1026 print_cipher(name);
1027 }
1028 }
1029
1030 printf("\nThe following ciphers have a block size of less than 128 bits, \n"
1031 "and are therefore deprecated. Do not use unless you have to.\n\n");
1032 for (size_t i = 0; i < cipher_info_table_entries; i++)
1033 {
1034 const cipher_info_t *info = &cipher_info_table[i];
1035 const char *name = info->name;
1036 if (cipher_kt_insecure(name) && (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(name)))
1037 {
1038 print_cipher(name);
1039 }
1040 }
1041 printf("\n");
1042}
1043
1044void
1046{
1047 /* Mbed TLS 4 does not currently have a mechanism to discover available
1048 * message digests. We instead print out the digests from md_info_table. */
1049
1050#ifndef ENABLE_SMALL
1051 printf("The following message digests are available for use with\n" PACKAGE_NAME
1052 ". A message digest is used in conjunction with\n"
1053 "the HMAC function, to authenticate received packets.\n"
1054 "You can specify a message digest as parameter to\n"
1055 "the --auth option.\n\n");
1056#endif
1057
1058 for (size_t i = 0; i < md_info_table_entries; i++)
1059 {
1060 const md_info_t *info = &md_info_table[i];
1061 printf("%s %d bit default key\n", info->name,
1062 (unsigned char)PSA_HASH_LENGTH(info->psa_alg) * 8);
1063 }
1064 printf("\n");
1065}
1066
1067void
1069{
1070 printf("Sorry, mbed TLS hardware crypto engine functionality is not "
1071 "available\n");
1072}
1073
1074bool
1075crypto_pem_encode(const char *name, struct buffer *dst, const struct buffer *src,
1076 struct gc_arena *gc)
1077{
1078 /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */
1079 char header[1000 + 1] = { 0 };
1080 char footer[1000 + 1] = { 0 };
1081
1082 if (!checked_snprintf(header, sizeof(header), "-----BEGIN %s-----\n", name))
1083 {
1084 return false;
1085 }
1086 if (!checked_snprintf(footer, sizeof(footer), "-----END %s-----\n", name))
1087 {
1088 return false;
1089 }
1090
1091 size_t out_len = 0;
1092 if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL
1093 != mbedtls_pem_write_buffer(header, footer, CBPTR(src), BLEN(src), NULL, 0, &out_len))
1094 {
1095 return false;
1096 }
1097
1098 /* We set the size buf to out_len-1 to NOT include the 0 byte that
1099 * mbedtls_pem_write_buffer in its length calculation */
1100 *dst = alloc_buf_gc(out_len, gc);
1101 if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, CBPTR(src), BLEN(src), BPTR(dst),
1102 BCAP(dst), &out_len))
1103 || !(out_len < INT_MAX && out_len > 1)
1104 || !buf_inc_len(dst, (int)out_len - 1))
1105 {
1106 CLEAR(*dst);
1107 return false;
1108 }
1109
1110 return true;
1111}
1112
1113bool
1114crypto_pem_decode(const char *name, struct buffer *dst, const struct buffer *src)
1115{
1116 /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */
1117 char header[1000 + 1] = { 0 };
1118 char footer[1000 + 1] = { 0 };
1119
1120 if (!checked_snprintf(header, sizeof(header), "-----BEGIN %s-----", name))
1121 {
1122 return false;
1123 }
1124 if (!checked_snprintf(footer, sizeof(footer), "-----END %s-----", name))
1125 {
1126 return false;
1127 }
1128
1129 /* mbed TLS requires the src to be null-terminated */
1130 /* allocate a new buffer to avoid modifying the src buffer */
1131 struct gc_arena gc = gc_new();
1132 struct buffer input = alloc_buf_gc(BLEN(src) + 1, &gc);
1133 buf_copy(&input, src);
1135
1136 size_t use_len = 0;
1137 mbedtls_pem_context ctx = { 0 };
1138 bool ret =
1139 mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPTR(&input), NULL, 0, &use_len));
1140 size_t buf_size = 0;
1141 const unsigned char *buf = mbedtls_pem_get_buffer(&ctx, &buf_size);
1142 if (ret && !buf_write(dst, buf, buf_size))
1143 {
1144 ret = false;
1145 msg(M_WARN, "PEM decode error: destination buffer too small");
1146 }
1147
1148 mbedtls_pem_free(&ctx);
1149 gc_free(&gc);
1150 return ret;
1151}
1152
1153#endif /* defined(ENABLE_CRYPTO_MBEDTLS) */
void buf_null_terminate(struct buffer *buf)
Force a null terminator at the end of the buffer content.
Definition buffer.c:496
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Allocate memory and, optionally, zero it.
Definition buffer.c:313
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Allocate a buffer of the given size under garbage collection.
Definition buffer.c:77
bool checked_snprintf(char *str, size_t size, const char *format,...)
Like snprintf() but returns an boolean.
Definition buffer.c:1115
Buffer management functions and garbage collection.
static bool buf_copy(struct buffer *dest, const struct buffer *src)
Copy the content of one buffer to the end of another.
Definition buffer.h:1342
#define BPTR(buf)
Return a pointer to the start of the buffer content.
Definition buffer.h:139
static bool buf_inc_len(struct buffer *buf, int inc)
Increase or decrease the length of a buffer.
Definition buffer.h:1119
#define CBPTR(buf)
Return a const pointer to the start of the buffer content.
Definition buffer.h:141
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition buffer.h:748
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Append data to a buffer.
Definition buffer.h:1239
#define BLEN(buf)
Return the length of the buffer content in bytes.
Definition buffer.h:151
static char * format_hex(const uint8_t *data, size_t size, size_t maxoutput, struct gc_arena *gc)
Format a binary buffer as a hex string with spaces every 4 bytes.
Definition buffer.h:960
#define BCAP(buf)
Return the number of bytes available for appending to the buffer.
Definition buffer.h:161
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1965
#define ALLOC_OBJ_CLEAR(dptr, type)
Allocate and zero-initialise memory for a single object of the given type.
Definition buffer.h:2027
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1949
#define PACKAGE_NAME
Definition config.h:492
void print_cipher(const char *ciphername)
Print a cipher list entry.
Definition crypto.c:1717
Data Channel Cryptography Module.
int memcmp_constant_time(const void *a, const void *b, size_t size)
As memcmp(), but constant-time.
Data Channel Cryptography SSL library-specific backend interface.
bool ssl_tls1_PRF(const uint8_t *seed, size_t seed_len, const uint8_t *secret, size_t secret_len, uint8_t *output, size_t output_len)
Calculates the TLS 1.0-1.1 PRF function.
void hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
hmac_ctx_t * hmac_ctx_new(void)
void hmac_ctx_reset(hmac_ctx_t *ctx)
bool cipher_kt_mode_cbc(const char *ciphername)
Check if the supplied cipher is a supported CBC mode cipher.
void show_available_engines(void)
void hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname)
md_ctx_t * md_ctx_new(void)
void hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
void md_ctx_update(md_ctx_t *ctx, const uint8_t *src, size_t src_len)
unsigned int cipher_kt_iv_size(const char *ciphername)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
unsigned int cipher_ctx_iv_length(const cipher_ctx_t *ctx)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
void crypto_unload_provider(const char *provname, provider_t *provider)
Unloads the given (OpenSSL) provider.
void crypto_uninit_lib(void)
bool cipher_kt_mode_aead(const char *ciphername)
Check if the supplied cipher is a supported AEAD mode cipher.
int md_ctx_size(const md_ctx_t *ctx)
void show_available_ciphers(void)
bool md_valid(const char *digest)
Return if a message digest parameters is valid given the name of the digest.
bool cipher_ctx_mode_cbc(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported CBC mode cipher.
void crypto_init_lib(void)
cipher_ctx_t * cipher_ctx_new(void)
Generic cipher functions.
bool cipher_kt_mode_ofb_cfb(const char *ciphername)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
const char * md_kt_name(const char *mdname)
Retrieve a string describing the digest digest (e.g.
int hmac_ctx_size(hmac_ctx_t *ctx)
bool cipher_kt_insecure(const char *ciphername)
Returns true if we consider this cipher to be insecure.
#define MAX_CIPHER_KEY_LENGTH
void crypto_clear_error(void)
bool crypto_pem_decode(const char *name, struct buffer *dst, const struct buffer *src)
Decode a PEM buffer to binary data.
provider_t * crypto_load_provider(const char *provider)
Load the given (OpenSSL) providers.
void cipher_ctx_free(cipher_ctx_t *ctx)
Cleanup and free a cipher context.
int cipher_ctx_mode(const cipher_ctx_t *ctx)
Returns the mode that the cipher runs in.
bool cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
bool cipher_ctx_mode_aead(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported AEAD mode cipher.
void hmac_ctx_free(hmac_ctx_t *ctx)
unsigned int cipher_kt_tag_size(const char *ciphername)
Returns the MAC tag size of the cipher, in bytes.
int cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len)
Updates the given cipher context, providing additional data (AD) for authenticated encryption with ad...
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
const size_t cipher_name_translation_table_count
const char * cipher_kt_name(const char *ciphername)
Retrieve a normalised string describing the cipher (e.g.
#define MAX_HMAC_KEY_LENGTH
unsigned int cipher_kt_key_size(const char *ciphername)
Returns the size of keys used by the cipher, in bytes.
#define OPENVPN_AEAD_TAG_LENGTH
void cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, const char *ciphername, crypto_operation_t enc)
Initialise a cipher context, based on the given key and key type.
int cipher_ctx_get_tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len)
Gets the computed message authenticated code (MAC) tag for this cipher.
int cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, const uint8_t *src, int src_len)
Updates the given cipher context, encrypting data in the source buffer, and placing any complete bloc...
void crypto_init_lib_engine(const char *engine_name)
void hmac_ctx_cleanup(hmac_ctx_t *ctx)
int cipher_ctx_reset(cipher_ctx_t *ctx, const uint8_t *iv_buf)
Resets the given cipher context, setting the IV to the specified value.
const cipher_name_pair cipher_name_translation_table[]
Cipher name translation table.
void md_ctx_cleanup(md_ctx_t *ctx)
unsigned int cipher_ctx_block_size(const cipher_ctx_t *ctx)
Returns the block size of the cipher, in bytes.
int cipher_ctx_final(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len)
Pads the final cipher block using PKCS padding, and output to the destination buffer.
unsigned int cipher_kt_block_size(const char *ciphername)
Returns the block size of the cipher, in bytes.
void md_ctx_final(md_ctx_t *ctx, uint8_t *dst)
unsigned char md_kt_size(const char *mdname)
Returns the size of the message digest, in bytes.
void show_available_digests(void)
bool cipher_valid_reason(const char *ciphername, const char **reason)
Returns if the cipher is valid, based on the given cipher name and provides a reason if invalid.
int cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *tag, size_t tag_len)
Like cipher_ctx_final, but check the computed authentication tag against the supplied (expected) tag.
void md_ctx_init(md_ctx_t *ctx, const char *mdname)
Initialises the given message digest context.
void md_ctx_free(md_ctx_t *ctx)
bool crypto_pem_encode(const char *name, struct buffer *dst, const struct buffer *src, struct gc_arena *gc)
Encode binary data as PEM.
Data Channel Cryptography backend interface using the TF-PSA-Crypto library part of Mbed TLS 4.
#define OPENVPN_OP_DECRYPT
Cipher should decrypt.
#define OPENVPN_MODE_OFB
Cipher is in OFB mode.
#define mbed_ok(errval)
Check errval and log on error.
int crypto_operation_t
bool mbed_log_err(unsigned int flags, int errval, const char *prefix)
Log the supplied mbed TLS error, prefixed by supplied prefix.
#define OPENVPN_MODE_CFB
Cipher is in CFB mode.
#define OPENVPN_MODE_CBC
Cipher is in CBC mode.
void provider_t
#define OPENVPN_OP_ENCRYPT
Cipher should encrypt.
bool mbed_log_func_line(unsigned int flags, int errval, const char *func, int line)
Log the supplied mbed TLS error, prefixed by function name and line number.
static evp_cipher_type * cipher_get(const char *ciphername)
static evp_md_type * md_get(const char *digest)
#define D_SHOW_KEY_SOURCE
Definition errlevel.h:121
#define D_LOW
Definition errlevel.h:96
static SERVICE_STATUS status
Definition interactive.c:52
#define CLEAR(x)
Definition basic.h:32
#define M_FATAL
Definition error.h:90
#define dmsg(flags,...)
Definition error.h:164
#define msg(flags,...)
Definition error.h:152
#define ASSERT(x)
Definition error.h:221
#define M_WARN
Definition error.h:92
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:76
cipher_operation_t operation
uint8_t tag[16]
psa_key_attributes_t key_attributes
mbedtls_svc_key_id_t key
const cipher_info_t * cipher_info
psa_key_type_t psa_key_type
unsigned int iv_bytes
psa_algorithm_t psa_alg
unsigned int key_bytes
const char * name
unsigned int block_size
Struct used in cipher name translation table.
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
const md_info_t * md_info
psa_mac_operation_t operation
psa_key_attributes_t key_attributes
mbedtls_svc_key_id_t key
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:152
const md_info_t * md_info
psa_hash_operation_t operation
psa_algorithm_t psa_alg
const char * name
struct gc_arena gc
Definition test_ssl.c:138
psa_aead_operation_t aead
psa_cipher_operation_t cipher