From: "MaxF (Code Review)" In-Reply-To: References: Reply-To: max@...2606..., arne-openvpn@...1227..., openvpn-devel@lists.sourceforge.net Message-ID: <6e7024155197f1a344f53f6d849a343cc83d2ad6-EmailReplacePatchSet-HTML@...2715...> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Content-Disposition: inline Content-Type: multipart/alternative; boundary="YKGksJiGtY4="; charset=UTF-8 Subject: [Openvpn-devel] [XL] Change in openvpn[master]: Add support for Mbed TLS 4 List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Date: Mon, 15 Dec 2025 12:11:50 -0000 To: plaisthos Cc: openvpn-devel --YKGksJiGtY4= Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable Attention is currently required from: plaisthos. Hello plaisthos, I'd like you to reexamine a change. Please visit http://gerrit.openvpn.net/c/openvpn/+/1441?usp=3Demail to look at the new patch set (#2). Change subject: Add support for Mbed TLS 4 ...................................................................... Add support for Mbed TLS 4 This commit adds support for Mbed TLS 4. This version comes with some drastic changes. The crypto library has been completely redesigned, so the contents of crypto_mbedtls.c are moved to crypto_mbedtls_legacy.c and crypto_mbedtls.c handles the crypto for version 4. Mbed TLS 4 also removed the feature for looking up a crypto algorithm by name, so we need to translate algorithm names to Mbed TLS numbers in OpenVPN. The tables are not yet complete. For symmetric algorithms, I have added AES and Chacha-Poly which should be enough for most use cases. Change-Id: Ib251d546d993b96ed3bd8cb9111bcc627cdb0fae Signed-off-by: Max Fillinger --- M src/openvpn/Makefile.am M src/openvpn/crypto_backend.h M src/openvpn/crypto_mbedtls.c M src/openvpn/crypto_mbedtls.h A src/openvpn/crypto_mbedtls_legacy.c A src/openvpn/crypto_mbedtls_legacy.h M src/openvpn/mbedtls_compat.h M src/openvpn/ssl_mbedtls.c M src/openvpn/ssl_mbedtls.h M src/openvpn/ssl_verify_mbedtls.c M src/openvpn/syshead.h M tests/Makefile.am M tests/unit_tests/openvpn/Makefile.am M tests/unit_tests/openvpn/test_common.h 14 files changed, 2,450 insertions(+), 700 deletions(-) git pull ssh://gerrit.openvpn.net:29418/openvpn refs/changes/41/1441/2 diff --git a/src/openvpn/Makefile.am b/src/openvpn/Makefile.am index db87dfc..1caed27 100644 --- a/src/openvpn/Makefile.am +++ b/src/openvpn/Makefile.am @@ -53,6 +53,7 @@ comp-lz4.c comp-lz4.h \ crypto.c crypto.h crypto_backend.h \ crypto_openssl.c crypto_openssl.h \ + crypto_mbedtls_legacy.c crypto_mbedtls_legacy.h \ crypto_mbedtls.c crypto_mbedtls.h \ crypto_epoch.c crypto_epoch.h \ dco.c dco.h dco_internal.h \ diff --git a/src/openvpn/crypto_backend.h b/src/openvpn/crypto_backend.h index e95752a..39ae90a 100644 --- a/src/openvpn/crypto_backend.h +++ b/src/openvpn/crypto_backend.h @@ -32,9 +32,16 @@ #ifdef ENABLE_CRYPTO_OPENSSL #include "crypto_openssl.h" #endif + #ifdef ENABLE_CRYPTO_MBEDTLS +#include +#if MBEDTLS_VERSION_NUMBER < 0x04000000 +#include "crypto_mbedtls_legacy.h" +#else #include "crypto_mbedtls.h" #endif +#endif + #include "basic.h" #include "buffer.h" diff --git a/src/openvpn/crypto_mbedtls.c b/src/openvpn/crypto_mbedtls.c index 6688d48..425ac92 100644 --- a/src/openvpn/crypto_mbedtls.c +++ b/src/openvpn/crypto_mbedtls.c @@ -6,7 +6,7 @@ * packet compression. * * Copyright (C) 2002-2025 OpenVPN Inc - * Copyright (C) 2010-2021 Sentyron B.V. + * Copyright (C) 2010-2025 Sentyron B.V. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -23,7 +23,8 @@ /** * @file - * Data Channel Cryptography mbed TLS-specific backend interface + * Data Channel Cryptography backend interface using the TF-PSA-Crypto lib= rary + * part of Mbed TLS 4. */ #ifdef HAVE_CONFIG_H @@ -33,6 +34,9 @@ #include "syshead.h" #if defined(ENABLE_CRYPTO_MBEDTLS) +#include + +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 #include "errlevel.h" #include "basic.h" @@ -40,20 +44,16 @@ #include "crypto.h" #include "integer.h" #include "crypto_backend.h" +#include "crypto_mbedtls.h" #include "otime.h" #include "misc.h" -#include -#include +#include +#include +#include #include -#include -#include #include -#include -#include - - /* * * Hardware engine support. Allows loading/unloading of engines. @@ -82,331 +82,75 @@ { } -/* - * - * Functions related to the core crypto library - * - */ +/* The library doesn't support looking up algorithms by string anymore, so= here + * is a lookup table. */ +static const cipher_info_t cipher_info_table[] =3D { +/* TODO: Complete the table. */ -void -crypto_init_lib(void) -{ -} +/* AES */ +#if PSA_WANT_KEY_TYPE_AES +#if PSA_WANT_ALG_GCM + { "AES-128-GCM", PSA_KEY_TYPE_AES, PSA_ALG_GCM, 128 / 8, 96 / 8, 128 /= 8 }, +#endif +#if PSA_WANT_ALG_CBC_PKCS7 + { "AES-128-CBC", PSA_KEY_TYPE_AES, PSA_ALG_CBC_PKCS7, 128 / 8, 128 / 8= , 128 / 8 }, +#endif +#if PSA_WANT_ALG_CTR + { "AES-128-CTR", PSA_KEY_TYPE_AES, PSA_ALG_CTR, 128 / 8, 128 / 8, 128 = / 8 }, +#endif +#if PSA_WANT_ALG_GCM + { "AES-192-GCM", PSA_KEY_TYPE_AES, PSA_ALG_GCM, 192 / 8, 96 / 8, 128 /= 8 }, +#endif +#if PSA_WANT_ALG_CBC_PKCS7 + { "AES-192-CBC", PSA_KEY_TYPE_AES, PSA_ALG_CBC_PKCS7, 192 / 8, 128 / 8= , 128 / 8 }, +#endif +#if PSA_WANT_ALG_CTR + { "AES-192-CTR", PSA_KEY_TYPE_AES, PSA_ALG_CTR, 192 / 8, 128 / 8, 128 = / 8 }, +#endif +#if PSA_WANT_ALG_GCM + { "AES-256-GCM", PSA_KEY_TYPE_AES, PSA_ALG_GCM, 256 / 8, 96 / 8, 128 /= 8 }, +#endif +#if PSA_WANT_ALG_CBC_PKCS7 + { "AES-256-CBC", PSA_KEY_TYPE_AES, PSA_ALG_CBC_PKCS7, 256 / 8, 128 / 8= , 128 / 8 }, +#endif + { "AES-256-CTR", PSA_KEY_TYPE_AES, PSA_ALG_CTR, 256 / 8, 128 / 8, 128 = / 8 }, +#endif /* PSA_WANT_KEY_TYPE_AES */ -void -crypto_uninit_lib(void) -{ -} - -void -crypto_clear_error(void) -{ -} - -bool -mbed_log_err(unsigned int flags, int errval, const char *prefix) -{ - if (0 !=3D errval) - { - char errstr[256]; - mbedtls_strerror(errval, errstr, sizeof(errstr)); - - if (NULL =3D=3D prefix) - { - prefix =3D "mbed TLS error"; - } - msg(flags, "%s: %s", prefix, errstr); - } - - return 0 =3D=3D errval; -} - -bool -mbed_log_func_line(unsigned int flags, int errval, const char *func, int l= ine) -{ - char prefix[256]; - - if (snprintf(prefix, sizeof(prefix), "%s:%d", func, line) >=3D sizeof(= prefix)) - { - return mbed_log_err(flags, errval, func); - } - - return mbed_log_err(flags, errval, prefix); -} - - -#ifdef DMALLOC -void -crypto_init_dmalloc(void) -{ - msg(M_ERR, "Error: dmalloc support is not available for mbed TLS."); -} -#endif /* DMALLOC */ - -const cipher_name_pair cipher_name_translation_table[] =3D { - { "BF-CBC", "BLOWFISH-CBC" }, - { "BF-CFB", "BLOWFISH-CFB64" }, - { "CAMELLIA-128-CFB", "CAMELLIA-128-CFB128" }, - { "CAMELLIA-192-CFB", "CAMELLIA-192-CFB128" }, - { "CAMELLIA-256-CFB", "CAMELLIA-256-CFB128" } +/* Chacha-Poly */ +#if PSA_WANT_KEY_TYPE_CHACHA20 && PSA_WANT_ALG_CHACHA20_POLY1305 + { "CHACHA20-POLY1305", PSA_KEY_TYPE_CHACHA20, PSA_ALG_CHACHA20_POLY130= 5, 256 / 8, 96 / 8, 1 }, +#endif }; +static const size_t cipher_info_table_entries =3D sizeof(cipher_info_table= ) / sizeof(cipher_info_t); + +static const cipher_info_t * +cipher_get(const char *ciphername) +{ + for (size_t i =3D 0; i < cipher_info_table_entries; i++) + { + if (strcmp(ciphername, cipher_info_table[i].name) =3D=3D 0) + { + return &cipher_info_table[i]; + } + } + return NULL; +} + +/* Because Mbed TLS 4 doesn't support looking up algorithms by string, the= re's + * nothing to translate. */ +const cipher_name_pair cipher_name_translation_table[] =3D {}; const size_t cipher_name_translation_table_count =3D - sizeof(cipher_name_translation_table) / sizeof(*cipher_name_translatio= n_table); - -void -show_available_ciphers(void) -{ - const int *ciphers =3D mbedtls_cipher_list(); - -#ifndef ENABLE_SMALL - printf("The following ciphers and cipher modes are available for use\n" - "with " PACKAGE_NAME ". Each cipher shown below may be used as= a\n" - "parameter to the --data-ciphers (or --cipher) option. Using a= \n" - "GCM or CBC mode is recommended. In static key mode only CBC\n" - "mode is allowed.\n\n"); -#endif - - while (*ciphers !=3D 0) - { - const mbedtls_cipher_info_t *info =3D mbedtls_cipher_info_from_typ= e(*ciphers); - const char *name =3D mbedtls_cipher_info_get_name(info); - if (info && name && !cipher_kt_insecure(name) - && (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(name))) - { - print_cipher(name); - } - ciphers++; - } - - printf("\nThe following ciphers have a block size of less than 128 bit= s, \n" - "and are therefore deprecated. Do not use unless you have to.\= n\n"); - ciphers =3D mbedtls_cipher_list(); - while (*ciphers !=3D 0) - { - const mbedtls_cipher_info_t *info =3D mbedtls_cipher_info_from_typ= e(*ciphers); - const char *name =3D mbedtls_cipher_info_get_name(info); - if (info && name && cipher_kt_insecure(name) - && (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(name))) - { - print_cipher(name); - } - ciphers++; - } - printf("\n"); -} - -void -show_available_digests(void) -{ - const int *digests =3D mbedtls_md_list(); - -#ifndef ENABLE_SMALL - printf("The following message digests are available for use with\n" PA= CKAGE_NAME - ". A message digest is used in conjunction with\n" - "the HMAC function, to authenticate received packets.\n" - "You can specify a message digest as parameter to\n" - "the --auth option.\n\n"); -#endif - - while (*digests !=3D 0) - { - const mbedtls_md_info_t *info =3D mbedtls_md_info_from_type(*diges= ts); - - if (info) - { - printf("%s %d bit default key\n", mbedtls_md_get_name(info), - mbedtls_md_get_size(info) * 8); - } - digests++; - } - printf("\n"); -} - -void -show_available_engines(void) -{ - printf("Sorry, mbed TLS hardware crypto engine functionality is not " - "available\n"); -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - -bool -crypto_pem_encode(const char *name, struct buffer *dst, const struct buffe= r *src, - struct gc_arena *gc) -{ - /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ - char header[1000 + 1] =3D { 0 }; - char footer[1000 + 1] =3D { 0 }; - - if (snprintf(header, sizeof(header), "-----BEGIN %s-----\n", name) >= =3D sizeof(header)) - { - return false; - } - if (snprintf(footer, sizeof(footer), "-----END %s-----\n", name) >=3D = sizeof(footer)) - { - return false; - } - - size_t out_len =3D 0; - if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL - !=3D mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src)= , NULL, 0, &out_len)) - { - return false; - } - - /* We set the size buf to out_len-1 to NOT include the 0 byte that - * mbedtls_pem_write_buffer in its length calculation */ - *dst =3D alloc_buf_gc(out_len, gc); - if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(= src), BPTR(dst), - BCAP(dst), &out_len)) - || !buf_inc_len(dst, out_len - 1)) - { - CLEAR(*dst); - return false; - } - - return true; -} - -bool -crypto_pem_decode(const char *name, struct buffer *dst, const struct buffe= r *src) -{ - /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ - char header[1000 + 1] =3D { 0 }; - char footer[1000 + 1] =3D { 0 }; - - if (snprintf(header, sizeof(header), "-----BEGIN %s-----", name) >=3D = sizeof(header)) - { - return false; - } - if (snprintf(footer, sizeof(footer), "-----END %s-----", name) >=3D si= zeof(footer)) - { - return false; - } - - /* mbed TLS requires the src to be null-terminated */ - /* allocate a new buffer to avoid modifying the src buffer */ - struct gc_arena gc =3D gc_new(); - struct buffer input =3D alloc_buf_gc(BLEN(src) + 1, &gc); - buf_copy(&input, src); - buf_null_terminate(&input); - - size_t use_len =3D 0; - mbedtls_pem_context ctx =3D { 0 }; - bool ret =3D - mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPTR(&input)= , NULL, 0, &use_len)); - size_t buf_size =3D 0; - const unsigned char *buf =3D mbedtls_pem_get_buffer(&ctx, &buf_size); - if (ret && !buf_write(dst, buf, buf_size)) - { - ret =3D false; - msg(M_WARN, "PEM decode error: destination buffer too small"); - } - - mbedtls_pem_free(&ctx); - gc_free(&gc); - return ret; -} - -/* - * - * Random number functions, used in cases where we want - * reasonably strong cryptographic random number generation - * without depleting our entropy pool. Used for random - * IV values and a number of other miscellaneous tasks. - * - */ - -/* - * Initialise the given ctr_drbg context, using a personalisation string a= nd an - * entropy gathering function. - */ -mbedtls_ctr_drbg_context * -rand_ctx_get(void) -{ - static mbedtls_entropy_context ec =3D { 0 }; - static mbedtls_ctr_drbg_context cd_ctx =3D { 0 }; - static bool rand_initialised =3D false; - - if (!rand_initialised) - { - struct gc_arena gc =3D gc_new(); - struct buffer pers_string =3D alloc_buf_gc(100, &gc); - - /* - * Personalisation string, should be as unique as possible (see NI= ST - * 800-90 section 8.7.1). We have very little information at this = stage. - * Include Program Name, memory address of the context and PID. - */ - buf_printf(&pers_string, "OpenVPN %0u %p %s", platform_getpid(), &= cd_ctx, - time_string(0, 0, 0, &gc)); - - /* Initialise mbed TLS RNG, and built-in entropy sources */ - mbedtls_entropy_init(&ec); - - mbedtls_ctr_drbg_init(&cd_ctx); - if (!mbed_ok(mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, = &ec, BPTR(&pers_string), - BLEN(&pers_string)))) - { - msg(M_FATAL, "Failed to initialize random generator"); - } - - gc_free(&gc); - rand_initialised =3D true; - } - - return &cd_ctx; -} - -#ifdef ENABLE_PREDICTION_RESISTANCE -void -rand_ctx_enable_prediction_resistance(void) -{ - mbedtls_ctr_drbg_context *cd_ctx =3D rand_ctx_get(); - - mbedtls_ctr_drbg_set_prediction_resistance(cd_ctx, 1); -} -#endif /* ENABLE_PREDICTION_RESISTANCE */ + sizeof(cipher_name_translation_table) / sizeof(cipher_name_pair); int rand_bytes(uint8_t *output, int len) { - mbedtls_ctr_drbg_context *rng_ctx =3D rand_ctx_get(); - - while (len > 0) + if (len < 0) { - const size_t blen =3D min_int(len, MBEDTLS_CTR_DRBG_MAX_REQUEST); - if (0 !=3D mbedtls_ctr_drbg_random(rng_ctx, output, blen)) - { - return 0; - } - - output +=3D blen; - len -=3D blen; + return 0; } - - return 1; -} - -/* - * - * Generic cipher key type functions - * - */ -static const mbedtls_cipher_info_t * -cipher_get(const char *ciphername) -{ - ASSERT(ciphername); - - const mbedtls_cipher_info_t *cipher =3D NULL; - - ciphername =3D translate_cipher_name_from_openvpn(ciphername); - cipher =3D mbedtls_cipher_info_from_string(ciphername); - return cipher; + psa_status_t result =3D psa_generate_random(output, (size_t)len); + return result =3D=3D PSA_SUCCESS; } bool @@ -414,23 +158,22 @@ { ASSERT(reason); - const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); + const cipher_info_t *cipher_info =3D cipher_get(ciphername); - if (NULL =3D=3D cipher) + if (cipher_info =3D=3D NULL) { msg(D_LOW, "Cipher algorithm '%s' not found", ciphername); *reason =3D "disabled because unknown"; return false; } - const size_t key_bytelen =3D mbedtls_cipher_info_get_key_bitlen(cipher= ) / 8; - if (key_bytelen > MAX_CIPHER_KEY_LENGTH) + if (cipher_info->key_bytes > MAX_CIPHER_KEY_LENGTH) { msg(D_LOW, - "Cipher algorithm '%s' uses a default key size (%zu bytes) " + "Cipher algorithm '%s' uses a default key size (%d bytes) " "which is larger than " PACKAGE_NAME "'s current maximum key s= ize " "(%d bytes)", - ciphername, key_bytelen, MAX_CIPHER_KEY_LENGTH); + ciphername, cipher_info->key_bytes, MAX_CIPHER_KEY_LENGTH); *reason =3D "disabled due to key size too large"; return false; } @@ -442,49 +185,46 @@ const char * cipher_kt_name(const char *ciphername) { - const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); - if (NULL =3D=3D cipher_kt) + const cipher_info_t *cipher_info =3D cipher_get(ciphername); + if (cipher_info =3D=3D NULL) { return "[null-cipher]"; } - - return translate_cipher_name_to_openvpn(mbedtls_cipher_info_get_name(c= ipher_kt)); + return cipher_info->name; } int cipher_kt_key_size(const char *ciphername) { - const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); - - if (NULL =3D=3D cipher_kt) + const cipher_info_t *cipher_info =3D cipher_get(ciphername); + if (cipher_info =3D=3D NULL) { return 0; } - - return (int)mbedtls_cipher_info_get_key_bitlen(cipher_kt) / 8; + return (int)cipher_info->key_bytes; } int cipher_kt_iv_size(const char *ciphername) { - const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); + const cipher_info_t *cipher_info =3D cipher_get(ciphername); - if (NULL =3D=3D cipher_kt) + if (cipher_info =3D=3D NULL) { return 0; } - return (int)mbedtls_cipher_info_get_iv_size(cipher_kt); + return cipher_info->iv_bytes; } int cipher_kt_block_size(const char *ciphername) { - const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); - if (NULL =3D=3D cipher_kt) + const cipher_info_t *cipher_info =3D cipher_get(ciphername); + if (cipher_info =3D=3D NULL) { return 0; } - return (int)mbedtls_cipher_info_get_block_size(cipher_kt); + return cipher_info->block_size; } int @@ -500,498 +240,599 @@ bool cipher_kt_insecure(const char *ciphername) { - const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); - if (!cipher_kt) + const cipher_info_t *cipher_info =3D cipher_get(ciphername); + if (cipher_info =3D=3D NULL) { return true; } - return !(cipher_kt_block_size(ciphername) >=3D 128 / 8 -#ifdef MBEDTLS_CHACHAPOLY_C - || mbedtls_cipher_info_get_type(cipher_kt) =3D=3D MBEDTLS_CIP= HER_CHACHA20_POLY1305 -#endif - ); -} - -static mbedtls_cipher_mode_t -cipher_kt_mode(const mbedtls_cipher_info_t *cipher_kt) -{ - ASSERT(NULL !=3D cipher_kt); - return mbedtls_cipher_info_get_mode(cipher_kt); + return !(cipher_info->block_size >=3D 128 / 8 + || cipher_info->psa_alg =3D=3D PSA_ALG_CHACHA20_POLY1305); } bool cipher_kt_mode_cbc(const char *ciphername) { - const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); - return cipher && cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CBC; + const cipher_info_t *cipher_info =3D cipher_get(ciphername); + if (cipher_info =3D=3D NULL) + { + return false; + } + return cipher_info->psa_alg =3D=3D PSA_ALG_CBC_PKCS7; } =20 bool cipher_kt_mode_ofb_cfb(const char *ciphername) { - const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); - return cipher - && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB - || cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CFB); + const cipher_info_t *cipher_info =3D cipher_get(ciphername); + if (cipher_info =3D=3D NULL) + { + return false; + } + return cipher_info->psa_alg =3D=3D PSA_ALG_OFB || cipher_info->psa_alg= =3D=3D PSA_ALG_CFB; } bool cipher_kt_mode_aead(const char *ciphername) { - const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); - return cipher - && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_GCM -#ifdef MBEDTLS_CHACHAPOLY_C - || cipher_kt_mode(cipher) =3D=3D MBEDTLS_MODE_CHACHAPOLY -#endif - ); + const cipher_info_t *cipher_info =3D cipher_get(ciphername); + if (cipher_info =3D=3D NULL) + { + return false; + } + return cipher_info->psa_alg =3D=3D PSA_ALG_GCM || cipher_info->psa_alg= =3D=3D PSA_ALG_CHACHA20_POLY1305; } - -/* - * - * Generic cipher context functions - * - */ - -mbedtls_cipher_context_t * +cipher_ctx_t * cipher_ctx_new(void) { - mbedtls_cipher_context_t *ctx; - ALLOC_OBJ(ctx, mbedtls_cipher_context_t); + cipher_ctx_t *ctx; + /* Initializing the object with zeros ensures that it is always safe t= o call + * cipher_ctx_free. */ + ALLOC_OBJ_CLEAR(ctx, cipher_ctx_t); return ctx; } void -cipher_ctx_free(mbedtls_cipher_context_t *ctx) +cipher_ctx_free(cipher_ctx_t *ctx) { - mbedtls_cipher_free(ctx); + /* TODO: Log warning on errors? */ + if (cipher_ctx_mode_aead(ctx)) + { + psa_aead_abort(&ctx->operation.aead); + } + else + { + psa_cipher_abort(&ctx->operation.cipher); + } + psa_destroy_key(ctx->key); free(ctx); } void -cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, const c= har *ciphername, +cipher_ctx_init(cipher_ctx_t *ctx, const uint8_t *key, const char *ciphern= ame, crypto_operation_t enc) { - ASSERT(NULL !=3D ciphername && NULL !=3D ctx); + ASSERT(ciphername !=3D NULL && ctx !=3D NULL); CLEAR(*ctx); - const mbedtls_cipher_info_t *kt =3D cipher_get(ciphername); - ASSERT(kt); - size_t key_bitlen =3D mbedtls_cipher_info_get_key_bitlen(kt); + ctx->cipher_info =3D cipher_get(ciphername); + ASSERT(ctx->cipher_info !=3D NULL); - if (!mbed_ok(mbedtls_cipher_setup(ctx, kt))) - { - msg(M_FATAL, "mbed TLS cipher context init #1"); - } + psa_set_key_type(&ctx->key_attributes, ctx->cipher_info->psa_key_type); + psa_set_key_algorithm(&ctx->key_attributes, ctx->cipher_info->psa_alg); + psa_set_key_bits(&ctx->key_attributes, (size_t)ctx->cipher_info->key_b= ytes * 8); + psa_set_key_usage_flags(&ctx->key_attributes, + enc =3D=3D OPENVPN_OP_ENCRYPT ? PSA_KEY_USAGE_= ENCRYPT : PSA_KEY_USAGE_DECRYPT); - if (!mbed_ok(mbedtls_cipher_setkey(ctx, key, (int)key_bitlen, enc))) + if (psa_import_key(&ctx->key_attributes, key, (size_t)ctx->cipher_info= ->key_bytes, &ctx->key) !=3D PSA_SUCCESS) { - msg(M_FATAL, "mbed TLS cipher set key"); - } - - if (mbedtls_cipher_info_get_mode(kt) =3D=3D MBEDTLS_MODE_CBC) - { - if (!mbed_ok(mbedtls_cipher_set_padding_mode(ctx, MBEDTLS_PADDING_= PKCS7))) - { - msg(M_FATAL, "mbed TLS cipher set padding mode"); - } + msg(M_FATAL, "psa_import_key failed"); } /* make sure we used a big enough key */ - ASSERT(mbedtls_cipher_get_key_bitlen(ctx) <=3D key_bitlen); + ASSERT(psa_get_key_bits(&ctx->key_attributes) =3D=3D (size_t)(8 * ctx-= >cipher_info->key_bytes)); } int -cipher_ctx_iv_length(const mbedtls_cipher_context_t *ctx) +cipher_ctx_iv_length(const cipher_ctx_t *ctx) { - return mbedtls_cipher_get_iv_size(ctx); + return ctx->cipher_info->iv_bytes; } int cipher_ctx_get_tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len) { - if (tag_len > SIZE_MAX) + if (!ctx->aead_finished || tag_len < OPENVPN_AEAD_TAG_LENGTH) { return 0; } - if (!mbed_ok(mbedtls_cipher_write_tag(ctx, (unsigned char *)tag, tag_l= en))) - { - return 0; - } - + memcpy(tag, ctx->tag, OPENVPN_AEAD_TAG_LENGTH); return 1; } int -cipher_ctx_block_size(const mbedtls_cipher_context_t *ctx) +cipher_ctx_block_size(const cipher_ctx_t *ctx) { - return (int)mbedtls_cipher_get_block_size(ctx); + return ctx->cipher_info->block_size; } int -cipher_ctx_mode(const mbedtls_cipher_context_t *ctx) +cipher_ctx_mode(const cipher_ctx_t *ctx) { - ASSERT(NULL !=3D ctx); - - return mbedtls_cipher_get_cipher_mode(ctx); + ASSERT(ctx !=3D NULL); + return (int)psa_get_key_algorithm(&ctx->key_attributes); } bool cipher_ctx_mode_cbc(const cipher_ctx_t *ctx) { - return ctx && cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CBC; + return ctx !=3D NULL && cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CBC; } - bool cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx) { - return ctx - && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_OFB - || cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CFB); + if (ctx =3D=3D NULL) + { + return false; + } + int mode =3D cipher_ctx_mode(ctx); + return mode =3D=3D OPENVPN_MODE_OFB || mode =3D=3D OPENVPN_MODE_CFB; } bool cipher_ctx_mode_aead(const cipher_ctx_t *ctx) { - return ctx - && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_GCM -#ifdef MBEDTLS_CHACHAPOLY_C - || cipher_ctx_mode(ctx) =3D=3D MBEDTLS_MODE_CHACHAPOLY -#endif - ); + if (ctx =3D=3D NULL) + { + return false; + } + int mode =3D cipher_ctx_mode(ctx); + return mode =3D=3D (int)PSA_ALG_GCM || mode =3D=3D (int)PSA_ALG_CHACHA= 20_POLY1305; +} + +static int +cipher_ctx_direction(const cipher_ctx_t *ctx) +{ + psa_key_usage_t key_usage =3D psa_get_key_usage_flags(&ctx->key_attrib= utes); + if (key_usage & PSA_KEY_USAGE_ENCRYPT) + { + return OPENVPN_OP_ENCRYPT; + } + else if (key_usage & PSA_KEY_USAGE_DECRYPT) + { + return OPENVPN_OP_DECRYPT; + } + else + { + return -1; + } } int -cipher_ctx_reset(mbedtls_cipher_context_t *ctx, const uint8_t *iv_buf) +cipher_ctx_reset(cipher_ctx_t *ctx, const uint8_t *iv_buf) { - if (!mbed_ok(mbedtls_cipher_reset(ctx))) - { - return 0; - } + psa_status_t status =3D 0; - if (!mbed_ok(mbedtls_cipher_set_iv(ctx, iv_buf, (size_t)mbedtls_cipher= _get_iv_size(ctx)))) + if (cipher_ctx_mode_aead(ctx)) { - return 0; + if (psa_aead_abort(&ctx->operation.aead) !=3D PSA_SUCCESS) + { + return 0; + } + + if (cipher_ctx_direction(ctx) =3D=3D OPENVPN_OP_ENCRYPT) + { + status =3D psa_aead_encrypt_setup(&ctx->operation.aead, ctx->k= ey, ctx->cipher_info->psa_alg); + } + else if (cipher_ctx_direction(ctx) =3D=3D OPENVPN_OP_DECRYPT) + { + status =3D psa_aead_decrypt_setup(&ctx->operation.aead, ctx->k= ey, ctx->cipher_info->psa_alg); + } + else + { + return 0; + } + + if (status !=3D PSA_SUCCESS) + { + return 0; + } + + status =3D psa_aead_set_nonce(&ctx->operation.aead, iv_buf, ctx->c= ipher_info->iv_bytes); + if (status !=3D PSA_SUCCESS) + { + return 0; + } + } + else + { + if (psa_cipher_abort(&ctx->operation.cipher) !=3D PSA_SUCCESS) + { + return 0; + } + + if (cipher_ctx_direction(ctx) =3D=3D OPENVPN_OP_ENCRYPT) + { + status =3D psa_cipher_encrypt_setup(&ctx->operation.cipher, ct= x->key, ctx->cipher_info->psa_alg); + } + else if (cipher_ctx_direction(ctx) =3D=3D OPENVPN_OP_DECRYPT) + { + status =3D psa_cipher_decrypt_setup(&ctx->operation.cipher, ct= x->key, ctx->cipher_info->psa_alg); + } + else + { + return 0; + } + + if (status !=3D PSA_SUCCESS) + { + return 0; + } + + status =3D psa_cipher_set_iv(&ctx->operation.cipher, iv_buf, ctx->= cipher_info->iv_bytes); + if (status !=3D PSA_SUCCESS) + { + return 0; + } } return 1; } +/* We rely on the caller to ensure that the destination buffer has enough = room, + * but Mbed TLS always wants a size for the destination buffer. This funct= ion + * calculates the minimum necessary size for a given cipher and input leng= th. + * + * This funcion assumes that src_len has been checked to be >=3D 0. */ +static size_t +needed_dst_size(const cipher_ctx_t *ctx, int src_len) +{ + int mode =3D cipher_ctx_mode(ctx); + if (mode =3D=3D PSA_ALG_CTR || mode =3D=3D PSA_ALG_GCM || mode =3D=3D = PSA_ALG_CHACHA20_POLY1305) + { + /* These algorithms are based on a keystream, so the input and out= put + * length are always equal. */ + return (size_t)src_len; + } + else + { + /* These algorithms are block-based. The number of output blocks t= hat are + * produced is at most 1 + src_len / block_size. */ + size_t block_size =3D (size_t)cipher_ctx_block_size(ctx); + size_t max_blocks =3D 1 + (size_t)src_len / block_size; + return max_blocks * block_size; + } +} + int cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len) { - if (src_len > SIZE_MAX) + if (src_len < 0 || !cipher_ctx_mode_aead(ctx)) { return 0; } - if (!mbed_ok(mbedtls_cipher_update_ad(ctx, src, src_len))) + if (psa_aead_update_ad(&ctx->operation.aead, src, (size_t)src_len) != =3D PSA_SUCCESS) { return 0; } + return 1; +} + +int +cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, uint8_t *= src, int src_len) +{ + if (src_len < 0) + { + return 0; + } + + size_t dst_size =3D needed_dst_size(ctx, src_len); + size_t psa_output_len =3D 0; + psa_status_t status =3D 0; + + if (cipher_ctx_mode_aead(ctx)) + { + status =3D psa_aead_update(&ctx->operation.aead, src, (size_t)src_= len, dst, dst_size, &psa_output_len); + } + else + { + status =3D psa_cipher_update(&ctx->operation.cipher, src, (size_t)= src_len, dst, dst_size, &psa_output_len); + } + + if (status !=3D PSA_SUCCESS) + { + return 0; + } + + if (psa_output_len > INT_MAX) + { + return 0; + } + *dst_len =3D (int)psa_output_len; return 1; } int -cipher_ctx_update(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_le= n, uint8_t *src, - int src_len) +cipher_ctx_final(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len) { - size_t s_dst_len =3D *dst_len; + size_t dst_size =3D needed_dst_size(ctx, 0); + size_t psa_output_len =3D 0; + psa_status_t status =3D 0; - if (!mbed_ok(mbedtls_cipher_update(ctx, src, (size_t)src_len, dst, &s_= dst_len))) + if (cipher_ctx_mode_aead(ctx)) { - return 0; + size_t actual_tag_size =3D 0; + status =3D psa_aead_finish(&ctx->operation.aead, + dst, + dst_size, + &psa_output_len, + ctx->tag, + (size_t)OPENVPN_AEAD_TAG_LENGTH, + &actual_tag_size); + if (status !=3D PSA_SUCCESS || psa_output_len > (size_t)INT_MAX ||= actual_tag_size !=3D (size_t)OPENVPN_AEAD_TAG_LENGTH) + { + return 0; + } + ctx->aead_finished =3D true; + } + else + { + status =3D psa_cipher_finish(&ctx->operation.cipher, dst, dst_size= , &psa_output_len); + if (status !=3D PSA_SUCCESS || psa_output_len > (size_t)INT_MAX) + { + return 0; + } } - *dst_len =3D s_dst_len; + *dst_len =3D (int)psa_output_len; return 1; } int -cipher_ctx_final(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_len) +cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, = uint8_t *tag, size_t tag_len) { - size_t s_dst_len =3D *dst_len; - - if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &s_dst_len))) + if (cipher_ctx_direction(ctx) !=3D OPENVPN_OP_DECRYPT || !cipher_ctx_m= ode_aead(ctx)) { return 0; } - *dst_len =3D s_dst_len; + size_t psa_output_len =3D 0; + psa_status_t status =3D 0; + + status =3D psa_aead_verify(&ctx->operation.aead, dst, 0, &psa_output_l= en, tag, tag_len); + if (status !=3D PSA_SUCCESS || psa_output_len > (size_t)INT_MAX) + { + return 0; + } + *dst_len =3D (int)psa_output_len; return 1; } -int -cipher_ctx_final_check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst, in= t *dst_len, uint8_t *tag, - size_t tag_len) +static const md_info_t md_info_table[] =3D { + /* TODO: Fill out table. */ + { "MD5", PSA_ALG_MD5 }, + { "SHA1", PSA_ALG_SHA_1 }, + { "SHA256", PSA_ALG_SHA_256 }, +}; +const size_t md_info_table_entries =3D sizeof(md_info_table) / sizeof(md_i= nfo_t); + +static const md_info_t * +md_get(const char *digest_name) { - size_t olen =3D 0; - - if (MBEDTLS_DECRYPT !=3D mbedtls_cipher_get_operation(ctx)) + for (size_t i =3D 0; i < md_info_table_entries; i++) { - return 0; + if (strcmp(digest_name, md_info_table[i].name) =3D=3D 0) + { + return &md_info_table[i]; + } } - - if (tag_len > SIZE_MAX) - { - return 0; - } - - if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &olen))) - { - msg(D_CRYPT_ERRORS, "%s: cipher_ctx_final() failed", __func__); - return 0; - } - - if (olen > INT_MAX) - { - return 0; - } - *dst_len =3D olen; - - if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (const unsigned char *)tag,= tag_len))) - { - return 0; - } - - return 1; -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic pop -#endif - -/* - * - * Generic message digest information functions - * - */ - - -static const mbedtls_md_info_t * -md_get(const char *digest) -{ - const mbedtls_md_info_t *md =3D NULL; - ASSERT(digest); - - md =3D mbedtls_md_info_from_string(digest); - if (!md) - { - msg(M_FATAL, "Message hash algorithm '%s' not found", digest); - } - if (mbedtls_md_get_size(md) > MAX_HMAC_KEY_LENGTH) - { - msg(M_FATAL, - "Message hash algorithm '%s' uses a default hash size (%d byte= s) which is larger than " PACKAGE_NAME - "'s current maximum hash size (%d bytes)", - digest, mbedtls_md_get_size(md), MAX_HMAC_KEY_LENGTH); - } - return md; + return NULL; } bool md_valid(const char *digest) { - const mbedtls_md_info_t *md =3D mbedtls_md_info_from_string(digest); + const md_info_t *md =3D md_get(digest); return md !=3D NULL; } const char * md_kt_name(const char *mdname) { - if (!strcmp("none", mdname)) + if (strcmp("none", mdname) =3D=3D 0) { return "[null-digest]"; } - const mbedtls_md_info_t *kt =3D md_get(mdname); - return mbedtls_md_get_name(kt); + const md_info_t *md =3D md_get(mdname); + if (md =3D=3D NULL) + { + return NULL; + } + return md->name; } unsigned char md_kt_size(const char *mdname) { - if (!strcmp("none", mdname)) + if (strcmp("none", mdname) =3D=3D 0) { return 0; } - const mbedtls_md_info_t *kt =3D md_get(mdname); - return mbedtls_md_get_size(kt); + const md_info_t *md_info =3D md_get(mdname); + if (md_info =3D=3D NULL) + { + return 0; + } + return (unsigned char)PSA_HASH_LENGTH(md_info->psa_alg); } -/* - * - * Generic message digest functions - * - */ +md_ctx_t * +md_ctx_new(void) +{ + md_ctx_t *ctx; + ALLOC_OBJ_CLEAR(ctx, md_ctx_t); + return ctx; +} int md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst) { - const mbedtls_md_info_t *kt =3D md_get(mdname); - return 0 =3D=3D mbedtls_md(kt, src, src_len, dst); -} + const md_info_t *md =3D md_get(mdname); + if (md =3D=3D NULL || src_len < 0) + { + return 0; + } -mbedtls_md_context_t * -md_ctx_new(void) -{ - mbedtls_md_context_t *ctx; - ALLOC_OBJ_CLEAR(ctx, mbedtls_md_context_t); - return ctx; + /* We depend on the caller to ensure that dst has enough room for the = hash, + * so we just tell PSA that it can hold the appropriate amount of byte= s. */ + size_t dst_size =3D PSA_HASH_LENGTH(md->psa_alg); + size_t hash_length =3D 0; + + psa_status_t status =3D psa_hash_compute(md->psa_alg, src, (size_t)src= _len, dst, dst_size, &hash_length); + if (status !=3D PSA_SUCCESS || hash_length !=3D dst_size) + { + return 0; + } + return 1; } void -md_ctx_free(mbedtls_md_context_t *ctx) +md_ctx_free(md_ctx_t *ctx) { free(ctx); } void -md_ctx_init(mbedtls_md_context_t *ctx, const char *mdname) +md_ctx_init(md_ctx_t *ctx, const char *mdname) { - const mbedtls_md_info_t *kt =3D md_get(mdname); - ASSERT(NULL !=3D ctx && NULL !=3D kt); + const md_info_t *md_info =3D md_get(mdname); + ASSERT(ctx !=3D NULL && md_info !=3D NULL); - mbedtls_md_init(ctx); - ASSERT(0 =3D=3D mbedtls_md_setup(ctx, kt, 0)); - ASSERT(0 =3D=3D mbedtls_md_starts(ctx)); + ctx->md_info =3D md_info; + ASSERT(psa_hash_setup(&ctx->operation, md_info->psa_alg) =3D=3D PSA_SU= CCESS); } =20 void -md_ctx_cleanup(mbedtls_md_context_t *ctx) +md_ctx_cleanup(md_ctx_t *ctx) { - mbedtls_md_free(ctx); + /* TODO: Warn if not success? */ + psa_hash_abort(&ctx->operation); } int -md_ctx_size(const mbedtls_md_context_t *ctx) +md_ctx_size(const md_ctx_t *ctx) { - if (NULL =3D=3D ctx) + if (ctx =3D=3D NULL) { return 0; } - return (int)mbedtls_md_get_size(mbedtls_md_info_from_ctx(ctx)); + return (int)PSA_HASH_LENGTH(ctx->md_info->psa_alg); } void -md_ctx_update(mbedtls_md_context_t *ctx, const uint8_t *src, size_t src_le= n) +md_ctx_update(md_ctx_t *ctx, const uint8_t *src, size_t src_len) { - ASSERT(0 =3D=3D mbedtls_md_update(ctx, src, src_len)); + ASSERT(psa_hash_update(&ctx->operation, src, src_len) =3D=3D PSA_SUCCE= SS); } void -md_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst) +md_ctx_final(md_ctx_t *ctx, uint8_t *dst) { - ASSERT(0 =3D=3D mbedtls_md_finish(ctx, dst)); - mbedtls_md_free(ctx); + /* We depend on the caller to ensure that dst has enough room for the = hash, + * so we just tell PSA that it can hold the appropriate amount of byte= s. */ + size_t dst_size =3D PSA_HASH_LENGTH(ctx->md_info->psa_alg); + size_t hash_length =3D 0; + + ASSERT(psa_hash_finish(&ctx->operation, dst, dst_size, &hash_length) = =3D=3D PSA_SUCCESS); + ASSERT(hash_length =3D=3D dst_size); } - -/* - * - * Generic HMAC functions - * - */ - - -/* - * TODO: re-enable dmsg for crypto debug - */ - -mbedtls_md_context_t * +hmac_ctx_t * hmac_ctx_new(void) { - mbedtls_md_context_t *ctx; - ALLOC_OBJ(ctx, mbedtls_md_context_t); + hmac_ctx_t *ctx; + ALLOC_OBJ_CLEAR(ctx, hmac_ctx_t); return ctx; } void -hmac_ctx_free(mbedtls_md_context_t *ctx) +hmac_ctx_free(hmac_ctx_t *ctx) { free(ctx); } -void -hmac_ctx_init(mbedtls_md_context_t *ctx, const uint8_t *key, const char *m= dname) +static void +hmac_ctx_init_with_arbitrary_key_length(hmac_ctx_t *ctx, const uint8_t *ke= y, size_t key_len, const md_info_t *md_info) { - const mbedtls_md_info_t *kt =3D md_get(mdname); - ASSERT(NULL !=3D kt && NULL !=3D ctx); + ctx->md_info =3D md_info; + psa_set_key_type(&ctx->key_attributes, PSA_KEY_TYPE_HMAC); + psa_set_key_algorithm(&ctx->key_attributes, PSA_ALG_HMAC(md_info->psa_= alg)); + psa_set_key_usage_flags(&ctx->key_attributes, PSA_KEY_USAGE_SIGN_MESSA= GE); - mbedtls_md_init(ctx); - int key_len =3D mbedtls_md_get_size(kt); - ASSERT(0 =3D=3D mbedtls_md_setup(ctx, kt, 1)); - ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx, key, key_len)); + if (psa_import_key(&ctx->key_attributes, key, key_len, &ctx->key) !=3D= PSA_SUCCESS) + { + msg(M_FATAL, "psa_import_key failed"); + } - /* make sure we used a big enough key */ - ASSERT(mbedtls_md_get_size(kt) <=3D key_len); + ASSERT(psa_mac_sign_setup(&ctx->operation, ctx->key, PSA_ALG_HMAC(md_i= nfo->psa_alg)) =3D=3D PSA_SUCCESS); } void -hmac_ctx_cleanup(mbedtls_md_context_t *ctx) +hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname) { - mbedtls_md_free(ctx); + const md_info_t *md_info =3D md_get(mdname); + ASSERT(ctx !=3D NULL && key !=3D NULL && md_info !=3D NULL); + + hmac_ctx_init_with_arbitrary_key_length(ctx, key, PSA_HASH_LENGTH(md_i= nfo->psa_alg), md_info); +} + +void +hmac_ctx_cleanup(hmac_ctx_t *ctx) +{ + /* TODO: Warn if not success? */ + psa_mac_abort(&ctx->operation); + psa_destroy_key(ctx->key); } int -hmac_ctx_size(mbedtls_md_context_t *ctx) +hmac_ctx_size(hmac_ctx_t *ctx) { - if (NULL =3D=3D ctx) - { - return 0; - } - return mbedtls_md_get_size(mbedtls_md_info_from_ctx(ctx)); + return (int)PSA_HASH_LENGTH(ctx->md_info->psa_alg); } void -hmac_ctx_reset(mbedtls_md_context_t *ctx) +hmac_ctx_reset(hmac_ctx_t *ctx) { - ASSERT(0 =3D=3D mbedtls_md_hmac_reset(ctx)); + ASSERT(psa_mac_abort(&ctx->operation) =3D=3D PSA_SUCCESS); + ASSERT(psa_mac_sign_setup(&ctx->operation, ctx->key, PSA_ALG_HMAC(ctx-= >md_info->psa_alg)) =3D=3D PSA_SUCCESS); } void -hmac_ctx_update(mbedtls_md_context_t *ctx, const uint8_t *src, int src_len) +hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len) { - ASSERT(0 =3D=3D mbedtls_md_hmac_update(ctx, src, src_len)); + ASSERT(src_len >=3D 0); + ASSERT(psa_mac_update(&ctx->operation, src, (size_t)src_len) =3D=3D PS= A_SUCCESS); } void -hmac_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst) +hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst) { - ASSERT(0 =3D=3D mbedtls_md_hmac_finish(ctx, dst)); + /* We depend on the caller to ensure that dst has enough room for the = hash, + * so we just tell PSA that it can hold the appropriate amount of byte= s. */ + size_t dst_size =3D PSA_HASH_LENGTH(ctx->md_info->psa_alg); + size_t hmac_length =3D 0; + + ASSERT(psa_mac_sign_finish(&ctx->operation, dst, dst_size, &hmac_lengt= h) =3D=3D PSA_SUCCESS); + ASSERT(hmac_length =3D=3D dst_size); } -int -memcmp_constant_time(const void *a, const void *b, size_t size) -{ - /* mbed TLS has a no const time memcmp function that it exposes - * via its APIs like OpenSSL does with CRYPTO_memcmp - * Adapt the function that mbedtls itself uses in - * mbedtls_safer_memcmp as it considers that to be safe */ - volatile const unsigned char *A =3D (volatile const unsigned char *)a; - volatile const unsigned char *B =3D (volatile const unsigned char *)b; - volatile unsigned char diff =3D 0; - - for (size_t i =3D 0; i < size; i++) - { - unsigned char x =3D A[i], y =3D B[i]; - diff |=3D x ^ y; - } - - return diff; -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - /* * Generate the hash required by for the \c tls1_PRF function. * @@ -1004,8 +845,8 @@ * @param olen Length of the output buffer */ static void -tls1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *sec, size_t sec= _len, const uint8_t *seed, - size_t seed_len, uint8_t *out, size_t olen) +tls1_P_hash(const md_info_t *md_info, const uint8_t *sec, size_t sec_len, = const uint8_t *seed, + int seed_len, uint8_t *out, size_t olen) { struct gc_arena gc =3D gc_new(); uint8_t A1[MAX_HMAC_KEY_LENGTH]; @@ -1023,18 +864,13 @@ dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex(sec, sec_len= , 0, &gc)); dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex(seed, seed_= len, 0, &gc)); - unsigned int chunk =3D mbedtls_md_get_size(md_kt); - unsigned int A1_len =3D mbedtls_md_get_size(md_kt); + unsigned int chunk =3D (unsigned int)PSA_HASH_LENGTH(md_info->psa_alg); + unsigned int A1_len =3D (unsigned int)PSA_HASH_LENGTH(md_info->psa_alg= ); /* This is the only place where we init an HMAC with a key that is not * equal to its size, therefore we init the hmac ctx manually here */ - mbedtls_md_init(ctx); - ASSERT(0 =3D=3D mbedtls_md_setup(ctx, md_kt, 1)); - ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx, sec, sec_len)); - - mbedtls_md_init(ctx_tmp); - ASSERT(0 =3D=3D mbedtls_md_setup(ctx_tmp, md_kt, 1)); - ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx_tmp, sec, sec_len)); + hmac_ctx_init_with_arbitrary_key_length(ctx, sec, sec_len, md_info); + hmac_ctx_init_with_arbitrary_key_length(ctx_tmp, sec, sec_len, md_info= ); hmac_ctx_update(ctx, seed, seed_len); hmac_ctx_final(ctx, A1); @@ -1045,7 +881,7 @@ hmac_ctx_reset(ctx_tmp); hmac_ctx_update(ctx, A1, A1_len); hmac_ctx_update(ctx_tmp, A1, A1_len); - hmac_ctx_update(ctx, seed, seed_len); + hmac_ctx_update(ctx, seed, (int)seed_len); if (olen > chunk) { @@ -1094,9 +930,15 @@ ssl_tls1_PRF(const uint8_t *label, size_t label_len, const uint8_t *sec, s= ize_t slen, uint8_t *out1, size_t olen) { + const md_info_t *md5 =3D md_get("MD5"); + const md_info_t *sha1 =3D md_get("SHA1"); + + if (label_len > (size_t)INT_MAX) + { + return false; + } + struct gc_arena gc =3D gc_new(); - const md_kt_t *md5 =3D md_get("MD5"); - const md_kt_t *sha1 =3D md_get("SHA1"); uint8_t *out2 =3D (uint8_t *)gc_malloc(olen, false, &gc); @@ -1105,8 +947,8 @@ const uint8_t *S2 =3D &(sec[len]); len +=3D (slen & 1); /* add for odd, make longer */ - tls1_P_hash(md5, S1, len, label, label_len, out1, olen); - tls1_P_hash(sha1, S2, len, label, label_len, out2, olen); + tls1_P_hash(md5, S1, len, label, (int)label_len, out1, olen); + tls1_P_hash(sha1, S2, len, label, (int)label_len, out2, olen); for (size_t i =3D 0; i < olen; i++) { @@ -1121,8 +963,204 @@ return true; } -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic pop +void +crypto_init_lib(void) +{ +} + +void +crypto_uninit_lib(void) +{ +} + +void +crypto_clear_error(void) +{ +} + +bool +mbed_log_err(unsigned int flags, int errval, const char *prefix) +{ + if (0 !=3D errval) + { + char errstr[256]; + mbedtls_strerror(errval, errstr, sizeof(errstr)); + + if (NULL =3D=3D prefix) + { + prefix =3D "mbed TLS error"; + } + msg(flags, "%s: %s", prefix, errstr); + } + + return 0 =3D=3D errval; +} + +bool +mbed_log_func_line(unsigned int flags, int errval, const char *func, int l= ine) +{ + char prefix[256]; + + if (snprintf(prefix, sizeof(prefix), "%s:%d", func, line) >=3D sizeof(= prefix)) + { + return mbed_log_err(flags, errval, func); + } + + return mbed_log_err(flags, errval, prefix); +} + +int +memcmp_constant_time(const void *a, const void *b, size_t size) +{ + return mbedtls_ct_memcmp(a, b, size); +} + +void +show_available_ciphers(void) +{ + /* Mbed TLS 4 does not currently have a mechanism to discover available + * ciphers. We instead print out the ciphers from cipher_info_table. */ + +#ifndef ENABLE_SMALL + printf("The following ciphers and cipher modes are available for use\n" + "with " PACKAGE_NAME ". Each cipher shown below may be used as= a\n" + "parameter to the --data-ciphers (or --cipher) option. Using a= \n" + "GCM or CBC mode is recommended. In static key mode only CBC\n" + "mode is allowed.\n\n"); #endif -#endif /* ENABLE_CRYPTO_MBEDTLS */ + for (size_t i =3D 0; i < cipher_info_table_entries; i++) + { + const cipher_info_t *info =3D &cipher_info_table[i]; + const char *name =3D info->name; + if (!cipher_kt_insecure(name) && (cipher_kt_mode_aead(name) || cip= her_kt_mode_cbc(name))) + { + print_cipher(name); + } + } + + printf("\nThe following ciphers have a block size of less than 128 bit= s, \n" + "and are therefore deprecated. Do not use unless you have to.\= n\n"); + for (size_t i =3D 0; i < cipher_info_table_entries; i++) + { + const cipher_info_t *info =3D &cipher_info_table[i]; + const char *name =3D info->name; + if (cipher_kt_insecure(name) && (cipher_kt_mode_aead(name) || ciph= er_kt_mode_cbc(name))) + { + print_cipher(name); + } + } + printf("\n"); +} + +void +show_available_digests(void) +{ + /* Mbed TLS 4 does not currently have a mechanism to discover available + * message digests. We instead print out the digests from md_info_tabl= e. */ + +#ifndef ENABLE_SMALL + printf("The following message digests are available for use with\n" PA= CKAGE_NAME + ". A message digest is used in conjunction with\n" + "the HMAC function, to authenticate received packets.\n" + "You can specify a message digest as parameter to\n" + "the --auth option.\n\n"); +#endif + + for (size_t i =3D 0; i < md_info_table_entries; i++) + { + const md_info_t *info =3D &md_info_table[i]; + printf("%s %d bit default key\n", info->name, + (unsigned char)PSA_HASH_LENGTH(info->psa_alg) * 8); + } + printf("\n"); +} + +void +show_available_engines(void) +{ + printf("Sorry, mbed TLS hardware crypto engine functionality is not " + "available\n"); +} + +bool +crypto_pem_encode(const char *name, struct buffer *dst, const struct buffe= r *src, + struct gc_arena *gc) +{ + /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ + char header[1000 + 1] =3D { 0 }; + char footer[1000 + 1] =3D { 0 }; + + if (snprintf(header, sizeof(header), "-----BEGIN %s-----\n", name) >= =3D sizeof(header)) + { + return false; + } + if (snprintf(footer, sizeof(footer), "-----END %s-----\n", name) >=3D = sizeof(footer)) + { + return false; + } + + size_t out_len =3D 0; + if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL + !=3D mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src)= , NULL, 0, &out_len)) + { + return false; + } + + /* We set the size buf to out_len-1 to NOT include the 0 byte that + * mbedtls_pem_write_buffer in its length calculation */ + *dst =3D alloc_buf_gc(out_len, gc); + if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(= src), BPTR(dst), + BCAP(dst), &out_len)) + || !(out_len < INT_MAX && out_len > 1) + || !buf_inc_len(dst, (int)out_len - 1)) + { + CLEAR(*dst); + return false; + } + + return true; +} + +bool +crypto_pem_decode(const char *name, struct buffer *dst, const struct buffe= r *src) +{ + /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ + char header[1000 + 1] =3D { 0 }; + char footer[1000 + 1] =3D { 0 }; + + if (snprintf(header, sizeof(header), "-----BEGIN %s-----", name) >=3D = sizeof(header)) + { + return false; + } + if (snprintf(footer, sizeof(footer), "-----END %s-----", name) >=3D si= zeof(footer)) + { + return false; + } + + /* mbed TLS requires the src to be null-terminated */ + /* allocate a new buffer to avoid modifying the src buffer */ + struct gc_arena gc =3D gc_new(); + struct buffer input =3D alloc_buf_gc(BLEN(src) + 1, &gc); + buf_copy(&input, src); + buf_null_terminate(&input); + + size_t use_len =3D 0; + mbedtls_pem_context ctx =3D { 0 }; + bool ret =3D + mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPTR(&input)= , NULL, 0, &use_len)); + size_t buf_size =3D 0; + const unsigned char *buf =3D mbedtls_pem_get_buffer(&ctx, &buf_size); + if (ret && !buf_write(dst, buf, buf_size)) + { + ret =3D false; + msg(M_WARN, "PEM decode error: destination buffer too small"); + } + + mbedtls_pem_free(&ctx); + gc_free(&gc); + return ret; +} + +#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */ +#endif /* defined(ENABLE_CRYPTO_MBEDTLS) */ diff --git a/src/openvpn/crypto_mbedtls.h b/src/openvpn/crypto_mbedtls.h index 71514fc..dd491f3 100644 --- a/src/openvpn/crypto_mbedtls.h +++ b/src/openvpn/crypto_mbedtls.h @@ -1,3 +1,4 @@ + /* * OpenVPN -- An application to securely tunnel IP networks * over a single TCP/UDP port, with support for SSL/TLS-based @@ -6,7 +7,7 @@ * packet compression. * * Copyright (C) 2002-2025 OpenVPN Inc - * Copyright (C) 2010-2021 Sentyron B.V. + * Copyright (C) 2010-2025 Sentyron B.V. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 @@ -23,85 +24,98 @@ /** * @file - * Data Channel Cryptography mbed TLS-specific backend interface + * Data Channel Cryptography backend interface using the TF-PSA-Crypto lib= rary + * part of Mbed TLS 4. */ -#ifndef CRYPTO_MBEDTLS_H_ -#define CRYPTO_MBEDTLS_H_ +#ifndef CRYPTO_MBEDTLS4_H_ +#define CRYPTO_MBEDTLS4_H_ -#include -#include -#include -#include +#include -/** Generic message digest key type %context. */ -typedef mbedtls_md_info_t md_kt_t; - -/** Generic cipher %context. */ -typedef mbedtls_cipher_context_t cipher_ctx_t; - -/** Generic message digest %context. */ -typedef mbedtls_md_context_t md_ctx_t; - -/** Generic HMAC %context. */ -typedef mbedtls_md_context_t hmac_ctx_t; - -/* Use a dummy type for the provider */ -typedef void provider_t; +#include "integer.h" /** Maximum length of an IV */ -#define OPENVPN_MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH +#define OPENVPN_MAX_IV_LENGTH 16 /** Cipher is in CBC mode */ -#define OPENVPN_MODE_CBC MBEDTLS_MODE_CBC +#define OPENVPN_MODE_CBC PSA_ALG_CBC_PKCS7 /** Cipher is in OFB mode */ -#define OPENVPN_MODE_OFB MBEDTLS_MODE_OFB +#define OPENVPN_MODE_OFB PSA_ALG_OFB /** Cipher is in CFB mode */ -#define OPENVPN_MODE_CFB MBEDTLS_MODE_CFB +#define OPENVPN_MODE_CFB PSA_ALG_CFB /** Cipher is in GCM mode */ -#define OPENVPN_MODE_GCM MBEDTLS_MODE_GCM +#define OPENVPN_MODE_GCM PSA_ALG_GCM -typedef mbedtls_operation_t crypto_operation_t; +typedef int crypto_operation_t; /** Cipher should encrypt */ -#define OPENVPN_OP_ENCRYPT MBEDTLS_ENCRYPT +#define OPENVPN_OP_ENCRYPT 0 /** Cipher should decrypt */ -#define OPENVPN_OP_DECRYPT MBEDTLS_DECRYPT +#define OPENVPN_OP_DECRYPT 1 #define MD4_DIGEST_LENGTH 16 #define MD5_DIGEST_LENGTH 16 #define SHA_DIGEST_LENGTH 20 #define SHA256_DIGEST_LENGTH 32 -/** - * Returns a singleton instance of the mbed TLS random number generator. - * - * For PolarSSL/mbed TLS 1.1+, this is the CTR_DRBG random number generato= r. If it - * hasn't been initialised yet, the RNG will be initialised using the defa= ult - * entropy sources. Aside from the default platform entropy sources, an - * additional entropy source, the HAVEGE random number generator will also= be - * added. During initialisation, a personalisation string will be added ba= sed - * on the time, the PID, and a pointer to the random context. - */ -mbedtls_ctr_drbg_context *rand_ctx_get(void); +typedef void provider_t; -#ifdef ENABLE_PREDICTION_RESISTANCE -/** - * Enable prediction resistance on the random number generator. - */ -void rand_ctx_enable_prediction_resistance(void); +typedef struct cipher_info +{ + const char *name; + psa_key_type_t psa_key_type; + psa_algorithm_t psa_alg; + int key_bytes; + int iv_bytes; + int block_size; +} cipher_info_t; -#endif +typedef union psa_cipher_or_aead_operation +{ + psa_cipher_operation_t cipher; + psa_aead_operation_t aead; +} cipher_operation_t; + +typedef struct cipher_ctx +{ + mbedtls_svc_key_id_t key; + psa_key_attributes_t key_attributes; + const cipher_info_t *cipher_info; + bool aead_finished; + cipher_operation_t operation; + uint8_t tag[16]; +} cipher_ctx_t; + +typedef struct md_info +{ + const char *name; + psa_algorithm_t psa_alg; +} md_info_t; + +typedef struct md_ctx +{ + const md_info_t *md_info; + psa_hash_operation_t operation; +} md_ctx_t; + +typedef struct hmac_ctx +{ + mbedtls_svc_key_id_t key; + psa_key_attributes_t key_attributes; + const md_info_t *md_info; + psa_mac_operation_t operation; +} hmac_ctx_t; /** * Log the supplied mbed TLS error, prefixed by supplied prefix. * * @param flags Flags to indicate error type and priority. - * @param errval mbed TLS error code to convert to error message. + * @param errval mbed TLS error code. * @param prefix Prefix to mbed TLS error message. * * @returns true if no errors are detected, false otherwise. @@ -112,7 +126,7 @@ * Log the supplied mbed TLS error, prefixed by function name and line num= ber. * * @param flags Flags to indicate error type and priority. - * @param errval mbed TLS error code to convert to error message. + * @param errval mbed TLS error code. * @param func Function name where error was reported. * @param line Line number where error was reported. * @@ -142,7 +156,8 @@ * @param errval mbed TLS error code to convert to error message. * * @returns true if no errors are detected, false otherwise. + * TODO: The log function has been removed, do something about it? */ #define mbed_ok(errval) mbed_log_func_line_lite(D_CRYPT_ERRORS, errval, __= func__, __LINE__) -#endif /* CRYPTO_MBEDTLS_H_ */ +#endif /* CRYPTO_MBEDTLS4_H_ */ diff --git a/src/openvpn/crypto_mbedtls_legacy.c b/src/openvpn/crypto_mbedt= ls_legacy.c new file mode 100644 index 0000000..c847038 --- /dev/null +++ b/src/openvpn/crypto_mbedtls_legacy.c @@ -0,0 +1,1133 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single TCP/UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2002-2025 OpenVPN Inc + * Copyright (C) 2010-2021 Sentyron B.V. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, see . + */ + +/** + * @file + * Data Channel Cryptography mbed TLS-specific backend interface, + * for mbed TLS 3.X versions. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "syshead.h" + +#if defined(ENABLE_CRYPTO_MBEDTLS) +#include + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 + +#include "errlevel.h" +#include "basic.h" +#include "buffer.h" +#include "crypto.h" +#include "integer.h" +#include "crypto_backend.h" +#include "otime.h" +#include "misc.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + + +/* + * + * Hardware engine support. Allows loading/unloading of engines. + * + */ + +void +crypto_init_lib_engine(const char *engine_name) +{ + msg(M_WARN, "Note: mbed TLS hardware crypto engine functionality is no= t " + "available"); +} + +provider_t * +crypto_load_provider(const char *provider) +{ + if (provider) + { + msg(M_WARN, "Note: mbed TLS provider functionality is not availabl= e"); + } + return NULL; +} + +void +crypto_unload_provider(const char *provname, provider_t *provider) +{ +} + +/* + * + * Functions related to the core crypto library + * + */ + +void +crypto_init_lib(void) +{ +} + +void +crypto_uninit_lib(void) +{ +} + +void +crypto_clear_error(void) +{ +} + +bool +mbed_log_err(unsigned int flags, int errval, const char *prefix) +{ + if (0 !=3D errval) + { + char errstr[256]; + mbedtls_strerror(errval, errstr, sizeof(errstr)); + + if (NULL =3D=3D prefix) + { + prefix =3D "mbed TLS error"; + } + msg(flags, "%s: %s", prefix, errstr); + } + + return 0 =3D=3D errval; +} + +bool +mbed_log_func_line(unsigned int flags, int errval, const char *func, int l= ine) +{ + char prefix[256]; + + if (snprintf(prefix, sizeof(prefix), "%s:%d", func, line) >=3D sizeof(= prefix)) + { + return mbed_log_err(flags, errval, func); + } + + return mbed_log_err(flags, errval, prefix); +} + + +#ifdef DMALLOC +void +crypto_init_dmalloc(void) +{ + msg(M_ERR, "Error: dmalloc support is not available for mbed TLS."); +} +#endif /* DMALLOC */ + +const cipher_name_pair cipher_name_translation_table[] =3D { + { "BF-CBC", "BLOWFISH-CBC" }, + { "BF-CFB", "BLOWFISH-CFB64" }, + { "CAMELLIA-128-CFB", "CAMELLIA-128-CFB128" }, + { "CAMELLIA-192-CFB", "CAMELLIA-192-CFB128" }, + { "CAMELLIA-256-CFB", "CAMELLIA-256-CFB128" } +}; +const size_t cipher_name_translation_table_count =3D + sizeof(cipher_name_translation_table) / sizeof(*cipher_name_translatio= n_table); + +void +show_available_ciphers(void) +{ + const int *ciphers =3D mbedtls_cipher_list(); + +#ifndef ENABLE_SMALL + printf("The following ciphers and cipher modes are available for use\n" + "with " PACKAGE_NAME ". Each cipher shown below may be used as= a\n" + "parameter to the --data-ciphers (or --cipher) option. Using a= \n" + "GCM or CBC mode is recommended. In static key mode only CBC\n" + "mode is allowed.\n\n"); +#endif + + while (*ciphers !=3D 0) + { + const mbedtls_cipher_info_t *info =3D mbedtls_cipher_info_from_typ= e(*ciphers); + const char *name =3D mbedtls_cipher_info_get_name(info); + if (info && name && !cipher_kt_insecure(name) + && (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(name))) + { + print_cipher(name); + } + ciphers++; + } + + printf("\nThe following ciphers have a block size of less than 128 bit= s, \n" + "and are therefore deprecated. Do not use unless you have to.\= n\n"); + ciphers =3D mbedtls_cipher_list(); + while (*ciphers !=3D 0) + { + const mbedtls_cipher_info_t *info =3D mbedtls_cipher_info_from_typ= e(*ciphers); + const char *name =3D mbedtls_cipher_info_get_name(info); + if (info && name && cipher_kt_insecure(name) + && (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(name))) + { + print_cipher(name); + } + ciphers++; + } + printf("\n"); +} + +void +show_available_digests(void) +{ + const int *digests =3D mbedtls_md_list(); + +#ifndef ENABLE_SMALL + printf("The following message digests are available for use with\n" PA= CKAGE_NAME + ". A message digest is used in conjunction with\n" + "the HMAC function, to authenticate received packets.\n" + "You can specify a message digest as parameter to\n" + "the --auth option.\n\n"); +#endif + + while (*digests !=3D 0) + { + const mbedtls_md_info_t *info =3D mbedtls_md_info_from_type(*diges= ts); + + if (info) + { + printf("%s %d bit default key\n", mbedtls_md_get_name(info), + mbedtls_md_get_size(info) * 8); + } + digests++; + } + printf("\n"); +} + +void +show_available_engines(void) +{ + printf("Sorry, mbed TLS hardware crypto engine functionality is not " + "available\n"); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + +bool +crypto_pem_encode(const char *name, struct buffer *dst, const struct buffe= r *src, + struct gc_arena *gc) +{ + /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ + char header[1000 + 1] =3D { 0 }; + char footer[1000 + 1] =3D { 0 }; + + if (snprintf(header, sizeof(header), "-----BEGIN %s-----\n", name) >= =3D sizeof(header)) + { + return false; + } + if (snprintf(footer, sizeof(footer), "-----END %s-----\n", name) >=3D = sizeof(footer)) + { + return false; + } + + size_t out_len =3D 0; + if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL + !=3D mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src)= , NULL, 0, &out_len)) + { + return false; + } + + /* We set the size buf to out_len-1 to NOT include the 0 byte that + * mbedtls_pem_write_buffer in its length calculation */ + *dst =3D alloc_buf_gc(out_len, gc); + if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(= src), BPTR(dst), + BCAP(dst), &out_len)) + || !buf_inc_len(dst, out_len - 1)) + { + CLEAR(*dst); + return false; + } + + return true; +} + +bool +crypto_pem_decode(const char *name, struct buffer *dst, const struct buffe= r *src) +{ + /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */ + char header[1000 + 1] =3D { 0 }; + char footer[1000 + 1] =3D { 0 }; + + if (snprintf(header, sizeof(header), "-----BEGIN %s-----", name) >=3D = sizeof(header)) + { + return false; + } + if (snprintf(footer, sizeof(footer), "-----END %s-----", name) >=3D si= zeof(footer)) + { + return false; + } + + /* mbed TLS requires the src to be null-terminated */ + /* allocate a new buffer to avoid modifying the src buffer */ + struct gc_arena gc =3D gc_new(); + struct buffer input =3D alloc_buf_gc(BLEN(src) + 1, &gc); + buf_copy(&input, src); + buf_null_terminate(&input); + + size_t use_len =3D 0; + mbedtls_pem_context ctx =3D { 0 }; + bool ret =3D + mbed_ok(mbedtls_pem_read_buffer(&ctx, header, footer, BPTR(&input)= , NULL, 0, &use_len)); + size_t buf_size =3D 0; + const unsigned char *buf =3D mbedtls_pem_get_buffer(&ctx, &buf_size); + if (ret && !buf_write(dst, buf, buf_size)) + { + ret =3D false; + msg(M_WARN, "PEM decode error: destination buffer too small"); + } + + mbedtls_pem_free(&ctx); + gc_free(&gc); + return ret; +} + +/* + * + * Random number functions, used in cases where we want + * reasonably strong cryptographic random number generation + * without depleting our entropy pool. Used for random + * IV values and a number of other miscellaneous tasks. + * + */ + +/* + * Initialise the given ctr_drbg context, using a personalisation string a= nd an + * entropy gathering function. + */ +mbedtls_ctr_drbg_context * +rand_ctx_get(void) +{ + static mbedtls_entropy_context ec =3D { 0 }; + static mbedtls_ctr_drbg_context cd_ctx =3D { 0 }; + static bool rand_initialised =3D false; + + if (!rand_initialised) + { + struct gc_arena gc =3D gc_new(); + struct buffer pers_string =3D alloc_buf_gc(100, &gc); + + /* + * Personalisation string, should be as unique as possible (see NI= ST + * 800-90 section 8.7.1). We have very little information at this = stage. + * Include Program Name, memory address of the context and PID. + */ + buf_printf(&pers_string, "OpenVPN %0u %p %s", platform_getpid(), &= cd_ctx, + time_string(0, 0, 0, &gc)); + + /* Initialise mbed TLS RNG, and built-in entropy sources */ + mbedtls_entropy_init(&ec); + + mbedtls_ctr_drbg_init(&cd_ctx); + if (!mbed_ok(mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, = &ec, BPTR(&pers_string), + BLEN(&pers_string)))) + { + msg(M_FATAL, "Failed to initialize random generator"); + } + + gc_free(&gc); + rand_initialised =3D true; + } + + return &cd_ctx; +} + +#ifdef ENABLE_PREDICTION_RESISTANCE +void +rand_ctx_enable_prediction_resistance(void) +{ + mbedtls_ctr_drbg_context *cd_ctx =3D rand_ctx_get(); + + mbedtls_ctr_drbg_set_prediction_resistance(cd_ctx, 1); +} +#endif /* ENABLE_PREDICTION_RESISTANCE */ + +int +rand_bytes(uint8_t *output, int len) +{ + mbedtls_ctr_drbg_context *rng_ctx =3D rand_ctx_get(); + + while (len > 0) + { + const size_t blen =3D min_int(len, MBEDTLS_CTR_DRBG_MAX_REQUEST); + if (0 !=3D mbedtls_ctr_drbg_random(rng_ctx, output, blen)) + { + return 0; + } + + output +=3D blen; + len -=3D blen; + } + + return 1; +} + +/* + * + * Generic cipher key type functions + * + */ +static const mbedtls_cipher_info_t * +cipher_get(const char *ciphername) +{ + ASSERT(ciphername); + + const mbedtls_cipher_info_t *cipher =3D NULL; + + ciphername =3D translate_cipher_name_from_openvpn(ciphername); + cipher =3D mbedtls_cipher_info_from_string(ciphername); + return cipher; +} + +bool +cipher_valid_reason(const char *ciphername, const char **reason) +{ + ASSERT(reason); + + const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); + + if (NULL =3D=3D cipher) + { + msg(D_LOW, "Cipher algorithm '%s' not found", ciphername); + *reason =3D "disabled because unknown"; + return false; + } + + const size_t key_bytelen =3D mbedtls_cipher_info_get_key_bitlen(cipher= ) / 8; + if (key_bytelen > MAX_CIPHER_KEY_LENGTH) + { + msg(D_LOW, + "Cipher algorithm '%s' uses a default key size (%zu bytes) " + "which is larger than " PACKAGE_NAME "'s current maximum key s= ize " + "(%d bytes)", + ciphername, key_bytelen, MAX_CIPHER_KEY_LENGTH); + *reason =3D "disabled due to key size too large"; + return false; + } + + *reason =3D NULL; + return true; +} + +const char * +cipher_kt_name(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); + if (NULL =3D=3D cipher_kt) + { + return "[null-cipher]"; + } + + return translate_cipher_name_to_openvpn(mbedtls_cipher_info_get_name(c= ipher_kt)); +} + +int +cipher_kt_key_size(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); + + if (NULL =3D=3D cipher_kt) + { + return 0; + } + + return (int)mbedtls_cipher_info_get_key_bitlen(cipher_kt) / 8; +} + +int +cipher_kt_iv_size(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); + + if (NULL =3D=3D cipher_kt) + { + return 0; + } + return (int)mbedtls_cipher_info_get_iv_size(cipher_kt); +} + +int +cipher_kt_block_size(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); + if (NULL =3D=3D cipher_kt) + { + return 0; + } + return (int)mbedtls_cipher_info_get_block_size(cipher_kt); +} + +int +cipher_kt_tag_size(const char *ciphername) +{ + if (cipher_kt_mode_aead(ciphername)) + { + return OPENVPN_AEAD_TAG_LENGTH; + } + return 0; +} + +bool +cipher_kt_insecure(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername); + if (!cipher_kt) + { + return true; + } + + return !(cipher_kt_block_size(ciphername) >=3D 128 / 8 +#ifdef MBEDTLS_CHACHAPOLY_C + || mbedtls_cipher_info_get_type(cipher_kt) =3D=3D MBEDTLS_CIP= HER_CHACHA20_POLY1305 +#endif + ); +} + +static mbedtls_cipher_mode_t +cipher_kt_mode(const mbedtls_cipher_info_t *cipher_kt) +{ + ASSERT(NULL !=3D cipher_kt); + return mbedtls_cipher_info_get_mode(cipher_kt); +} + +bool +cipher_kt_mode_cbc(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); + return cipher && cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CBC; +} + +bool +cipher_kt_mode_ofb_cfb(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); + return cipher + && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB + || cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CFB); +} + +bool +cipher_kt_mode_aead(const char *ciphername) +{ + const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername); + return cipher + && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_GCM +#ifdef MBEDTLS_CHACHAPOLY_C + || cipher_kt_mode(cipher) =3D=3D MBEDTLS_MODE_CHACHAPOLY +#endif + ); +} + + +/* + * + * Generic cipher context functions + * + */ + +mbedtls_cipher_context_t * +cipher_ctx_new(void) +{ + mbedtls_cipher_context_t *ctx; + ALLOC_OBJ(ctx, mbedtls_cipher_context_t); + return ctx; +} + +void +cipher_ctx_free(mbedtls_cipher_context_t *ctx) +{ + mbedtls_cipher_free(ctx); + free(ctx); +} + +void +cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, const c= har *ciphername, + crypto_operation_t enc) +{ + ASSERT(NULL !=3D ciphername && NULL !=3D ctx); + CLEAR(*ctx); + + const mbedtls_cipher_info_t *kt =3D cipher_get(ciphername); + ASSERT(kt); + size_t key_bitlen =3D mbedtls_cipher_info_get_key_bitlen(kt); + + if (!mbed_ok(mbedtls_cipher_setup(ctx, kt))) + { + msg(M_FATAL, "mbed TLS cipher context init #1"); + } + + if (!mbed_ok(mbedtls_cipher_setkey(ctx, key, (int)key_bitlen, enc))) + { + msg(M_FATAL, "mbed TLS cipher set key"); + } + + if (mbedtls_cipher_info_get_mode(kt) =3D=3D MBEDTLS_MODE_CBC) + { + if (!mbed_ok(mbedtls_cipher_set_padding_mode(ctx, MBEDTLS_PADDING_= PKCS7))) + { + msg(M_FATAL, "mbed TLS cipher set padding mode"); + } + } + + /* make sure we used a big enough key */ + ASSERT(mbedtls_cipher_get_key_bitlen(ctx) <=3D key_bitlen); +} + +int +cipher_ctx_iv_length(const mbedtls_cipher_context_t *ctx) +{ + return mbedtls_cipher_get_iv_size(ctx); +} + +int +cipher_ctx_get_tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len) +{ + if (tag_len > SIZE_MAX) + { + return 0; + } + + if (!mbed_ok(mbedtls_cipher_write_tag(ctx, (unsigned char *)tag, tag_l= en))) + { + return 0; + } + + return 1; +} + +int +cipher_ctx_block_size(const mbedtls_cipher_context_t *ctx) +{ + return (int)mbedtls_cipher_get_block_size(ctx); +} + +int +cipher_ctx_mode(const mbedtls_cipher_context_t *ctx) +{ + ASSERT(NULL !=3D ctx); + + return mbedtls_cipher_get_cipher_mode(ctx); +} + +bool +cipher_ctx_mode_cbc(const cipher_ctx_t *ctx) +{ + return ctx && cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CBC; +} + + +bool +cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx) +{ + return ctx + && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_OFB + || cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CFB); +} + +bool +cipher_ctx_mode_aead(const cipher_ctx_t *ctx) +{ + return ctx + && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_GCM +#ifdef MBEDTLS_CHACHAPOLY_C + || cipher_ctx_mode(ctx) =3D=3D MBEDTLS_MODE_CHACHAPOLY +#endif + ); +} + +int +cipher_ctx_reset(mbedtls_cipher_context_t *ctx, const uint8_t *iv_buf) +{ + if (!mbed_ok(mbedtls_cipher_reset(ctx))) + { + return 0; + } + + if (!mbed_ok(mbedtls_cipher_set_iv(ctx, iv_buf, (size_t)mbedtls_cipher= _get_iv_size(ctx)))) + { + return 0; + } + + return 1; +} + +int +cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len) +{ + if (src_len > SIZE_MAX) + { + return 0; + } + + if (!mbed_ok(mbedtls_cipher_update_ad(ctx, src, src_len))) + { + return 0; + } + + return 1; +} + +int +cipher_ctx_update(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_le= n, uint8_t *src, + int src_len) +{ + size_t s_dst_len =3D *dst_len; + + if (!mbed_ok(mbedtls_cipher_update(ctx, src, (size_t)src_len, dst, &s_= dst_len))) + { + return 0; + } + + *dst_len =3D s_dst_len; + + return 1; +} + +int +cipher_ctx_final(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_len) +{ + size_t s_dst_len =3D *dst_len; + + if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &s_dst_len))) + { + return 0; + } + + *dst_len =3D s_dst_len; + + return 1; +} + +int +cipher_ctx_final_check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst, in= t *dst_len, uint8_t *tag, + size_t tag_len) +{ + size_t olen =3D 0; + + if (MBEDTLS_DECRYPT !=3D mbedtls_cipher_get_operation(ctx)) + { + return 0; + } + + if (tag_len > SIZE_MAX) + { + return 0; + } + + if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &olen))) + { + msg(D_CRYPT_ERRORS, "%s: cipher_ctx_final() failed", __func__); + return 0; + } + + if (olen > INT_MAX) + { + return 0; + } + *dst_len =3D olen; + + if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (const unsigned char *)tag,= tag_len))) + { + return 0; + } + + return 1; +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +/* + * + * Generic message digest information functions + * + */ + + +static const mbedtls_md_info_t * +md_get(const char *digest) +{ + const mbedtls_md_info_t *md =3D NULL; + ASSERT(digest); + + md =3D mbedtls_md_info_from_string(digest); + if (!md) + { + msg(M_FATAL, "Message hash algorithm '%s' not found", digest); + } + if (mbedtls_md_get_size(md) > MAX_HMAC_KEY_LENGTH) + { + msg(M_FATAL, + "Message hash algorithm '%s' uses a default hash size (%d byte= s) which is larger than " PACKAGE_NAME + "'s current maximum hash size (%d bytes)", + digest, mbedtls_md_get_size(md), MAX_HMAC_KEY_LENGTH); + } + return md; +} + +bool +md_valid(const char *digest) +{ + const mbedtls_md_info_t *md =3D mbedtls_md_info_from_string(digest); + return md !=3D NULL; +} + +const char * +md_kt_name(const char *mdname) +{ + if (!strcmp("none", mdname)) + { + return "[null-digest]"; + } + const mbedtls_md_info_t *kt =3D md_get(mdname); + return mbedtls_md_get_name(kt); +} + +unsigned char +md_kt_size(const char *mdname) +{ + if (!strcmp("none", mdname)) + { + return 0; + } + const mbedtls_md_info_t *kt =3D md_get(mdname); + return mbedtls_md_get_size(kt); +} + +/* + * + * Generic message digest functions + * + */ + +int +md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst) +{ + const mbedtls_md_info_t *kt =3D md_get(mdname); + return 0 =3D=3D mbedtls_md(kt, src, src_len, dst); +} + +mbedtls_md_context_t * +md_ctx_new(void) +{ + mbedtls_md_context_t *ctx; + ALLOC_OBJ_CLEAR(ctx, mbedtls_md_context_t); + return ctx; +} + +void +md_ctx_free(mbedtls_md_context_t *ctx) +{ + free(ctx); +} + +void +md_ctx_init(mbedtls_md_context_t *ctx, const char *mdname) +{ + const mbedtls_md_info_t *kt =3D md_get(mdname); + ASSERT(NULL !=3D ctx && NULL !=3D kt); + + mbedtls_md_init(ctx); + ASSERT(0 =3D=3D mbedtls_md_setup(ctx, kt, 0)); + ASSERT(0 =3D=3D mbedtls_md_starts(ctx)); +} + +void +md_ctx_cleanup(mbedtls_md_context_t *ctx) +{ + mbedtls_md_free(ctx); +} + +int +md_ctx_size(const mbedtls_md_context_t *ctx) +{ + if (NULL =3D=3D ctx) + { + return 0; + } + return (int)mbedtls_md_get_size(mbedtls_md_info_from_ctx(ctx)); +} + +void +md_ctx_update(mbedtls_md_context_t *ctx, const uint8_t *src, size_t src_le= n) +{ + ASSERT(0 =3D=3D mbedtls_md_update(ctx, src, src_len)); +} + +void +md_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst) +{ + ASSERT(0 =3D=3D mbedtls_md_finish(ctx, dst)); + mbedtls_md_free(ctx); +} + + +/* + * + * Generic HMAC functions + * + */ + + +/* + * TODO: re-enable dmsg for crypto debug + */ + +mbedtls_md_context_t * +hmac_ctx_new(void) +{ + mbedtls_md_context_t *ctx; + ALLOC_OBJ(ctx, mbedtls_md_context_t); + return ctx; +} + +void +hmac_ctx_free(mbedtls_md_context_t *ctx) +{ + free(ctx); +} + +void +hmac_ctx_init(mbedtls_md_context_t *ctx, const uint8_t *key, const char *m= dname) +{ + const mbedtls_md_info_t *kt =3D md_get(mdname); + ASSERT(NULL !=3D kt && NULL !=3D ctx); + + mbedtls_md_init(ctx); + int key_len =3D mbedtls_md_get_size(kt); + ASSERT(0 =3D=3D mbedtls_md_setup(ctx, kt, 1)); + ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx, key, key_len)); + + /* make sure we used a big enough key */ + ASSERT(mbedtls_md_get_size(kt) <=3D key_len); +} + +void +hmac_ctx_cleanup(mbedtls_md_context_t *ctx) +{ + mbedtls_md_free(ctx); +} + +int +hmac_ctx_size(mbedtls_md_context_t *ctx) +{ + if (NULL =3D=3D ctx) + { + return 0; + } + return mbedtls_md_get_size(mbedtls_md_info_from_ctx(ctx)); +} + +void +hmac_ctx_reset(mbedtls_md_context_t *ctx) +{ + ASSERT(0 =3D=3D mbedtls_md_hmac_reset(ctx)); +} + +void +hmac_ctx_update(mbedtls_md_context_t *ctx, const uint8_t *src, int src_len) +{ + ASSERT(0 =3D=3D mbedtls_md_hmac_update(ctx, src, src_len)); +} + +void +hmac_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst) +{ + ASSERT(0 =3D=3D mbedtls_md_hmac_finish(ctx, dst)); +} + +int +memcmp_constant_time(const void *a, const void *b, size_t size) +{ + /* mbed TLS has a no const time memcmp function that it exposes + * via its APIs like OpenSSL does with CRYPTO_memcmp + * Adapt the function that mbedtls itself uses in + * mbedtls_safer_memcmp as it considers that to be safe */ + volatile const unsigned char *A =3D (volatile const unsigned char *)a; + volatile const unsigned char *B =3D (volatile const unsigned char *)b; + volatile unsigned char diff =3D 0; + + for (size_t i =3D 0; i < size; i++) + { + unsigned char x =3D A[i], y =3D B[i]; + diff |=3D x ^ y; + } + + return diff; +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + +/* + * Generate the hash required by for the \c tls1_PRF function. + * + * @param md_kt Message digest to use + * @param sec Secret to base the hash on + * @param sec_len Length of the secret + * @param seed Seed to hash + * @param seed_len Length of the seed + * @param out Output buffer + * @param olen Length of the output buffer + */ +static void +tls1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *sec, size_t sec= _len, const uint8_t *seed, + size_t seed_len, uint8_t *out, size_t olen) +{ + struct gc_arena gc =3D gc_new(); + uint8_t A1[MAX_HMAC_KEY_LENGTH]; + +#ifdef ENABLE_DEBUG + /* used by the D_SHOW_KEY_SOURCE, guarded with ENABLE_DEBUG to avoid u= nused + * variables warnings if compiled with --enable-small */ + const size_t olen_orig =3D olen; + const uint8_t *out_orig =3D out; +#endif + + hmac_ctx_t *ctx =3D hmac_ctx_new(); + hmac_ctx_t *ctx_tmp =3D hmac_ctx_new(); + + dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex(sec, sec_len= , 0, &gc)); + dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex(seed, seed_= len, 0, &gc)); + + unsigned int chunk =3D mbedtls_md_get_size(md_kt); + unsigned int A1_len =3D mbedtls_md_get_size(md_kt); + + /* This is the only place where we init an HMAC with a key that is not + * equal to its size, therefore we init the hmac ctx manually here */ + mbedtls_md_init(ctx); + ASSERT(0 =3D=3D mbedtls_md_setup(ctx, md_kt, 1)); + ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx, sec, sec_len)); + + mbedtls_md_init(ctx_tmp); + ASSERT(0 =3D=3D mbedtls_md_setup(ctx_tmp, md_kt, 1)); + ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx_tmp, sec, sec_len)); + + hmac_ctx_update(ctx, seed, seed_len); + hmac_ctx_final(ctx, A1); + + for (;;) + { + hmac_ctx_reset(ctx); + hmac_ctx_reset(ctx_tmp); + hmac_ctx_update(ctx, A1, A1_len); + hmac_ctx_update(ctx_tmp, A1, A1_len); + hmac_ctx_update(ctx, seed, seed_len); + + if (olen > chunk) + { + hmac_ctx_final(ctx, out); + out +=3D chunk; + olen -=3D chunk; + hmac_ctx_final(ctx_tmp, A1); /* calc the next A1 value */ + } + else /* last one */ + { + hmac_ctx_final(ctx, A1); + memcpy(out, A1, olen); + break; + } + } + hmac_ctx_cleanup(ctx); + hmac_ctx_free(ctx); + hmac_ctx_cleanup(ctx_tmp); + hmac_ctx_free(ctx_tmp); + secure_memzero(A1, sizeof(A1)); + + dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex(out_orig, ol= en_orig, 0, &gc)); + gc_free(&gc); +} + +/* + * Use the TLS PRF function for generating data channel keys. + * This code is based on the OpenSSL library. + * + * TLS generates keys as such: + * + * master_secret[48] =3D PRF(pre_master_secret[48], "master secret", + * ClientHello.random[32] + ServerHello.random[32]) + * + * key_block[] =3D PRF(SecurityParameters.master_secret[48], + * "key expansion", + * SecurityParameters.server_random[32] + + * SecurityParameters.client_random[32]); + * + * Notes: + * + * (1) key_block contains a full set of 4 keys. + * (2) The pre-master secret is generated by the client. + */ +bool +ssl_tls1_PRF(const uint8_t *label, size_t label_len, const uint8_t *sec, s= ize_t slen, uint8_t *out1, + size_t olen) +{ + struct gc_arena gc =3D gc_new(); + const md_kt_t *md5 =3D md_get("MD5"); + const md_kt_t *sha1 =3D md_get("SHA1"); + + uint8_t *out2 =3D (uint8_t *)gc_malloc(olen, false, &gc); + + size_t len =3D slen / 2; + const uint8_t *S1 =3D sec; + const uint8_t *S2 =3D &(sec[len]); + len +=3D (slen & 1); /* add for odd, make longer */ + + tls1_P_hash(md5, S1, len, label, label_len, out1, olen); + tls1_P_hash(sha1, S2, len, label, label_len, out2, olen); + + for (size_t i =3D 0; i < olen; i++) + { + out1[i] ^=3D out2[i]; + } + + secure_memzero(out2, olen); + + dmsg(D_SHOW_KEY_SOURCE, "tls1_PRF out[%zu]: %s", olen, format_hex(out1= , olen, 0, &gc)); + + gc_free(&gc); + return true; +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif /* MBEDTLS_VERSION_NUMBER < 0x040000 */ +#endif /* ENABLE_CRYPTO_MBEDTLS */ diff --git a/src/openvpn/crypto_mbedtls_legacy.h b/src/openvpn/crypto_mbedt= ls_legacy.h new file mode 100644 index 0000000..71514fc --- /dev/null +++ b/src/openvpn/crypto_mbedtls_legacy.h @@ -0,0 +1,148 @@ +/* + * OpenVPN -- An application to securely tunnel IP networks + * over a single TCP/UDP port, with support for SSL/TLS-based + * session authentication and key exchange, + * packet encryption, packet authentication, and + * packet compression. + * + * Copyright (C) 2002-2025 OpenVPN Inc + * Copyright (C) 2010-2021 Sentyron B.V. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, see . + */ + +/** + * @file + * Data Channel Cryptography mbed TLS-specific backend interface + */ + +#ifndef CRYPTO_MBEDTLS_H_ +#define CRYPTO_MBEDTLS_H_ + +#include +#include +#include +#include + +/** Generic message digest key type %context. */ +typedef mbedtls_md_info_t md_kt_t; + +/** Generic cipher %context. */ +typedef mbedtls_cipher_context_t cipher_ctx_t; + +/** Generic message digest %context. */ +typedef mbedtls_md_context_t md_ctx_t; + +/** Generic HMAC %context. */ +typedef mbedtls_md_context_t hmac_ctx_t; + +/* Use a dummy type for the provider */ +typedef void provider_t; + +/** Maximum length of an IV */ +#define OPENVPN_MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH + +/** Cipher is in CBC mode */ +#define OPENVPN_MODE_CBC MBEDTLS_MODE_CBC + +/** Cipher is in OFB mode */ +#define OPENVPN_MODE_OFB MBEDTLS_MODE_OFB + +/** Cipher is in CFB mode */ +#define OPENVPN_MODE_CFB MBEDTLS_MODE_CFB + +/** Cipher is in GCM mode */ +#define OPENVPN_MODE_GCM MBEDTLS_MODE_GCM + +typedef mbedtls_operation_t crypto_operation_t; + +/** Cipher should encrypt */ +#define OPENVPN_OP_ENCRYPT MBEDTLS_ENCRYPT + +/** Cipher should decrypt */ +#define OPENVPN_OP_DECRYPT MBEDTLS_DECRYPT + +#define MD4_DIGEST_LENGTH 16 +#define MD5_DIGEST_LENGTH 16 +#define SHA_DIGEST_LENGTH 20 +#define SHA256_DIGEST_LENGTH 32 + +/** + * Returns a singleton instance of the mbed TLS random number generator. + * + * For PolarSSL/mbed TLS 1.1+, this is the CTR_DRBG random number generato= r. If it + * hasn't been initialised yet, the RNG will be initialised using the defa= ult + * entropy sources. Aside from the default platform entropy sources, an + * additional entropy source, the HAVEGE random number generator will also= be + * added. During initialisation, a personalisation string will be added ba= sed + * on the time, the PID, and a pointer to the random context. + */ +mbedtls_ctr_drbg_context *rand_ctx_get(void); + +#ifdef ENABLE_PREDICTION_RESISTANCE +/** + * Enable prediction resistance on the random number generator. + */ +void rand_ctx_enable_prediction_resistance(void); + +#endif + +/** + * Log the supplied mbed TLS error, prefixed by supplied prefix. + * + * @param flags Flags to indicate error type and priority. + * @param errval mbed TLS error code to convert to error message. + * @param prefix Prefix to mbed TLS error message. + * + * @returns true if no errors are detected, false otherwise. + */ +bool mbed_log_err(unsigned int flags, int errval, const char *prefix); + +/** + * Log the supplied mbed TLS error, prefixed by function name and line num= ber. + * + * @param flags Flags to indicate error type and priority. + * @param errval mbed TLS error code to convert to error message. + * @param func Function name where error was reported. + * @param line Line number where error was reported. + * + * @returns true if no errors are detected, false otherwise. + */ +bool mbed_log_func_line(unsigned int flags, int errval, const char *func, = int line); + +/** Wraps mbed_log_func_line() to prevent function calls for non-errors */ +static inline bool +mbed_log_func_line_lite(unsigned int flags, int errval, const char *func, = int line) +{ + if (errval) + { + return mbed_log_func_line(flags, errval, func, line); + } + return true; +} + +/** + * Check errval and log on error. + * + * Convenience wrapper to put around mbed TLS library calls, e.g. + * if (!mbed_ok (mbedtls_ssl_func())) return 0; + * or + * ASSERT (mbed_ok (mbedtls_ssl_func())); + * + * @param errval mbed TLS error code to convert to error message. + * + * @returns true if no errors are detected, false otherwise. + */ +#define mbed_ok(errval) mbed_log_func_line_lite(D_CRYPT_ERRORS, errval, __= func__, __LINE__) + +#endif /* CRYPTO_MBEDTLS_H_ */ diff --git a/src/openvpn/mbedtls_compat.h b/src/openvpn/mbedtls_compat.h index 540f370..f904184 100644 --- a/src/openvpn/mbedtls_compat.h +++ b/src/openvpn/mbedtls_compat.h @@ -34,6 +34,16 @@ #include "errlevel.h" +#include +#include + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 +#include +#include "crypto_mbedtls_legacy.h" +#else +#include +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ + #ifdef HAVE_PSA_CRYPTO_H #include #endif @@ -51,4 +61,176 @@ #endif } +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 +typedef struct +{ + const char *name; + uint16_t tls_id; +} mbedtls_ecp_curve_info; + +static inline int +mbedtls_oid_get_attr_short_name(const mbedtls_asn1_buf *oid, const char **= desc) +{ + /* The relevant OIDs all have equal length. */ + if (oid->tag !=3D MBEDTLS_ASN1_OID || oid->len !=3D strlen(MBEDTLS_OID= _AT_CN)) + { + *desc =3D NULL; + return -1; + } + + if (memcmp(oid->p, MBEDTLS_OID_AT_CN, oid->len) =3D=3D 0) + { + *desc =3D "CN"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_SUR_NAME, oid->len) =3D=3D 0) + { + *desc =3D "SN"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_SERIAL_NUMBER, oid->len) =3D=3D= 0) + { + *desc =3D "serialNumber"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_COUNTRY, oid->len) =3D=3D 0) + { + *desc =3D "C"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_LOCALITY, oid->len) =3D=3D 0) + { + *desc =3D "L"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_STATE, oid->len) =3D=3D 0) + { + *desc =3D "ST"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_ORGANIZATION, oid->len) =3D=3D = 0) + { + *desc =3D "O"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_ORG_UNIT, oid->len) =3D=3D 0) + { + *desc =3D "OU"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_TITLE, oid->len) =3D=3D 0) + { + *desc =3D "title"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_POSTAL_ADDRESS, oid->len) =3D= =3D 0) + { + *desc =3D "postalAddress"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_POSTAL_CODE, oid->len) =3D=3D 0) + { + *desc =3D "postalCode"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_GIVEN_NAME, oid->len) =3D=3D 0) + { + *desc =3D "GN"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_INITIALS, oid->len) =3D=3D 0) + { + *desc =3D "initials"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_GENERATION_QUALIFIER, oid->len)= =3D=3D 0) + { + *desc =3D "generationQualifier"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_UNIQUE_IDENTIFIER, oid->len) = =3D=3D 0) + { + *desc =3D "uniqueIdentifier"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_DN_QUALIFIER, oid->len) =3D=3D = 0) + { + *desc =3D "dnQualifier"; + } + else if (memcmp(oid->p, MBEDTLS_OID_AT_PSEUDONYM, oid->len) =3D=3D 0) + { + *desc =3D "pseudonym"; + } + else + { + *desc =3D NULL; + return -1; + } + return 0; +} + +static inline int +mbedtls_oid_get_extended_key_usage(const mbedtls_asn1_buf *oid, const char= **desc) +{ + /* The relevant OIDs all have equal length. */ + if (oid->tag !=3D MBEDTLS_ASN1_OID || oid->len !=3D strlen(MBEDTLS_OID= _SERVER_AUTH)) + { + *desc =3D NULL; + return -1; + } + + if (memcmp(oid->p, MBEDTLS_OID_SERVER_AUTH, oid->len) =3D=3D 0) + { + *desc =3D "TLS Web Server Authentication"; + } + else if (memcmp(oid->p, MBEDTLS_OID_CLIENT_AUTH, oid->len) =3D=3D 0) + { + *desc =3D "TLS Web Client Authentication"; + } + else if (memcmp(oid->p, MBEDTLS_OID_CODE_SIGNING, oid->len) =3D=3D 0) + { + *desc =3D "Code Signing"; + } + else if (memcmp(oid->p, MBEDTLS_OID_EMAIL_PROTECTION, oid->len) =3D=3D= 0) + { + *desc =3D "E-mail Protection"; + } + else if (memcmp(oid->p, MBEDTLS_OID_TIME_STAMPING, oid->len) =3D=3D 0) + { + *desc =3D "Time Stamping"; + } + else if (memcmp(oid->p, MBEDTLS_OID_OCSP_SIGNING, oid->len) =3D=3D 0) + { + *desc =3D "OCSP Signing"; + } + else + { + *desc =3D NULL; + return -1; + } + + return 0; +} +#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */ + +/* Some functions that operate on private keys use randomness to protect a= gainst + * side channels. In Mbed TLS 4, they automatically use the RNG in the PSA + * library, but in Mbed TLS 3, they require them as explicit arguments. */ +static inline int +mbedtls_compat_pk_parse_key(mbedtls_pk_context *ctx, + const unsigned char *key, size_t keylen, + const unsigned char *pwd, size_t pwdlen) +{ +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 + return mbedtls_pk_parse_key(ctx, key, keylen, pwd, pwdlen); +#else + return mbedtls_pk_parse_key(ctx, key, keylen, pwd, pwdlen, mbedtls_ctr= _drbg_random, rand_ctx_get()); +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ +} + +static inline int +mbedtls_compat_pk_parse_keyfile(mbedtls_pk_context *ctx, const char *path,= const char *password) +{ +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 + return mbedtls_pk_parse_keyfile(ctx, path, password); +#else + return mbedtls_pk_parse_keyfile(ctx, path, password, mbedtls_ctr_drbg_= random, rand_ctx_get()); +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ +} + +static inline int +mbedtls_compat_pk_check_pair(const mbedtls_pk_context *pub, const mbedtls_= pk_context *prv) +{ +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 + return mbedtls_pk_check_pair(pub, prv); +#else + return mbedtls_pk_check_pair(pub, prv, mbedtls_ctr_drbg_random, rand_c= tx_get()); +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ +} + #endif /* MBEDTLS_COMPAT_H_ */ diff --git a/src/openvpn/ssl_mbedtls.c b/src/openvpn/ssl_mbedtls.c index 3440319..a178e0c 100644 --- a/src/openvpn/ssl_mbedtls.c +++ b/src/openvpn/ssl_mbedtls.c @@ -93,7 +93,9 @@ ASSERT(NULL !=3D ctx); CLEAR(*ctx); +#if MBEDTLS_VERSION_NUMBER < 0x04000000 ALLOC_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context); +#endif ALLOC_OBJ_CLEAR(ctx->ca_chain, mbedtls_x509_crt); @@ -107,7 +109,9 @@ ASSERT(NULL !=3D ctx); CLEAR(*ctx); +#if MBEDTLS_VERSION_NUMBER < 0x04000000 ALLOC_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context); +#endif ALLOC_OBJ_CLEAR(ctx->ca_chain, mbedtls_x509_crt); ctx->endpoint =3D MBEDTLS_SSL_IS_CLIENT; @@ -128,8 +132,10 @@ mbedtls_x509_crt_free(ctx->crt_chain); free(ctx->crt_chain); +#if MBEDTLS_VERSION_NUMBER < 0x04000000 mbedtls_dhm_free(ctx->dhm_ctx); free(ctx->dhm_ctx); +#endif mbedtls_x509_crl_free(ctx->crl); free(ctx->crl); @@ -346,6 +352,34 @@ } } +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 +static const mbedtls_ecp_curve_info ecp_curve_info_table[] =3D { + /* TODO: Fill out the table. */ + { "secp256r1", MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1 }, + { "secp384r1", MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 }, + { "X25519", MBEDTLS_SSL_IANA_TLS_GROUP_X25519 }, + { "ffdhe2048", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE2048 }, + { "ffdhe3072", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE3072 }, + { "ffdhe4096", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE4096 }, + { "ffdhe6144", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE6144 }, + { "ffdhe8192", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE8192 }, +}; +static const size_t ecp_curve_info_table_items =3D sizeof(ecp_curve_info_t= able) / sizeof(mbedtls_ecp_curve_info); + +static const mbedtls_ecp_curve_info * +mbedtls_ecp_curve_info_from_name(const char *name) +{ + for (size_t i =3D 0; i < ecp_curve_info_table_items; i++) + { + if (strcmp(name, ecp_curve_info_table[i].name) =3D=3D 0) + { + return &ecp_curve_info_table[i]; + } + } + return NULL; +} +#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */ + void tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups) { @@ -407,6 +441,7 @@ void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool= dh_inline) { +#if MBEDTLS_VERSION_NUMBER < 0x04000000 if (dh_inline) { if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx, (const unsigned c= har *)dh_file, @@ -425,6 +460,9 @@ msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with " counter_format= " bit key", (counter_type)mbedtls_dhm_get_bitlen(ctx->dhm_ctx)); +#else + msg(M_FATAL, "Mbed TLS 4 only supports pre-defined Diffie-Hellman grou= ps."); +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ } void @@ -498,29 +536,26 @@ if (priv_key_inline) { - status =3D mbedtls_pk_parse_key(ctx->priv_key, (const unsigned cha= r *)priv_key_file, - strlen(priv_key_file) + 1, NULL, 0, - mbedtls_ctr_drbg_random, rand_ctx_ge= t()); + status =3D mbedtls_compat_pk_parse_key(ctx->priv_key, (const unsig= ned char *)priv_key_file, + strlen(priv_key_file) + 1, NU= LL, 0); if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED =3D=3D status) { char passbuf[512] =3D { 0 }; pem_password_callback(passbuf, 512, 0, NULL); - status =3D mbedtls_pk_parse_key( + status =3D mbedtls_compat_pk_parse_key( ctx->priv_key, (const unsigned char *)priv_key_file, strle= n(priv_key_file) + 1, - (unsigned char *)passbuf, strlen(passbuf), mbedtls_ctr_drb= g_random, rand_ctx_get()); + (unsigned char *)passbuf, strlen(passbuf)); } } else { - status =3D mbedtls_pk_parse_keyfile(ctx->priv_key, priv_key_file, = NULL, - mbedtls_ctr_drbg_random, rand_ct= x_get()); + status =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv_key= _file, NULL); if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED =3D=3D status) { char passbuf[512] =3D { 0 }; pem_password_callback(passbuf, 512, 0, NULL); - status =3D mbedtls_pk_parse_keyfile(ctx->priv_key, priv_key_fi= le, passbuf, - mbedtls_ctr_drbg_random, ran= d_ctx_get()); + status =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv= _key_file, passbuf); } } if (!mbed_ok(status)) @@ -536,8 +571,7 @@ return 1; } - if (!mbed_ok(mbedtls_pk_check_pair(&ctx->crt_chain->pk, ctx->priv_key, - mbedtls_ctr_drbg_random, rand_ctx_g= et()))) + if (!mbed_ok(mbedtls_compat_pk_check_pair(&ctx->crt_chain->pk, ctx->pr= iv_key))) { msg(M_WARN, "Private key does not match the certificate"); return 1; @@ -574,6 +608,10 @@ mbedtls_md_type_t md_alg, unsigned int hashlen, const = unsigned char *hash, unsigned char *sig) { +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 + msg(M_WARN, "external_pkcs1_sign is not implemented for Mbed TLS 4."); + return 1; +#else struct external_context *const ctx =3D ctx_voidptr; int rv; uint8_t *to_sign =3D NULL; @@ -658,6 +696,7 @@ done: free(to_sign); return rv; +#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */ } static inline size_t @@ -672,6 +711,10 @@ tls_ctx_use_external_signing_func(struct tls_root_ctx *ctx, external_sign_= func sign_func, void *sign_ctx) { +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 + msg(M_WARN, "tls_ctx_use_external_signing_func is not implemented for = Mbed TLS 4."); + return 1; +#else ASSERT(NULL !=3D ctx); if (ctx->crt_chain =3D=3D NULL) @@ -699,6 +742,7 @@ } return 0; +#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */ } #ifdef ENABLE_MANAGEMENT @@ -936,6 +980,7 @@ void tls_ctx_personalise_random(struct tls_root_ctx *ctx) { +#if MBEDTLS_VERSION_NUMBER < 0x04000000 static char old_sha256_hash[32] =3D { 0 }; unsigned char sha256_hash[32] =3D { 0 }; mbedtls_ctr_drbg_context *cd_ctx =3D rand_ctx_get(); @@ -958,6 +1003,7 @@ memcpy(old_sha256_hash, sha256_hash, sizeof(old_sha256_hash)); } } +#endif /* MBEDTLS_VERSION_NUMBER < 0x040000 */ } #if defined(__GNUC__) || defined(__clang__) @@ -1067,7 +1113,9 @@ } #endif mbedtls_ssl_conf_dbg(ks_ssl->ssl_config, my_debug, NULL); +#if MBEDTLS_VERSION_NUMBER < 0x04000000 mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_drbg_random, rand= _ctx_get()); +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ mbedtls_ssl_conf_cert_profile(ks_ssl->ssl_config, &ssl_ctx->cert_profi= le); @@ -1098,12 +1146,14 @@ #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ /* Initialise authentication information */ +#if MBEDTLS_VERSION_NUMBER < 0x04000000 if (is_server) { mbed_ok(mbedtls_ssl_conf_dh_param_ctx(ks_ssl->ssl_config, ssl_ctx-= >dhm_ctx)); } +#endif - mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_cha= in, ssl_ctx->priv_key)); + (void)mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->c= rt_chain, ssl_ctx->priv_key)); /* Initialise SSL verification */ if (session->opt->ssl_flags & SSLF_CLIENT_CERT_OPTIONAL) @@ -1158,7 +1208,7 @@ /* Initialise SSL context */ ALLOC_OBJ_CLEAR(ks_ssl->ctx, mbedtls_ssl_context); mbedtls_ssl_init(ks_ssl->ctx); - mbed_ok(mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl->ssl_config)); + (void)mbed_ok(mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl->ssl_config)); /* We do verification in our own callback depending on the * exact configuration. We do not rely on the default hostname * verification. */ @@ -1454,6 +1504,7 @@ void show_available_curves(void) { +#if MBEDTLS_VERSION_NUMBER < 0x04000000 const mbedtls_ecp_curve_info *pcurve =3D mbedtls_ecp_curve_list(); if (NULL =3D=3D pcurve) @@ -1468,6 +1519,9 @@ printf("%s\n", pcurve->name); pcurve++; } +#else + msg(M_FATAL, "Mbed TLS 4 has no mechanism to list supported curves."); +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ } const char * diff --git a/src/openvpn/ssl_mbedtls.h b/src/openvpn/ssl_mbedtls.h index 8380a116..882a8e7 100644 --- a/src/openvpn/ssl_mbedtls.h +++ b/src/openvpn/ssl_mbedtls.h @@ -116,7 +116,9 @@ int endpoint; /**< Whether or not this is a s= erver or a client */ +#if MBEDTLS_VERSION_NUMBER < 0x04000000 mbedtls_dhm_context *dhm_ctx; /**< Diffie-Helmann-Merkle cont= ext */ +#endif mbedtls_x509_crt *crt_chain; /**< Local Certificate chain */ mbedtls_x509_crt *ca_chain; /**< CA chain for remote verifi= cation */ mbedtls_pk_context *priv_key; /**< Local private key */ diff --git a/src/openvpn/ssl_verify_mbedtls.c b/src/openvpn/ssl_verify_mbed= tls.c index 250c806..2b5a0ca 100644 --- a/src/openvpn/ssl_verify_mbedtls.c +++ b/src/openvpn/ssl_verify_mbedtls.c @@ -34,13 +34,22 @@ #if defined(ENABLE_CRYPTO_MBEDTLS) +#include + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 +#include "crypto_mbedtls_legacy.h" +#include +#include +#else #include "crypto_mbedtls.h" +#endif + +#include "mbedtls_compat.h" + #include "ssl_verify.h" #include #include -#include #include -#include #define MAX_SUBJECT_LENGTH 256 @@ -168,11 +177,139 @@ return SUCCESS; } +#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000 +/* Mbed TLS 4 has no function to print the certificate serial number and d= oes + * not expose the bignum functions anymore. So in order to write the serial + * number as a decimal string, we implement bignum % 10 and bignum / 10. */ +static char +bignum_mod_10(const uint8_t *bignum, size_t bignum_length) +{ + int result =3D 0; + for (size_t i =3D 0; i < bignum_length; i++) + { + result =3D (result * 256) % 10; + result =3D (result + bignum[i]) % 10; + } + return (char)result; +} + +/* Divide bignum by 10 rounded down, in place. */ +static void +bignum_div_10(uint8_t *bignum, size_t *bignum_length) +{ + /* + * Some intuition for the algorithm below: + * + * We want to calculate + * + * (bignum[0] * 256^n + bignum[1] * 256^(n-1) + ... + bignum[n]) /= 10. + * + * Let remainder =3D bignum[0] % 10 and carry =3D remainder * 256. + * Then we can write the above as + * + * (bignum[0] / 10) * 256^n + * + ((carry + bignum[1]) * 256^(n-1) + ... + bignum[n]) / 10. + * + * So now we have the first byte of our result. The second byte will be + * (carry + bignum[1]) / 10. Note that this fits into one byte because + * 0 <=3D remainder < 10. We calculate the next remainder and carry as + * remainder =3D (carry + bignum[1]) % 10 and carry =3D remainder * 25= 6 and + * move on to the next byte until we are done. + */ + size_t new_length =3D 0; + int carry =3D 0; + for (size_t i =3D 0; i < *bignum_length; i++) + { + uint8_t next_byte =3D (uint8_t)((bignum[i] + carry) / 10); + int remainder =3D (bignum[i] + carry) % 10; + carry =3D remainder * 256; + + /* Write the byte unless it's a leading zero. */ + if (new_length !=3D 0 || next_byte !=3D 0) + { + bignum[new_length++] =3D next_byte; + } + } + *bignum_length =3D new_length; +} + +/* Write the decimal representation of bignum to out, if enough space is a= vailable. + * Returns the number of bytes needed in out, or 0 on error. To calculate = the + * necessary buffer size, the function can be called with out =3D NULL. */ +static size_t +write_bignum(char *out, size_t out_size, const uint8_t *bignum, size_t big= num_length) +{ + if (bignum_length =3D=3D 0) + { + /* We want out to be "0". */ + if (out !=3D NULL) + { + if (out_size >=3D 2) + { + out[0] =3D '0'; + out[1] =3D '\0'; + } + else if (out_size > 0) + { + out[0] =3D '\0'; + } + } + return 2; + } + + uint8_t *bignum_copy =3D malloc(bignum_length); + if (bignum_copy =3D=3D NULL) + { + return 0; + } + memcpy(bignum_copy, bignum, bignum_length); + + size_t bytes_needed =3D 0; + size_t bytes_written =3D 0; + while (bignum_length > 0) + { + /* We're writing the digits in reverse order. We put them in the r= ight order later. */ + char digit =3D bignum_mod_10(bignum_copy, bignum_length); + if (out !=3D NULL && bytes_written < out_size - 1) + { + out[bytes_written++] =3D '0' + (char)digit; + } + bytes_needed +=3D 1; + bignum_div_10(bignum_copy, &bignum_length); + } + + if (out !=3D NULL) + { + if (bytes_written =3D=3D bytes_needed) + { + /* We had space for all digits. Now reverse them. */ + for (size_t i =3D 0; i < bytes_written / 2; i++) + { + char tmp =3D out[i]; + out[i] =3D out[bytes_written - 1 - i]; + out[bytes_written - 1 - i] =3D tmp; + } + out[bytes_written] =3D '\0'; + } + else if (out_size > 0) + { + out[0] =3D '\0'; + } + } + bytes_needed +=3D 1; + + free(bignum_copy); + return bytes_needed; +} +#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */ + char * backend_x509_get_serial(mbedtls_x509_crt *cert, struct gc_arena *gc) { char *buf =3D NULL; size_t buflen =3D 0; + +#if MBEDTLS_VERSION_NUMBER < 0x04000000 mbedtls_mpi serial_mpi =3D { 0 }; /* Transform asn1 integer serial into mbed TLS MPI */ @@ -198,6 +335,21 @@ end: mbedtls_mpi_free(&serial_mpi); return buf; +#else + buflen =3D write_bignum(NULL, 0, cert->serial.p, cert->serial.len); + if (buflen =3D=3D 0) + { + msg(M_WARN, "Failed to write serial to string."); + return NULL; + } + buf =3D gc_malloc(buflen, true, gc); + if (write_bignum(buf, buflen, cert->serial.p, cert->serial.len) !=3D b= uflen) + { + msg(M_WARN, "Failed to write serial to string."); + return NULL; + } + return buf; +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ } char * diff --git a/src/openvpn/syshead.h b/src/openvpn/syshead.h index 627ba92..de9f5f3 100644 --- a/src/openvpn/syshead.h +++ b/src/openvpn/syshead.h @@ -475,7 +475,10 @@ #endif #ifdef ENABLE_CRYPTO_MBEDTLS +#include +#if MBEDTLS_VERSION_NUMBER < 0x04000000 #define ENABLE_PREDICTION_RESISTANCE +#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */ #endif /* ENABLE_CRYPTO_MBEDTLS */ /* diff --git a/tests/Makefile.am b/tests/Makefile.am index 4b4bcaa..cdf24c8 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -55,6 +55,7 @@ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/otime.c \ $(top_srcdir)/src/openvpn/packet_id.c \ $(top_srcdir)/src/openvpn/platform.c diff --git a/tests/unit_tests/openvpn/Makefile.am b/tests/unit_tests/openvp= n/Makefile.am index 7aeea47..1128eb4 100644 --- a/tests/unit_tests/openvpn/Makefile.am +++ b/tests/unit_tests/openvpn/Makefile.am @@ -76,6 +76,7 @@ $(top_srcdir)/src/openvpn/buffer.c \ $(top_srcdir)/src/openvpn/crypto.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/otime.c \ @@ -110,6 +111,7 @@ $(top_srcdir)/src/openvpn/cryptoapi.c \ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/env_set.c \ $(top_srcdir)/src/openvpn/mss.c \ @@ -158,6 +160,7 @@ $(top_srcdir)/src/openvpn/crypto.c \ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/env_set.c \ $(top_srcdir)/src/openvpn/otime.c \ @@ -188,6 +191,7 @@ $(top_srcdir)/src/openvpn/crypto.c \ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/env_set.c \ $(top_srcdir)/src/openvpn/otime.c \ @@ -208,6 +212,7 @@ $(top_srcdir)/src/openvpn/crypto.c \ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/fdmisc.c \ $(top_srcdir)/src/openvpn/otime.c \ @@ -294,6 +299,7 @@ $(top_srcdir)/src/openvpn/crypto.c \ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/otime.c \ $(top_srcdir)/src/openvpn/packet_id.c \ @@ -332,6 +338,7 @@ $(top_srcdir)/src/openvpn/crypto.c \ $(top_srcdir)/src/openvpn/crypto_epoch.c \ $(top_srcdir)/src/openvpn/crypto_mbedtls.c \ + $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \ $(top_srcdir)/src/openvpn/crypto_openssl.c \ $(top_srcdir)/src/openvpn/otime.c \ $(top_srcdir)/src/openvpn/packet_id.c \ diff --git a/tests/unit_tests/openvpn/test_common.h b/tests/unit_tests/open= vpn/test_common.h index da98531..18222b0 100644 --- a/tests/unit_tests/openvpn/test_common.h +++ b/tests/unit_tests/openvpn/test_common.h @@ -24,6 +24,10 @@ #include #include +#if defined(ENABLE_CRYPTO_MBEDTLS) +#include "mbedtls_compat.h" +#endif + /** * Sets up the environment for unit tests like making both stderr and stdo= ut * non-buffered to avoid messages getting lost if the program exits early. @@ -36,6 +40,9 @@ { assert_int_equal(setvbuf(stdout, NULL, _IONBF, BUFSIZ), 0); assert_int_equal(setvbuf(stderr, NULL, _IONBF, BUFSIZ), 0); +#if defined(ENABLE_CRYPTO_MBEDTLS) + mbedtls_compat_psa_crypto_init(); +#endif } /** -- To view, visit http://gerrit.openvpn.net/c/openvpn/+/1441?usp=3Demail To unsubscribe, or for help writing mail filters, visit http://gerrit.openv= pn.net/settings?usp=3Demail Gerrit-MessageType: newpatchset Gerrit-Project: openvpn Gerrit-Branch: master Gerrit-Change-Id: Ib251d546d993b96ed3bd8cb9111bcc627cdb0fae Gerrit-Change-Number: 1441 Gerrit-PatchSet: 2 Gerrit-Owner: MaxF Gerrit-Reviewer: plaisthos Gerrit-CC: openvpn-devel Gerrit-Attention: plaisthos --YKGksJiGtY4= Content-Type: text/html; charset="UTF-8" Content-Transfer-Encoding: quoted-printable

Attention is cur= rently required from: plaisthos.

MaxF uploaded patch set #2 to this change.

View Change

Add support for Mbed TLS 4

This commit adds suppo= rt for Mbed TLS 4. This version comes with some
drastic changes. The cry= pto library has been completely redesigned, so
the contents of crypto_mb= edtls.c are moved to crypto_mbedtls_legacy.c
and crypto_mbedtls.c handle= s the crypto for version 4.

Mbed TLS 4 also removed the feature for = looking up a crypto algorithm by
name, so we need to translate algorithm= names to Mbed TLS numbers in
OpenVPN. The tables are not yet complete. = For symmetric algorithms, I
have added AES and Chacha-Poly which should = be enough for most use
cases.

Change-Id: Ib251d546d993b96ed3bd8cb= 9111bcc627cdb0fae
Signed-off-by: Max Fillinger <maximilian.fillinger@= ...2918...>
---
M src/openvpn/Makefile.am
M src/openvpn/crypto_= backend.h
M src/openvpn/crypto_mbedtls.c
M src/openvpn/crypto_mbedtls= .h
A src/openvpn/crypto_mbedtls_legacy.c
A src/openvpn/crypto_mbedtls= _legacy.h
M src/openvpn/mbedtls_compat.h
M src/openvpn/ssl_mbedtls.c<= br>M src/openvpn/ssl_mbedtls.h
M src/openvpn/ssl_verify_mbedtls.c
M s= rc/openvpn/syshead.h
M tests/Makefile.am
M tests/unit_tests/openvpn/M= akefile.am
M tests/unit_tests/openvpn/test_common.h
14 files changed,= 2,450 insertions(+), 700 deletions(-)

git pull =
ssh://gerrit.openvpn.net:29418/openvpn refs/changes/41/1441/2
diff =
--git a/src/openvpn/Makefile.am b/src/openvpn/Makefile.am
i= ndex db87dfc..1caed27 100644
--- a/src/openvpn/Makefile.am<= /span>
+++ b/src/openvpn/Makefile.am
@@ -53,6 +53,= 7 @@
comp-lz4.c comp-lz4.h \
crypto.c c= rypto.h crypto_backend.h \
crypto_openssl.c crypto_openss= l.h \
+ crypto_mbedtl= s_legacy.c crypto_mbedtls_legacy.h \
crypto_mbedtls.c cry= pto_mbedtls.h \
crypto_epoch.c crypto_epoch.h \ dco.c dco.h dco_internal.h \
diff --git a/src/open= vpn/crypto_backend.h b/src/openvpn/crypto_backend.h
index e= 95752a..39ae90a 100644
--- a/src/openvpn/crypto_backend.h
+++ b/src/openvpn/crypto_backend.h
@@ -32,9 = +32,16 @@
#ifdef ENABLE_CRYPTO_OPENSSL
#i= nclude "crypto_openssl.h"
#endif
+

#ifdef ENABLE_CRY= PTO_MBEDTLS
+#include= <mbedtls/version.h>
+#if MBEDTLS_VERSION_NUMBER < 0x04000000
+#include "crypto_mbedtls_legacy.h"<= /span>
+#else
#include "crypto_mbedtls.h"

#endif
= +#endif
+
#include "basic.h&= quot;
#include "buffer.h"

diff --git a/src/openvpn/crypto_mbedtls.c b/src/openvpn/crypto_= mbedtls.c
index 6688d48..425ac92 100644
---= a/src/openvpn/crypto_mbedtls.c
+++ b/src/openvpn/crypto_mb= edtls.c
@@ -6,7 +6,7 @@
* pac= ket compression.
*
* Copyright (C) 200= 2-2025 OpenVPN Inc <sales@...515...>
- * Copyright (C) 2010-2021 Sentyron B.V. <openvpn@= ...2918...>
+ * C= opyright (C) 2010-2025 Sentyron B.V. <openvpn@...2918...>
<= span> *

* This program is free software; you can redist= ribute it and/or modify
* it under the terms of the GNU = General Public License version 2
@@ -23,7 +23,8 @@
/**
* @file
- * Data Channel Cryptography mbed TLS-sp= ecific backend interface
+ * Data Channel Cryptography backend interface using the TF-PSA-Crypto= library
+ * part of = Mbed TLS 4.
*/

#ifdef = HAVE_CONFIG_H
@@ -33,6 +34,9 @@
#include &= quot;syshead.h"

#if defined(ENABLE_= CRYPTO_MBEDTLS)
+#inc= lude <mbedtls/version.h>
+
+#if MBED= TLS_VERSION_NUMBER >=3D 0x04000000

#i= nclude "errlevel.h"
#include "basic.h"=
@@ -40,20 +44,16 @@
#include "crypto= .h"
#include "integer.h"
#= include "crypto_backend.h"
+#include "crypto_mbedtls.h"
#in= clude "otime.h"
#include "misc.h"

-#include= <mbedtls/base64.h>
-#include <mbedtls/des.h>
+#include <psa/crypto.h>
+#include <psa/crypto_config.h>
+#include <mbedtls/constant_tim= e.h>

#include <mbedtls/error.h>
-#include <mbedtls/md5.h>-#include <mbedtls/cipher.h&= gt;
#include <mbedtls/pem.h>

-#include <mbedtls/entrop= y.h>
-#include <m= bedtls/ssl.h>
-
-
/*
*
* Hardware engine support. Allows loading/= unloading of engines.
@@ -82,331 +82,75 @@
= {
}

-/*
- = *
- * Functions related= to the core crypto library
- *
- */+/* The library doesn't su= pport looking up algorithms by string anymore, so here
+ * is a lookup table. */
+static const cipher_info_t cipher_i= nfo_table[] =3D {

+/*= TODO: Complete the table. */

-void
-crypto_init_lib(void)
-{
-}+/* AES */
+#if PSA_WANT_KEY_TYPE_AES
+#if PSA_WANT_ALG_GCM

+ { "AES-128-GCM", P= SA_KEY_TYPE_AES, PSA_ALG_GCM, 128 / 8, 96 / 8, 128 / 8 },

+#endif
+#if PSA_WANT_ALG_CBC_PKCS7
+ { "AES-128-CBC", PSA_KEY_TY= PE_AES, PSA_ALG_CBC_PKCS7, 128 / 8, 128 / 8, 128 / 8 },
+#endif
+#if PSA_WANT_ALG_CTR
+ { "AES-128-CTR", PSA_KEY_TYPE_AES, PS= A_ALG_CTR, 128 / 8, 128 / 8, 128 / 8 },
+#endif
+#if PSA_WANT_ALG_GCM
+ { "AES-192-GCM", PSA_KEY_TYPE_AES, PSA_ALG_GCM, 192 /= 8, 96 / 8, 128 / 8 },
+#if PSA_WA= NT_ALG_CBC_PKCS7
+ = { "AES-192-CBC", PSA_KEY_TYPE_AES, PSA_ALG_CBC_PKCS7, 192 / 8, 1= 28 / 8, 128 / 8 },
+#= endif
+#if PSA_WANT_A= LG_CTR
+ { "A= ES-192-CTR", PSA_KEY_TYPE_AES, PSA_ALG_CTR, 192 / 8, 128 / 8, 128 / 8 = },
+#endif
= +#if PSA_WANT_ALG_GCM+ { "AES-256-GCM"= , PSA_KEY_TYPE_AES, PSA_ALG_GCM, 256 / 8, 96 / 8, 128 / 8 },
+#endif

+#if PSA_WANT_ALG_CBC_PKCS7
+ { "AES-256-CBC", PSA_KEY_T= YPE_AES, PSA_ALG_CBC_PKCS7, 256 / 8, 128 / 8, 128 / 8 },
+#endif
+ { "AES-256-CTR", PSA_KEY_TYPE_AES, PS= A_ALG_CTR, 256 / 8, 128 / 8, 128 / 8 },
+#endif /* PSA_WANT_KEY_TYPE_AES */

-void
-crypto_uninit_lib(void)
-{
-}
-
-void
-crypto_clear_error(void)
-{
-}
-
-bool
-mbed_log_err(unsigned int flags, int errva= l, const char *prefix)
= -{
- if (0 !=3D errv= al)
- {
- char errstr[256];
- mbedtls_strerror(errva= l, errstr, sizeof(errstr));
-
- if (NUL= L =3D=3D prefix)
- = {
- prefi= x =3D "mbed TLS error";
- }
-= msg(flags, "%s: %s", prefix, errstr);
- }
-
- = return 0 =3D=3D errval;
-
-bool
-mbed_log_func_line(unsigned int flags, int errval, cons= t char *func, int line)
-{
- char prefix[25= 6];
-
- if (snprintf(prefix, sizeof(prefix)= , "%s:%d", func, line) >=3D sizeof(prefix))
- {
- return mbed_log_err(flags, errval, func);=
- }
-
- return mbed_log_err(flags, errval, prefix);
-}
-
-
-#ifdef DMALLOC
= -void
-crypto_init_dmalloc(void)
-{
- msg(M_ERR, "Error: dmalloc support is not available fo= r mbed TLS.");
-}<= /span>
-#endif /* DMALLOC */
-
-const cipher_name_pair cipher_name_translat= ion_table[] =3D {
- = { "BF-CBC", "BLOWFISH-CBC" },
- { "BF-CFB", "BLOWFISH-CFB64&= quot; },
- { "C= AMELLIA-128-CFB", "CAMELLIA-128-CFB128" },
- { "CAMELLIA-192-CFB", &qu= ot;CAMELLIA-192-CFB128" },
- { "CAMELLIA-256-CFB", "CAMELLIA-256-CFB128&quo= t; }
+/* Chacha-Poly = */
+#if PSA_WANT_KEY_= TYPE_CHACHA20 && PSA_WANT_ALG_CHACHA20_POLY1305
+ { "CHACHA20-POLY1305", PS= A_KEY_TYPE_CHACHA20, PSA_ALG_CHACHA20_POLY1305, 256 / 8, 96 / 8, 1 },
+#endif
}= ;
+static const size_= t cipher_info_table_entries =3D sizeof(cipher_info_table) / sizeof(cipher_i= nfo_t);
+
<= span style=3D"color: hsl(120, 100%, 40%);">+static const cipher_info_t *
+cipher_get(const char = *ciphername)
+{
+ for (size_t i =3D 0; = i < cipher_info_table_entries; i++)
+ {
+ if (strcmp(ciphername, cipher_info_table[i].name) =3D=3D 0)
+ {
+ return &cipher_i= nfo_table[i];

+ = }
+ }
= + return NULL;
+}

+
+/* Because Mbed TLS 4 doesn't support looking up algorithms by str= ing, there's
+ * = nothing to translate. */
+const cipher_name_pair cipher_name_translation_table[] =3D {};<= br> const size_t cipher_name_translation_table_count =3D
- sizeof(cipher_name_translation= _table) / sizeof(*cipher_name_translation_table);

-
-void
-show_avail= able_ciphers(void)
-{
- const int *ciphers = =3D mbedtls_cipher_list();
-
-#ifndef ENABLE_S= MALL
- printf("= The following ciphers and cipher modes are available for use\n"=
- "with "= PACKAGE_NAME ". Each cipher shown below may be used as a\n"
- "paramete= r to the --data-ciphers (or --cipher) option. Using a\n"
- "GCM or CBC mode i= s recommended. In static key mode only CBC\n"

- "mode is allowed.\n\n"= );
-#endif
-

- while (*ciphers !=3D 0)
- {
- const mbedtls_cipher_info_t *info =3D mbedtls_cipher_info= _from_type(*ciphers);
-= const char *name =3D mbedtls_cipher_info_get_name(info);
= - if (info && name= && !cipher_kt_insecure(name)
- && (cipher_kt_mode_aead(name) || cipher= _kt_mode_cbc(name)))
- = {
- p= rint_cipher(name);
- = }
- ciphers= ++;
- }
-

- printf("\nThe following ciphers have a block s= ize of less than 128 bits, \n"
- "and are therefore deprecated. Do not use un= less you have to.\n\n");
- ciphers =3D mbedtls_cipher_list();
- while (*ciphers !=3D 0)
- {
- const mbedtls_cipher_info_t *info =3D mbedtls_ciphe= r_info_from_type(*ciphers);
- const char *name =3D mbedtls_cipher_info_get_name(info);
- if (info &&= ; name && cipher_kt_insecure(name)
- && (cipher_kt_mode_aead(name) || c= ipher_kt_mode_cbc(name)))
- {
- = print_cipher(name);
- }
- ci= phers++;
- }<= br>- printf("\n");
-}
-
-void
-show_a= vailable_digests(void)
= -{
- const int *dige= sts =3D mbedtls_md_list();
-
-#ifndef ENABLE_S= MALL
- printf("= The following message digests are available for use with\n" PACKAGE_NA= ME
- ". = A message digest is used in conjunction with\n"
- "the HMAC function, to auth= enticate received packets.\n"
- "You can specify a message digest as parameter= to\n"
- = "the --auth option.\n\n");
-#endif
= -
- while (*digests = !=3D 0)
- {- const mbedtls_md_info_= t *info =3D mbedtls_md_info_from_type(*digests);
-
- if (info)
- {
- = printf("%s %d bit default key\n", mbedtls_md_get_name(info),
- mbedt= ls_md_get_size(info) * 8);
- }
- = digests++;
- }
- printf("\n")= ;
-}
-
-void
-sho= w_available_engines(void)
-{
- printf("= ;Sorry, mbed TLS hardware crypto engine functionality is not "<= br>- "available\n&= quot;);
-}
-

-#if defined(__GNUC__) || defined(__clang__)
<= span style=3D"color: hsl(0, 100%, 40%);">-#pragma GCC diagnostic push
-#pragma GCC diagnostic igno= red "-Wconversion"
-#endif
-<= br>-bool
-crypto_pem_encode(const char *name, struct buf= fer *dst, const struct buffer *src,
- struct gc_arena *gc)
-{
- /* 1000 chars is the PEM line length limit (+1 for tailing = NUL) */
- char heade= r[1000 + 1] =3D { 0 };
= - char footer[1000 + 1] =3D { 0 };
-
- i= f (snprintf(header, sizeof(header), "-----BEGIN %s-----\n", name)= >=3D sizeof(header))
- retur= n false;
- }<= br>- if (snprintf(footer, size= of(footer), "-----END %s-----\n", name) >=3D sizeof(footer))
- {
- return false;
- }
-
- = size_t out_len =3D 0;
- !=3D mbedtls_pem_write_buffer(header, foot= er, BPTR(src), BLEN(src), NULL, 0, &out_len))
- {
- return false;
- }
-
- /* We set the size bu= f to out_len-1 to NOT include the 0 byte that
- * mbedtls_pem_write_buffer in its length calcu= lation */
- *dst =3D= alloc_buf_gc(out_len, gc);
- if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), = BLEN(src), BPTR(dst),
-= BCAP(dst), &out_len))<= br>- || !buf_inc_len(dst, = out_len - 1))
- {
- CLEAR(*dst);
- return false;
- }
-
- return true;
-}
-
<= span style=3D"color: hsl(0, 100%, 40%);">-bool

-crypto_pem_decode(const char *name, struct buffer = *dst, const struct buffer *src)
-{
- /* 100= 0 chars is the PEM line length limit (+1 for tailing NUL) */
- char header[1000 + 1] =3D { 0 };=

- char footer[1000 = + 1] =3D { 0 };
-
- if (snprintf(header, si= zeof(header), "-----BEGIN %s-----", name) >=3D sizeof(header))=
- {
- return false;

- }

- if (snprintf(footer, sizeof(footer), "-----E= ND %s-----", name) >=3D sizeof(footer))
- {
- return false;
- }
-
- /* mbed TLS requires th= e src to be null-terminated */
- /* allocate a new buffer to avoid modifying the src buffer */<= /span>
- struct gc_arena gc= =3D gc_new();
- str= uct buffer input =3D alloc_buf_gc(BLEN(src) + 1, &gc);
- buf_copy(&input, src);<= br>- buf_null_terminate(&i= nput);
-
- size_t use_len =3D 0;

= - mbedtls_pem_context ctx =3D = { 0 };
- bool ret = =3D
- mbed_ok(mb= edtls_pem_read_buffer(&ctx, header, footer, BPTR(&input), NULL, 0, = &use_len));
- si= ze_t buf_size =3D 0;
- = const unsigned char *buf =3D mbedtls_pem_get_buffer(&ctx, &buf_s= ize);
- if (ret &= ;& !buf_write(dst, buf, buf_size))
- {
= - ret =3D false;
- msg(M_WARN, "PEM decode error: destination buffer too small&= quot;);
- }-
- mbedtls_pem_free(&ctx);
- gc_free(&gc);
- return ret;
-}
-
-/*
= - *
- * Random number functions, used in cases where we = want
- * reasonably str= ong cryptographic random number generation
- * without depleting our entropy pool. Used for rando= m
- * IV values and a n= umber of other miscellaneous tasks.
- *
- */
-
-/*
- * Initialise the given ctr_drbg context, using a personalisat= ion string and an
- * e= ntropy gathering function.
- */
-mbedtls_ctr_d= rbg_context *
-rand_ctx= _get(void)
-{- static mbedtls_entropy_cont= ext ec =3D { 0 };
- = static mbedtls_ctr_drbg_context cd_ctx =3D { 0 };
- static bool rand_initialised =3D false;
-
- if (!rand_initialised)
- {
- struct gc_arena gc =3D gc_new();
- struct buffer pers_string =3D = alloc_buf_gc(100, &gc);
-
- /*
- * Personalisation= string, should be as unique as possible (see NIST
- * 800-90 section 8.7.1). We have very= little information at this stage.
- * Include Program Name, memory address of the context= and PID.
- */<= /span>
- buf_printf(&am= p;pers_string, "OpenVPN %0u %p %s", platform_getpid(), &cd_ct= x,
- = time_string(0, 0, 0, &gc));
-
- /* = Initialise mbed TLS RNG, and built-in entropy sources */
- mbedtls_entropy_init(&ec);
-
- mbedtls_ctr_drbg_init(&cd_ctx);=
- if (!mbed_ok(= mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, &ec, BPTR(&= ;pers_string),
- = BLEN(&pers_string))))
- {

- msg(M_FATAL, "Failed to initia= lize random generator");
- }
-
- gc_free(&gc);=
- rand_initiali= sed =3D true;
- }
-
- return &cd_ctx;
-}
-
-#ifdef = ENABLE_PREDICTION_RESISTANCE
-void
-rand_ctx_e= nable_prediction_resistance(void)
-{
- mbed= tls_ctr_drbg_context *cd_ctx =3D rand_ctx_get();
-
- mbedtls_ctr_drbg_set_prediction_resistance(cd_ctx, 1);
= -}
-#endif /* ENABLE_PREDICTION_RESISTANCE */
= + sizeof(cipher_name_transla= tion_table) / sizeof(cipher_name_pair);

= int
rand_bytes(uint8_t *output, int len)
= {
- mbedtls_ctr_drbg= _context *rng_ctx =3D rand_ctx_get();
-
- w= hile (len > 0)
+ = if (len < 0)
{
- const size_t blen =3D min_int(len, MBEDTLS_CTR_D= RBG_MAX_REQUEST);
- = if (0 !=3D mbedtls_ctr_drbg_random(rng_ctx, output, blen))
- {

- return 0;
- }
-
- = output +=3D blen;
-= len -=3D blen;
-
= - return 1;
-}
-
-/*
- *
- * Generic = cipher key type functions
- *
- */
<= span style=3D"color: hsl(0, 100%, 40%);">-static const mbedtls_cipher_info_= t *

-cipher_get(const c= har *ciphername)
-{
- ASSERT(ciphername);
-
- const mbedtls_cipher_info_t *cipher =3D= NULL;
-
- ciphername =3D translate_cipher_= name_from_openvpn(ciphername);

- cipher =3D mbedtls_cipher_info_from_string(ciphername);=
- return cipher;+ psa_status_t result =3D p= sa_generate_random(output, (size_t)len);
+ return result =3D=3D PSA_SUCCESS;
= }

bool
@@ -414,23 +158,= 22 @@
{
ASSERT(reason);

- const mbedtls= _cipher_info_t *cipher =3D cipher_get(ciphername);
+ const cipher_info_t *cipher_info =3D cip= her_get(ciphername);

- if (NULL =3D=3D cipher)
+ if (cipher_info =3D=3D NULL)
= {
msg(D_LOW, "Cipher algorithm '%s= 9; not found", ciphername);
*reason =3D "= ;disabled because unknown";
return false;
}

- const size_t key_bytelen =3D mbedtls_cipher_info_get_ke= y_bitlen(cipher) / 8;
-= if (key_bytelen > MAX_CIPHER_KEY_LENGTH)
+ if (cipher_info->key_bytes > MAX_CIPH= ER_KEY_LENGTH)
{
msg(D_LOW,
- "Ciphe= r algorithm '%s' uses a default key size (%zu bytes) "<= br>+ "Cipher al= gorithm '%s' uses a default key size (%d bytes) "
"which is larger than " PACKAGE_NAME "'= s current maximum key size "

"(%d by= tes)",
- = ciphername, key_bytelen, MAX_CIPHER_KEY_LENGTH);
+ ciphername, cipher_info->key_= bytes, MAX_CIPHER_KEY_LENGTH);
*reason =3D "d= isabled due to key size too large";
return fa= lse;
}
@@ -442,49 +185,46 @@ const char *
cipher_kt_name(const char *ciphername= )
{
- = const mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername);
- if (NULL =3D=3D cipher_= kt)
+ const cipher= _info_t *cipher_info =3D cipher_get(ciphername);
+ if (cipher_info =3D=3D NULL)
{

return "[null-cipher]";=
}
-
- return translate_ciphe= r_name_to_openvpn(mbedtls_cipher_info_get_name(cipher_kt));
+ return cipher_info->name;
}

int
ci= pher_kt_key_size(const char *ciphername)
{
- const mbedtls_cipher_info_t *ciph= er_kt =3D cipher_get(ciphername);

-
- if (N= ULL =3D=3D cipher_kt)
+ const cipher_info_t *cipher_info =3D cipher_get(ciphername);+ if (cipher_info =3D=3D N= ULL)
{
return 0;
}

-
= - return (int)mbedtls_cipher_i= nfo_get_key_bitlen(cipher_kt) / 8;
+ return (int)cipher_info->key_bytes;
= }

int
cipher_kt_iv_size= (const char *ciphername)
{
- const mbedtls_cipher_info_t *cipher_kt =3D cipher= _get(ciphername);
+ = const cipher_info_t *cipher_info =3D cipher_get(ciphername);

- if (NULL =3D= =3D cipher_kt)
+ i= f (cipher_info =3D=3D NULL)
{
= return 0;
}
- return (int)mbedtls_cipher_info_get_iv_size(cipher_kt);
+ return cipher_info-= >iv_bytes;
}

int
cipher_kt_block_size(const char *ciphername)
= {
- const mbedtls_c= ipher_info_t *cipher_kt =3D cipher_get(ciphername);
- if (NULL =3D=3D cipher_kt)
+ const cipher_info_t *cipher_= info =3D cipher_get(ciphername);

+ if (cipher_info =3D=3D NULL)
{=
return 0;
}
- return (int)mbedtls_cipher_info_get_blo= ck_size(cipher_kt);
+= return cipher_info->block_size;
}
=
int
@@ -500,498 +240,599 @@
bool

cipher_kt_insecure(const char *ciphername)=
{
- const= mbedtls_cipher_info_t *cipher_kt =3D cipher_get(ciphername);
- if (!cipher_kt)

+ const cipher_info_t *cipher_inf= o =3D cipher_get(ciphername);

+ if (cipher_info =3D=3D NULL)
{ return true;
}

- return !(cipher_kt_bloc= k_size(ciphername) >=3D 128 / 8
-#ifdef MBEDTLS_CHACHAPOLY_C
- || mbedtls_cipher_info_get_type(cipher_kt) = =3D=3D MBEDTLS_CIPHER_CHACHA20_POLY1305
-#endif
-}
= -
-static mbedtls_cipher_mode_t
-cipher_kt_mode(const mbedtls_cipher_info_t *ci= pher_kt)
-{
<= span style=3D"color: hsl(0, 100%, 40%);">- ASSERT(NULL !=3D cipher_kt);<= /span>
- return mbedtls_cip= her_info_get_mode(cipher_kt);
+ return !(cipher_info->block_size >=3D 128 / 8+ || cipher_info-&= gt;psa_alg =3D=3D PSA_ALG_CHACHA20_POLY1305);
}
=
bool
cipher_kt_mode_cbc(const cha= r *ciphername)
{
- const mbedtls_cipher_info_t *cipher =3D cipher_get(cipherna= me);
- return cipher= && cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_CBC;
+ const cipher_info_t *cipher_inf= o =3D cipher_get(ciphername);

+ if (cipher_info =3D=3D NULL)
+ {
+ return false;
+ }
+ = return cipher_info->psa_alg =3D=3D PSA_ALG_CBC_PKCS7;
= }

bool
cipher_kt_mode_o= fb_cfb(const char *ciphername)
{
- const mbedtls_cipher_info_t *cipher =3D cip= her_get(ciphername);
- = return cipher
- = && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB
= - || cipher_kt_mode= (cipher) =3D=3D OPENVPN_MODE_CFB);
+ const cipher_info_t *cipher_info =3D cipher_get(cipherna= me);
+ if (cipher_= info =3D=3D NULL)
+ = {
+ return f= alse;
+ }+ return cipher_info->p= sa_alg =3D=3D PSA_ALG_OFB || cipher_info->psa_alg =3D=3D PSA_ALG_CFB;
}

bool
c= ipher_kt_mode_aead(const char *ciphername)
{
- const mbedtls_cipher_info_t *ci= pher =3D cipher_get(ciphername);

- return cipher
- && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_GC= M
-#ifdef MBEDTLS_CHACH= APOLY_C
- = || cipher_kt_mode(cipher) =3D=3D MBEDTLS_MODE_CHACHAPOLY
-#endif
- );
+ const cipher_info_t *cipher_info =3D cipher_get(cipherna= me);
+ if (cipher_= info =3D=3D NULL)
+ = {
+ return f= alse;
+ }+ return cipher_info->p= sa_alg =3D=3D PSA_ALG_GCM || cipher_info->psa_alg =3D=3D PSA_ALG_CHACHA2= 0_POLY1305;
}

-
-/*
- *
= - * Generic cipher context functi= ons
- *
- */

-
-m= bedtls_cipher_context_t *
+cipher_ctx_t *
cipher_ctx_new(void)
= {
- mbedtls_cipher_= context_t *ctx;
- AL= LOC_OBJ(ctx, mbedtls_cipher_context_t);
+ cipher_ctx_t *ctx;
+ /* Initializing the object with zeros ensures th= at it is always safe to call
+ * cipher_ctx_free. */
+ ALLOC_OBJ_CLEAR(ctx, cipher_ctx_t);
= return ctx;
}

void
-cipher_ctx_free(mbedtls_= cipher_context_t *ctx)
- mbedtls_cipher_free(ctx);
= + /* TODO: Log warning on er= rors? */
+ if (cip= her_ctx_mode_aead(ctx))
+ {
+ ps= a_aead_abort(&ctx->operation.aead);
+ }
+ else
+ = {
+ psa_ciph= er_abort(&ctx->operation.cipher);
+ }
+ psa_destroy_key(ctx->key);
free(ctx);
}

void
-cipher_ctx_init(mbedtls_cipher_context_t= *ctx, const uint8_t *key, const char *ciphername,
+cipher_ctx_init(cipher_ctx_t *ctx, const uin= t8_t *key, const char *ciphername,
crypto_= operation_t enc)
{
- ASSERT(NULL !=3D ciphername && NULL !=3D ctx);
+ ASSERT(ciphername = !=3D NULL && ctx !=3D NULL);
CLEAR(*ctx);

- cons= t mbedtls_cipher_info_t *kt =3D cipher_get(ciphername);
- ASSERT(kt);
- size_t key_bitlen =3D mbedtls_cipher_info_g= et_key_bitlen(kt);
+ = ctx->cipher_info =3D cipher_get(ciphername);
+ ASSERT(ctx->cipher_info !=3D NULL);

- i= f (!mbed_ok(mbedtls_cipher_setup(ctx, kt)))
- {
- msg(M_FATAL, "mbed TLS cipher context init #1");
- }
+ psa_set_key_type(&ctx->key_= attributes, ctx->cipher_info->psa_key_type);
+ psa_set_key_algorithm(&ctx->key_a= ttributes, ctx->cipher_info->psa_alg);
+ psa_set_key_bits(&ctx->key_attributes, = (size_t)ctx->cipher_info->key_bytes * 8);
+ psa_set_key_usage_flags(&ctx->key_at= tributes,
+ = enc =3D=3D OPENVPN_OP_ENCRYPT ? PSA_KEY_USAGE_ENCRYPT : P= SA_KEY_USAGE_DECRYPT);

- if (!mbed_ok(mbedtls_cipher_setkey(ctx, key, (int)ke= y_bitlen, enc)))
+ = if (psa_import_key(&ctx->key_attributes, key, (size_t)ctx->ciphe= r_info->key_bytes, &ctx->key) !=3D PSA_SUCCESS)
= {
- msg(M_FA= TAL, "mbed TLS cipher set key");
- }
-
- if (mbedtls_= cipher_info_get_mode(kt) =3D=3D MBEDTLS_MODE_CBC)
- {
- if (!mbed_ok(mbedtls_cipher_set_padding_mode(ctx, MBEDT= LS_PADDING_PKCS7)))
- = {
- ms= g(M_FATAL, "mbed TLS cipher set padding mode");
- }
+ msg(M_FATAL, "psa_import_key failed&= quot;);
}

/* ma= ke sure we used a big enough key */
- ASSERT(mbedtls_cipher_get_key_bitlen(ctx) <=3D key_bit= len);
+ ASSERT(psa= _get_key_bits(&ctx->key_attributes) =3D=3D (size_t)(8 * ctx->ciph= er_info->key_bytes));
}

int

-cipher_ctx_iv_= length(const mbedtls_cipher_context_t *ctx)
+cipher_ctx_iv_length(const cipher_ctx_t *ctx)
{
- retu= rn mbedtls_cipher_get_iv_size(ctx);
+ return ctx->cipher_info->iv_bytes;
}


int
cipher_ctx_get= _tag(cipher_ctx_t *ctx, uint8_t *tag, int tag_len)
{
- if (tag_len > SIZE_M= AX)
+ if (!ctx->= ;aead_finished || tag_len < OPENVPN_AEAD_TAG_LENGTH)
= {
return 0;
}

- if (!mbed_ok(= mbedtls_cipher_write_tag(ctx, (unsigned char *)tag, tag_len)))
- {

- return 0;
- }
-
+ memcpy(tag= , ctx->tag, OPENVPN_AEAD_TAG_LENGTH);
return 1;
}

int
-cipher_ctx_block_size(const mbedtls_cipher= _context_t *ctx)
+cip= her_ctx_block_size(const cipher_ctx_t *ctx)
{
- return (int)mbedtls_cipher_get= _block_size(ctx);

+ = return ctx->cipher_info->block_size;
}
<= span>

int
-cipher_ctx_mode(const mbedtls_cipher_context_t *ctx)
+cipher_ctx_mode(const cipher_ctx_t *= ctx)
{
- ASSERT(NULL !=3D ctx);
-
- return mbe= dtls_cipher_get_cipher_mode(ctx);
+ ASSERT(ctx !=3D NULL);
+ return (int)psa_get_key_algorithm(&ctx->key= _attributes);
}

bool
cipher_ctx_mode_cbc(const cipher_ctx_t *ctx)
{

- return ctx &am= p;& cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CBC;
+ return ctx !=3D NULL && ciphe= r_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CBC;
}

-
b= ool
cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx)
{
- retu= rn ctx
- &= ;& (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_OFB
- || cipher_ctx_mode(ctx) =3D= =3D OPENVPN_MODE_CFB);
+ {
+ = return false;
+ = }
+ int mode =3D c= ipher_ctx_mode(ctx);
= + return mode =3D=3D OPENVPN_MODE_OFB || mode =3D=3D OPENVPN_MODE_CFB;
}

bool
= cipher_ctx_mode_aead(const cipher_ctx_t *ctx)
{
= - return ctx
- && (cipher_ctx_mode(= ctx) =3D=3D OPENVPN_MODE_GCM
-#ifdef MBEDTLS_CHACHAPOLY_C
- || cipher_ctx_mode(ctx) =3D=3D MBEDTLS_MODE_CHA= CHAPOLY
-#endif<= br>- );
+ if (ctx =3D=3D NULL)

= + {
+ return false;
+ }
+ int mode =3D cipher_ctx_mode(ctx);
+ return mode =3D=3D (int)PSA_ALG_= GCM || mode =3D=3D (int)PSA_ALG_CHACHA20_POLY1305;
+}
+
+static= int
+cipher_ctx_dire= ction(const cipher_ctx_t *ctx)
+{
+ psa= _key_usage_t key_usage =3D psa_get_key_usage_flags(&ctx->key_attribu= tes);
+ if (key_us= age & PSA_KEY_USAGE_ENCRYPT)
+ {
+ = return OPENVPN_OP_ENCRYPT;
+ }
+= else if (key_usage & PSA_KEY_USAGE_DECRYPT)
+ {
+ return OPENVPN_OP_DECRYPT;
+ }
+ else
+ {
+ = return -1;
+ }=
}

int
-cipher_ctx_reset(mbedtls_cipher_contex= t_t *ctx, const uint8_t *iv_buf)
+cipher_ctx_reset(cipher_ctx_t *ctx, const uint8_t *iv_buf)
{
- if= (!mbed_ok(mbedtls_cipher_reset(ctx)))
- {
= - return 0;
- = }
+ psa_status_t = status =3D 0;

- if (!mbed_ok(mbedtls_cipher_set_iv(ctx, iv_buf, (size_t)mbedt= ls_cipher_get_iv_size(ctx))))
+ if (cipher_ctx_mode_aead(ctx))
{<= br>- return 0;
<= span style=3D"color: hsl(120, 100%, 40%);">+ if (psa_aead_abort(&= ;ctx->operation.aead) !=3D PSA_SUCCESS)

+ {
+ return 0;
+ }
+
+ if (ci= pher_ctx_direction(ctx) =3D=3D OPENVPN_OP_ENCRYPT)
+ {
+ status =3D psa_aead_encrypt_setup(&ctx= ->operation.aead, ctx->key, ctx->cipher_info->psa_alg);<= br>+ }
+ else if (cipher_ctx_direction= (ctx) =3D=3D OPENVPN_OP_DECRYPT)
+ {
+ }
+ else
+ {
+ }
+
+ if (status !=3D = PSA_SUCCESS)
+ = {
+ retur= n 0;
+ }
+
+ status =3D psa_aead_set_nonce(&c= tx->operation.aead, iv_buf, ctx->cipher_info->iv_bytes);+ if (status !=3D PSA_S= UCCESS)
+ {
+ return 0;<= /span>
+ }
= + }
+ else
+ {
+ if (psa_cipher_abort(&ctx->operation.cipher) !=3D PSA_= SUCCESS)
+ {
+ return 0;=
+ }+
+ if (cipher_ctx_direction(ctx) =3D=3D OPE= NVPN_OP_ENCRYPT)
+ = {
+ s= tatus =3D psa_cipher_encrypt_setup(&ctx->operation.cipher, ctx->k= ey, ctx->cipher_info->psa_alg);
+ }
+ else if (cipher_ctx_direction(ctx) =3D=3D OPENVPN_OP_DECRYP= T)
+ {<= br>+ status =3D psa_= cipher_decrypt_setup(&ctx->operation.cipher, ctx->key, ctx->ci= pher_info->psa_alg);
+ }
+ = else
+ {
+ return 0;
+ }
<= span style=3D"color: hsl(120, 100%, 40%);">+

+ if (status !=3D PSA_SUCCESS)
+ {

+ return 0;
+ }
+
+ status =3D psa_cipher_set_iv(&ctx->operation.cipher, = iv_buf, ctx->cipher_info->iv_bytes);
+ if (status !=3D PSA_SUCCESS)
+ {

+ return 0;
+ }
}
return 1;
}

+/* We rely on the= caller to ensure that the destination buffer has enough room,
+ * but Mbed TLS always wants a s= ize for the destination buffer. This function

+ * calculates the minimum necessary size for a gi= ven cipher and input length.
+ *
+ * This = funcion assumes that src_len has been checked to be >=3D 0. */+static size_t
+needed_dst_size(const cipher_ctx_t = *ctx, int src_len)

+{=
+ int mode =3D ci= pher_ctx_mode(ctx);
+= if (mode =3D=3D PSA_ALG_CTR || mode =3D=3D PSA_ALG_GCM || mode =3D=3D P= SA_ALG_CHACHA20_POLY1305)
+ {
+ = /* These algorithms are based on a keystream, so the input and output
+ * length are alw= ays equal. */
+ = return (size_t)src_len;
+ }
+ else=
+ {
+ /* These algorithms are b= lock-based. The number of output blocks that are

+ * produced is at most 1 + src_len / b= lock_size. */
+ = size_t block_size =3D (size_t)cipher_ctx_block_size(ctx);
+ size_t max_blocks =3D 1 + (= size_t)src_len / block_size;

+ return max_blocks * block_size;
+ }
+}
+
int
cipher_ctx_update_ad(cipher_ctx_t *ctx,= const uint8_t *src, int src_len)
{
- if (src_len > SIZE_MAX)
+ if (src_len < 0 || !ciphe= r_ctx_mode_aead(ctx))

{
retur= n 0;
}

- if (!mbed_ok(mbedtls_cipher_update_ad(ctx, src,= src_len)))
+ if (= psa_aead_update_ad(&ctx->operation.aead, src, (size_t)src_len) !=3D = PSA_SUCCESS)
{
return 0;
}
+ = return 1;
+}
+
+int
+cipher_ctx_update(cipher_ctx_t *ctx, uint8_t *dst, int *dst_= len, uint8_t *src, int src_len)
+{
+ if= (src_len < 0)
+ = {
+ return 0= ;
+ }
+

+ size_t dst_size =3D needed_dst_size(ctx, src_le= n);
+ size_t psa_o= utput_len =3D 0;
+ = psa_status_t status =3D 0;
+
+ if (cip= her_ctx_mode_aead(ctx))
+ {
+ st= atus =3D psa_aead_update(&ctx->operation.aead, src, (size_t)src_len,= dst, dst_size, &psa_output_len);
+ }
+ else
+ {
+ status =3D ps= a_cipher_update(&ctx->operation.cipher, src, (size_t)src_len, dst, d= st_size, &psa_output_len);
+ }
+
+ if (status !=3D PS= A_SUCCESS)
+ {
+ return 0;
+ }
+
+ if (psa_output_len > INT_MAX)
+ {
+ return 0;
+ }
+ *dst_len =3D (int)psa_output_len;

return 1;

}

int
-cipher_ctx_update(mbedt= ls_cipher_context_t *ctx, uint8_t *dst, int *dst_len, uint8_t *src,<= br>- int src_len= )
+cipher_ctx_final(c= ipher_ctx_t *ctx, uint8_t *dst, int *dst_len)
{
= - size_t s_dst_len =3D *dst_le= n;
+ size_t dst_si= ze =3D needed_dst_size(ctx, 0);
+ size_t psa_output_len =3D 0;
+ psa_status_t status =3D 0;

- if (!mbed_ok(mbedtl= s_cipher_update(ctx, src, (size_t)src_len, dst, &s_dst_len)))+ if (cipher_ctx_mode_aead(= ctx))
{
- return 0;
+ size_t actual_tag_size =3D 0;
+ status =3D psa_aead_finish(&ctx->oper= ation.aead,
+ = dst,
+ dst_size,
+ &psa= _output_len,
+ = ctx->tag,
+ (size_t)OPENVPN_AEAD_TA= G_LENGTH,
+ = &actual_tag_size);
+ if (status !=3D PSA_SUCCESS || psa_output= _len > (size_t)INT_MAX || actual_tag_size !=3D (size_t)OPENVPN_AEAD_TAG_= LENGTH)
+ {
+ return 0;<= /span>
+ }
= + ctx->aead_finished = =3D true;
+ }
+ else
+ {

+ status =3D psa_cipher_finish(&ctx->= ;operation.cipher, dst, dst_size, &psa_output_len);
+ if (status !=3D PSA_SUCCESS || = psa_output_len > (size_t)INT_MAX)
+ {
+ return 0;
+ }
}

- *dst_len =3D s_dst_len;
+ *dst_len =3D (int)psa_out= put_len;

return 1;
= }

int
-cipher_ctx_final(mbedtls_cipher_context_t *ctx, uint8_t = *dst, int *dst_len)
+= cipher_ctx_final_check_tag(cipher_ctx_t *ctx, uint8_t *dst, int *dst_len, u= int8_t *tag, size_t tag_len)
{
- size_t s_dst_len =3D *dst_len;
-

- if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &s_d= st_len)))
+ if (ci= pher_ctx_direction(ctx) !=3D OPENVPN_OP_DECRYPT || !cipher_ctx_mode_aead(ct= x))
{
return 0;
}


- *dst_len =3D s_dst_len;
+ size_t psa_output_len =3D 0;
+ psa_status_t status =3D 0;
+
+ status =3D psa_aead_verify(&ctx->operation.ae= ad, dst, 0, &psa_output_len, tag, tag_len);
+ if (status !=3D PSA_SUCCESS || psa_output_l= en > (size_t)INT_MAX)
+ {
+ r= eturn 0;
+ }
+ *dst_len =3D (int)psa= _output_len;

return 1;
}


-int
-cipher_ctx_final= _check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_len, uint8= _t *tag,
- = size_t tag_len)
+static const md_info_t md_info_table[] =3D {
+ /* TODO: Fill out table. */+ { "MD5", PSA_A= LG_MD5 },
+ { &quo= t;SHA1", PSA_ALG_SHA_1 },
+ { "SHA256", PSA_ALG_SHA_256 },
+};
+const size_t md_info_table_entries =3D sizeof(md_info_ta= ble) / sizeof(md_info_t);
+
+static const = md_info_t *
+md_get(c= onst char *digest_name)
{
- size_t olen =3D 0;
-
= - if (MBEDTLS_DECRYPT !=3D mbedtls_cipher_get_operation(ctx))
= + for (size_t i =3D 0; i <= ; md_info_table_entries; i++)
{
- return 0;
+ if (strcmp(digest_name, md_info_table= [i].name) =3D=3D 0)
+= {
+ = return &md_info_table[i];
+ }
}
-
- if (tag_len > SIZE_MAX)
- {
- = return 0;
- }
-
- if (!mbed_ok(mbedtls_cipher_finish(ctx, ds= t, &olen)))
- {<= /span>
- msg(D_CRYPT_ER= RORS, "%s: cipher_ctx_final() failed", __func__);
- return 0;

- }
-
- = if (olen > INT_MAX)
- {
- return= 0;
- }
- *dst_len =3D olen;

<= span style=3D"color: hsl(0, 100%, 40%);">-

- if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (const = unsigned char *)tag, tag_len)))
- {
- = return 0;
- }
-
- return 1;
-}
-=
-#if defined(__GNUC__)= || defined(__clang__)
= -#pragma GCC diagnostic pop
-#endif
--/*
- *
- * Generic message digest information functions
- *
- */
-
-
-static const mbedtls_md_info_t *
-md_get(const char *digest)
-{
- const mbedtls_md_info_t *md =3D NULL;- ASSERT(digest);
= -
- md =3D mbedtls_md_info_from_string(digest);
- if (!md)
- {

- msg(M_FATAL, "Message hash algorithm &#= 39;%s' not found", digest);
- }
- = if (mbedtls_md_get_size(md) > MAX_HMAC_KEY_LENGTH)
- {
- msg(M_FATAL,
- "Message hash algorithm '%s' use= s a default hash size (%d bytes) which is larger than " PACKAGE_NAME
- "'= s current maximum hash size (%d bytes)",
- digest, mbedtls_md_get_size(md), MAX_HM= AC_KEY_LENGTH);
- }<= /span>
- return md;<= br>+ return NULL;
= }

bool
md_valid(= const char *digest)
{
- const mbedtls_md_info_t *md =3D mbedtls_md_info_from_s= tring(digest);
+ c= onst md_info_t *md =3D md_get(digest);
return md !=3D = NULL;
}

const char *
md_kt_name(const char *mdname)
{
= - if (!strcmp("none"= , mdname))
+ if (s= trcmp("none", mdname) =3D=3D 0)
{
= return "[null-digest]";
}
- const mbedtls_md_info= _t *kt =3D md_get(mdname);
- return mbedtls_md_get_name(kt);
+ const md_info_t *md =3D md_get(mdname);
= + if (md =3D=3D NULL)=
+ {
+ return NULL;
+ }
+ return md->name;
}
=
unsigned char
md_kt_size(const ch= ar *mdname)
{
- if (!strcmp("none", mdname))
+ if (strcmp("none", mdname) = =3D=3D 0)
{
return 0;<= br> }
- co= nst mbedtls_md_info_t *kt =3D md_get(mdname);
- return mbedtls_md_get_size(kt);
+ const md_info_t *md_info =3D md= _get(mdname);

+ if= (md_info =3D=3D NULL)
+ ret= urn 0;
+ }<= br>+ return (unsigned char)P= SA_HASH_LENGTH(md_info->psa_alg);
}

-/*
- *
- * Generic message digest functions
- *
- */
+md_ctx_= t *
+md_ctx_new(void)=
+{
+ md_ctx_t *ctx;
+ ALLOC_OBJ_CLEAR(ctx, md_ctx_t);
+ return ctx;=
+}
=
int
md_full(const char *mdname, const uint8_t *= src, int src_len, uint8_t *dst)
{
- const mbedtls_md_info_t *kt =3D md_get(mdn= ame);
- return 0 =3D= =3D mbedtls_md(kt, src, src_len, dst);
-}
+ = const md_info_t *md =3D md_get(mdname);
+ if (md =3D=3D NULL || src_len < 0)
= + {
+ return 0;
+ }

-mbedtls_md_context_t *
-md_ctx_new(void)
-{
- mbedtls_md_context_t *ctx;
- ALLOC_OBJ_CLEAR(ctx, mbedtls_md_context_t);
= - return ctx;
+ /* We depend on the caller to en= sure that dst has enough room for the hash,
+ * so we just tell PSA that it can hold the app= ropriate amount of bytes. */
+ size_t dst_size =3D PSA_HASH_LENGTH(md->psa_alg);+ size_t hash_length =3D 0;=
+
+ psa_status_t status =3D psa_hash_c= ompute(md->psa_alg, src, (size_t)src_len, dst, dst_size, &hash_lengt= h);
+ if (status != =3D PSA_SUCCESS || hash_length !=3D dst_size)
+ {
+ return 0;
+ }
+ = return 1;
}

void=
-md_ctx_free(mbedtls_md_conte= xt_t *ctx)
+md_ctx_fr= ee(md_ctx_t *ctx)
{
free(ctx);=
}

void
-md_ctx_init(mbedtls_md_context_t *ctx, cons= t char *mdname)
+md_c= tx_init(md_ctx_t *ctx, const char *mdname)
{
- const mbedtls_md_info_t *kt =3D= md_get(mdname);

- A= SSERT(NULL !=3D ctx && NULL !=3D kt);
+ const md_info_t *md_info =3D md_get(mdname);<= /span>
+ ASSERT(ctx !=3D = NULL && md_info !=3D NULL);

- mbedtls_md_init(ctx);
- ASSERT(0 =3D=3D mbedtls_md_setup(ct= x, kt, 0));
- ASSERT= (0 =3D=3D mbedtls_md_starts(ctx));
+ ctx->md_info =3D md_info;
+ ASSERT(psa_hash_setup(&ctx->operatio= n, md_info->psa_alg) =3D=3D PSA_SUCCESS);
}
<= span>

void
-md_ctx_cleanup(mbedtls_md_context_t *ctx)
+md_ctx_cleanup(md_ctx_t *ctx)
= {
- mbedtls_md_free= (ctx);
+ /* TODO: = Warn if not success? */
+ psa_hash_abort(&ctx->operation);
}
int
-md_ctx_size(const mbedtls_md_context_t *ctx)
+md_ctx_size(const md_ctx_t *ctx) {
- if (NUL= L =3D=3D ctx)
+ if= (ctx =3D=3D NULL)
{
return 0= ;
}
+ return (int)PSA_HASH= _LENGTH(ctx->md_info->psa_alg);
}
<= /span>
void
-= md_ctx_update(mbedtls_md_context_t *ctx, const uint8_t *src, size_t src_len= )
+md_ctx_update(md_c= tx_t *ctx, const uint8_t *src, size_t src_len)
{- ASSERT(0 =3D=3D mbedtls_md_= update(ctx, src, src_len));
+ ASSERT(psa_hash_update(&ctx->operation, src, src_len) = =3D=3D PSA_SUCCESS);
}

= void
-md_ctx_final(mbed= tls_md_context_t *ctx, uint8_t *dst)
+md_ctx_final(md_ctx_t *ctx, uint8_t *dst)
= {
- ASSERT(0 =3D=3D= mbedtls_md_finish(ctx, dst));
- mbedtls_md_free(ctx);
+ /* We depend on the caller to ensure that dst has enough= room for the hash,
+= * so we just tell PSA that it can hold the appropriate amount of bytes= . */
+ size_t dst_= size =3D PSA_HASH_LENGTH(ctx->md_info->psa_alg);
+ size_t hash_length =3D 0;
= +
+ ASSERT(psa_hash_finish(&ctx->operation= , dst, dst_size, &hash_length) =3D=3D PSA_SUCCESS);
+ ASSERT(hash_length =3D=3D dst_size)= ;
}

-
-/*
- *
- * Generic HMAC functions
- *
- */
-=
-
-/*
- * TODO: re-enable dmsg for crypto debug
- */
-
-mbedtl= s_md_context_t *
+hma= c_ctx_t *
hmac_ctx_new(void)
{
= - mbedtls_md_context_t *ctx;
- ALLOC_OBJ(ctx, mbed= tls_md_context_t);
+ = hmac_ctx_t *ctx;
+= ALLOC_OBJ_CLEAR(ctx, hmac_ctx_t);
return ctx;
}

void
-hmac_ctx_free(mbedtls_md_context_t *ctx)
+hmac_ctx_free(hmac_ct= x_t *ctx)
{
free(ctx);
}


= -void
-hmac_ctx_init(mb= edtls_md_context_t *ctx, const uint8_t *key, const char *mdname)
= +static void
+hmac_ctx_init_with_arbitrary_key_lengt= h(hmac_ctx_t *ctx, const uint8_t *key, size_t key_len, const md_info_t *md_= info)
{
- ASSERT(NULL !=3D kt && NULL != =3D ctx);
+ ctx-&g= t;md_info =3D md_info;
+ psa_set_key_algori= thm(&ctx->key_attributes, PSA_ALG_HMAC(md_info->psa_alg));=
+ psa_set_key_usage_flag= s(&ctx->key_attributes, PSA_KEY_USAGE_SIGN_MESSAGE);

- mbedtls_md_init= (ctx);
- int key_len= =3D mbedtls_md_get_size(kt);
- ASSERT(0 =3D=3D mbedtls_md_setup(ctx, kt, 1));
- ASSERT(0 =3D=3D mbedtls_md_hmac_st= arts(ctx, key, key_len));
+ if (psa_import_key(&ctx->key_attributes, key, key_len, &am= p;ctx->key) !=3D PSA_SUCCESS)
+ {
+ = msg(M_FATAL, "psa_import_key failed");
+ }

- /* make sure we used a big enough= key */

- ASSERT(mbe= dtls_md_get_size(kt) <=3D key_len);
+ ASSERT(psa_mac_sign_setup(&ctx->operation, ct= x->key, PSA_ALG_HMAC(md_info->psa_alg)) =3D=3D PSA_SUCCESS); }

void
-hmac_ctx_cleanup(mbedtls_md_context_t *ctx)
+hmac_ctx_init(hmac_ctx= _t *ctx, const uint8_t *key, const char *mdname)
{<= br>- mbedtls_md_free(ctx);
+ const md_info_t *md= _info =3D md_get(mdname);
+ ASSERT(ctx !=3D NULL && key !=3D NULL && md_info = !=3D NULL);
+<= br>+ hmac_ctx_init_with_arbi= trary_key_length(ctx, key, PSA_HASH_LENGTH(md_info->psa_alg), md_info);<= /span>
+}
+
+void
+{
+ = /* TODO: Warn if not success? */
+ psa_mac_abort(&ctx->operation);
+ psa_destroy_key(ctx->key);
}

int
-hmac_ctx_size(mbedtls_md_context_t *ctx)<= /span>
+hmac_ctx_size(hmac_c= tx_t *ctx)
{
- if (NULL =3D=3D ctx)
- {
- = return 0;
- }
- return mbedtls_md_get= _size(mbedtls_md_info_from_ctx(ctx));
+ return (int)PSA_HASH_LENGTH(ctx->md_info->psa_a= lg);
}

void
<= span style=3D"color: hsl(0, 100%, 40%);">-hmac_ctx_reset(mbedtls_md_context= _t *ctx)

+hmac_ctx_re= set(hmac_ctx_t *ctx)
{
- ASSERT(0 =3D=3D mbedtls_md_hmac_reset(ctx));+ ASSERT(psa_mac_abort(&am= p;ctx->operation) =3D=3D PSA_SUCCESS);
+ ASSERT(psa_mac_sign_setup(&ctx->operation,= ctx->key, PSA_ALG_HMAC(ctx->md_info->psa_alg)) =3D=3D PSA_SUCCESS= );
}

void
-hmac_ctx_update(mbedtls_md_context_= t *ctx, const uint8_t *src, int src_len)

+hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, i= nt src_len)
{
- ASSERT(0 =3D=3D mbedtls_md_hmac_update(ctx, src, src_len));
+ ASSERT(src_len >= ;=3D 0);
+ ASSERT(= psa_mac_update(&ctx->operation, src, (size_t)src_len) =3D=3D PSA_SUC= CESS);
}

void-hmac_ctx_final(mbedtls_md_conte= xt_t *ctx, uint8_t *dst)
+hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
{
- ASSERT(0 =3D=3D mbedtls= _md_hmac_finish(ctx, dst));
+ /* We depend on the caller to ensure that dst has enough room f= or the hash,
+ * = so we just tell PSA that it can hold the appropriate amount of bytes. */
+ size_t dst_size = =3D PSA_HASH_LENGTH(ctx->md_info->psa_alg);
+ size_t hmac_length =3D 0;
+

+ ASSERT(psa_mac_sign_finish(&ctx->operation,= dst, dst_size, &hmac_length) =3D=3D PSA_SUCCESS);
+ ASSERT(hmac_length =3D=3D dst_size);=
}

-int
-me= mcmp_constant_time(const void *a, const void *b, size_t size)
-{

- /* mbed TLS has a no const time memcmp function tha= t it exposes
- * vi= a its APIs like OpenSSL does with CRYPTO_memcmp
- * Adapt the function that mbedtls itself use= s in
- * mbedtls_sa= fer_memcmp as it considers that to be safe */
- volatile const unsigned char *A =3D (volatile c= onst unsigned char *)a;
- volatile const unsigned char *B =3D (volatile const unsigned char *)b= ;
- volatile unsigne= d char diff =3D 0;
-
- for (size_t i =3D 0;= i < size; i++)
- = {
- unsigned ch= ar x =3D A[i], y =3D B[i];
- diff |=3D x ^ y;
- }
-<= br>- return diff;
-}

-
-= #if defined(__GNUC__) || defined(__clang__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wconversi= on"
-#endif=
-
/*<= br> * Generate the hash required by for the \c tls1_PRF function.
*
@@ -1004,8 +845,8 @@
* = @param olen Length of the output buffer
*/
static void
-tls1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *sec, size_t se= c_len, const uint8_t *seed,
- size_t seed_len, uint8_t *out, size_t olen)
+tls1_P_hash(const md_info_t *md_i= nfo, const uint8_t *sec, size_t sec_len, const uint8_t *seed,

+ int seed_len, uint8_t= *out, size_t olen)

{
struct gc_arena= gc =3D gc_new();
uint8_t A1[MAX_HMAC_KEY_LENGTH];
@@ -1023,18 +864,13 @@
dmsg(D_SHOW_KEY_SO= URCE, "tls1_P_hash sec: %s", format_hex(sec, sec_len, 0, &gc)= );
dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s&= quot;, format_hex(seed, seed_len, 0, &gc));
- unsigned int chunk =3D mbed= tls_md_get_size(md_kt);
- unsigned int A1_len =3D mbedtls_md_get_size(md_kt);
+ unsigned int chunk =3D (unsigned = int)PSA_HASH_LENGTH(md_info->psa_alg);
+ unsigned int A1_len =3D (unsigned int)PSA_HASH_LE= NGTH(md_info->psa_alg);

/* This i= s the only place where we init an HMAC with a key that is not
* equal to its size, therefore we init the hmac ctx manually here = */

- mbedtls_md_init= (ctx);
- ASSERT(0 = =3D=3D mbedtls_md_setup(ctx, md_kt, 1));
- ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx, sec, sec= _len));
-
- mbedtls_md_init(ctx_tmp);
- ASSERT(0 =3D=3D mbedtls= _md_setup(ctx_tmp, md_kt, 1));
- ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx_tmp, sec, sec_len))= ;
+ hmac_ctx_init_= with_arbitrary_key_length(ctx, sec, sec_len, md_info);
+ hmac_ctx_init_with_arbitrary_key_len= gth(ctx_tmp, sec, sec_len, md_info);

= hmac_ctx_update(ctx, seed, seed_len);
hmac_ctx_final(= ctx, A1);
@@ -1045,7 +881,7 @@
hma= c_ctx_reset(ctx_tmp);
hmac_ctx_update(ctx, A1, A1_= len);
hmac_ctx_update(ctx_tmp, A1, A1_len);=
- hmac_ctx_update(ctx,= seed, seed_len);
+ = hmac_ctx_update(ctx, seed, (int)seed_len);
if (olen > chunk)
{
= @@ -1094,9 +930,15 @@
ssl_tls1_PRF(const uint8_t *la= bel, size_t label_len, const uint8_t *sec, size_t slen, uint8_t *out1,
size_t olen)
{
+ const md_info_t *md5 =3D md_get(&= quot;MD5");
+ = const md_info_t *sha1 =3D md_get("SHA1");
+
+ if (label_len > (size_t)INT_MAX)
+ {
+ return false;
+ }
+
struct gc_arena gc =3D gc_new();
<= span style=3D"color: hsl(0, 100%, 40%);">- const md_kt_t *md5 =3D md_get= ("MD5");

- = const md_kt_t *sha1 =3D md_get("SHA1");
=
uint8_t *out2 =3D (uint8_t *)gc_malloc(olen, false, &gc)= ;

@@ -1105,8 +947,8 @@
= const uint8_t *S2 =3D &(sec[len]);
len +=3D (sl= en & 1); /* add for odd, make longer */

- tls1_P_hash(md5, S1, len, label= , label_len, out1, olen);

- tls1_P_hash(sha1, S2, len, label, label_len, out2, olen);+ tls1_P_hash(md5, S1, len,= label, (int)label_len, out1, olen);
+ tls1_P_hash(sha1, S2, len, label, (int)label_len, out2= , olen);

for (size_t i =3D 0; i <= olen; i++)
{
@@ -1121,8 +963,204 @@
return true;
}

-#if defined(__GNUC__) || de= fined(__clang__)
-#prag= ma GCC diagnostic pop
+void
+crypto_init_l= ib(void)
+{+}
+
+void
+crypto= _uninit_lib(void)
+{<= /span>
+}
+
+void
+{
+}+
+bool
+mbed_log_err(unsigned int flags, int errval, const char *prefi= x)
+{
+ if (0 !=3D errval)

+ {

+ char errstr[256];
+ mbedtls_strerror(errval, errstr,= sizeof(errstr));
+
+ if (NULL =3D= =3D prefix)
+ = {
+ prefix= =3D "mbed TLS error";
+ }
+ }
+
+ return 0 =3D=3D errval;
+}
+
+bool
+mbed_log_func_line(unsigned int flags,= int errval, const char *func, int line)
+{
+
+ if (snprin= tf(prefix, sizeof(prefix), "%s:%d", func, line) >=3D sizeof(pr= efix))
+ {<= br>+ return mbed_log_err= (flags, errval, func);
+
= + return mbed_log_err(flags,= errval, prefix);
+}<= /span>
+
+int
+memcmp_constant_time(const void *a, const void *b, size= _t size)
+{+ return mbedtls_ct_memcmp(= a, b, size);
+}
+
+void
+show_available_ciphers(void)
+{
+ /* Mbed TLS 4 does not currently have a mechanism to discover av= ailable
+ * ciphe= rs. We instead print out the ciphers from cipher_info_table. */
<= span style=3D"color: hsl(120, 100%, 40%);">+

+#ifndef ENABLE_SMALL
+ printf("The following ciphers and cipher= modes are available for use\n"
+ "with " PACKAGE_NAME ". Each ci= pher shown below may be used as a\n"
+ "parameter to the --data-ciphers (or = --cipher) option. Using a\n"
+ "GCM or CBC mode is recommended. In static = key mode only CBC\n"
+ "mode is allowed.\n\n");
#endif=

-#en= dif /* ENABLE_CRYPTO_MBEDTLS */
+ for (size_t i =3D 0; i < cipher_info_table_entries; i++)=
+ {
+ const cipher_info_t *info= =3D &cipher_info_table[i];

+ const char *name =3D info->name;
+ if (!cipher_kt_insecure(name) &= amp;& (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(name)))+ {
+ print_cipher(name);=
+ }
+ }
+
+ printf("\nThe following ciphers have a block size of less th= an 128 bits, \n"
+ "and are therefore deprecated. Do not use unless you hav= e to.\n\n");
+ = for (size_t i =3D 0; i < cipher_info_table_entries; i++)
+ {

+ const cipher_info_t *info =3D &ciph= er_info_table[i];
+ = const char *name =3D info->name;
+ if (cipher_kt_insecure(name) && (ciph= er_kt_mode_aead(name) || cipher_kt_mode_cbc(name)))
+ {
+ print_cipher(name);
+ }
+ }
+ printf("\n");
+}
+
+void
+show_available_digests(void)
+{
+ /* Mbed TLS 4 does not currently have= a mechanism to discover available
+ * message digests. We instead print out the digests fro= m md_info_table. */
+=
+#ifndef ENABLE_SMAL= L
+ printf("T= he following message digests are available for use with\n" PACKAGE_NAM= E
+ ".= A message digest is used in conjunction with\n"
+ "the HMAC function, to a= uthenticate received packets.\n"
+ "You can specify a message digest as para= meter to\n"
+ = "the --auth option.\n\n");
+#endif
+
+ for= (size_t i =3D 0; i < md_info_table_entries; i++)
+ {
+ const md_info_t *info =3D &md_info_table[i]= ;
+ printf(&qu= ot;%s %d bit default key\n", info->name,
+ (unsigned char)PSA_HASH_LENGTH(= info->psa_alg) * 8);
+ }
+ printf= ("\n");
+}<= /span>
+
+void
+show_available_engines(void)
+{
+ printf("Sorry, mbed TLS hardware crypto engine functio= nality is not "
= + "available\n");
+}
+=
+bool
+crypto_pem_encode(const char *name= , struct buffer *dst, const struct buffer *src,

+ struct gc_arena *gc)+{
+ /* 1000 chars is the PEM line length limit= (+1 for tailing NUL) */
+ char header[1000 + 1] =3D { 0 };
+ char footer[1000 + 1] =3D { 0 };
+
+ if (snprintf(header, sizeof(header), "-----BEG= IN %s-----\n", name) >=3D sizeof(header))
+ {
+ return false;
+ }
+ if (snprintf(footer, sizeof(footer), "-----END %s-----\n"= , name) >=3D sizeof(footer))
+ {
+ = return false;
+= }
+
+ size_t out_len =3D 0;
<= br>+ if (MBEDTLS_ERR_BASE64_= BUFFER_TOO_SMALL
+ = !=3D mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src), NU= LL, 0, &out_len))
+ {
+ retu= rn false;
+ }
+
+ /* We set the size buf to out_len-1 t= o NOT include the 0 byte that
+ * mbedtls_pem_write_buffer in its length calculation */
+ *dst =3D alloc_buf_g= c(out_len, gc);
+ = if (!mbed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src),= BPTR(dst),
+ = BCAP(dst), &out_len))
+ || !(out_len < INT_MAX &= amp;& out_len > 1)

+ || !buf_inc_len(dst, (int)out_len - 1))
+ {
+ CLEAR(*dst);
+ return false;
+ }
+
+ return= true;
+}
<= span style=3D"color: hsl(120, 100%, 40%);">+

+bool
+crypto_pem_decode(const char *name, struct buffer *dst, const str= uct buffer *src)
+{
+ /* 1000 chars is = the PEM line length limit (+1 for tailing NUL) */
+ char header[1000 + 1] =3D { 0 };+ char footer[1000 + 1] = =3D { 0 };
++ if (snprintf(header, siz= eof(header), "-----BEGIN %s-----", name) >=3D sizeof(header))<= /span>
+ {
+ return false;

+ }

+ if (snprintf(footer, sizeof(footer), "= ;-----END %s-----", name) >=3D sizeof(footer))
+ {
+ return false;
+ }
+
+ /* mbe= d TLS requires the src to be null-terminated */
+ /* allocate a new buffer to avoid modifying= the src buffer */
+ = struct gc_arena gc =3D gc_new();
+ struct buffer input =3D alloc_buf_gc(BLEN(src) + 1, &am= p;gc);
+ buf_copy(= &input, src);
+ = buf_null_terminate(&input);
+
+ s= ize_t use_len =3D 0;
= + mbedtls_pem_context ctx =3D { 0 };
+ bool ret =3D
+ mbed_ok(mbedtls_pem_read_buffer(&ctx, header, = footer, BPTR(&input), NULL, 0, &use_len));
+ size_t buf_size =3D 0;
+ const unsigned char *buf =3D mbed= tls_pem_get_buffer(&ctx, &buf_size);
+ if (ret && !buf_write(dst, buf, buf_si= ze))
+ {+ ret =3D false;=
+ msg(M_WARN, "= PEM decode error: destination buffer too small");
+ }
+
+ mbedtls_pem_free(&ctx);
+ gc_free(&gc);
+ return ret;
+}
+
+#endif /* MBEDTLS_VERSION= _NUMBER >=3D 0x04000000 */
+#endif /* defined(ENABLE_CRYPTO_MBEDTLS) */
diff = --git a/src/openvpn/crypto_mbedtls.h b/src/openvpn/crypto_mbedtls.h<= br>index 71514fc..dd491f3 100644
--- a/src/openvpn/cr= ypto_mbedtls.h
+++ b/src/openvpn/crypto_mbedtls.h@@ -1,3 +1,4 @@
- * Copyright (C) 2= 010-2021 Sentyron B.V. <openvpn@...2918...>
+ * Copyright (C) 2010-2025 Sentyron B.V. <= ;openvpn@...2918...>
*
* This progr= am is free software; you can redistribute it and/or modify
= * it under the terms of the GNU General Public License version 2<= br>@@ -23,85 +24,98 @@

/**<= br> * @file
- * = Data Channel Cryptography mbed TLS-specific backend interface
+ * Data Channel Cryptography back= end interface using the TF-PSA-Crypto library

+ * part of Mbed TLS 4.
*/

-#ifndef C= RYPTO_MBEDTLS_H_
-#defi= ne CRYPTO_MBEDTLS_H_
= +#ifndef CRYPTO_MBEDTLS4_H_
+#define CRYPTO_MBEDTLS4_H_

-#include <stdbool.h>
-#include <mbedtls/cipher.h>
-#include <mbedtls/md.h&= gt;
-#include <mbedt= ls/ctr_drbg.h>
+#i= nclude <psa/crypto.h>

-/** Generic message digest key type %context. */
-typedef mbedtls_md_info_= t md_kt_t;
-
= -/** Generic cipher %context. */<= /span>
-typedef mbedtls_cipher= _context_t cipher_ctx_t;
-/** Generic messag= e digest %context. */
-= typedef mbedtls_md_context_t md_ctx_t;
-
-/** = Generic HMAC %context. */
-typedef mbedtls_md_context_t hmac_ctx_t;
-
-/* Use a dummy type for the provider */
-typedef void provider_t;
+#include "integer.h"

/** Maximum length of an IV */
-#define OPENVPN_MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGT= H
+#define OPENVPN_MA= X_IV_LENGTH 16

/** Cipher is in CBC mode= */
-#define OPENVPN_MO= DE_CBC MBEDTLS_MODE_CBC
+#define OPENVPN_MODE_CBC PSA_ALG_CBC_PKCS7

= /** Cipher is in OFB mode */
-#define OPENVPN_MODE_OFB MBEDTLS_MODE_OFB
+#define OPENVPN_MODE_OFB PSA_ALG_OFB

/** Cipher is in CFB mode */
-#define OPENVPN_MODE_CFB MBEDTLS_MO= DE_CFB

+#define OPENV= PN_MODE_CFB PSA_ALG_CFB

/** Cipher is in= GCM mode */
-#define O= PENVPN_MODE_GCM MBEDTLS_MODE_GCM
+#define OPENVPN_MODE_GCM PSA_ALG_GCM
<= br>-typedef mbedtls_operation_t c= rypto_operation_t;
+t= ypedef int crypto_operation_t;

/** Ciphe= r should encrypt */
-#d= efine OPENVPN_OP_ENCRYPT MBEDTLS_ENCRYPT
+#define OPENVPN_OP_ENCRYPT 0
<= br> /** Cipher should decrypt */
-#define OPENVPN_OP_DECRYPT MBEDTLS_DECRYPT
+#define OPENVPN_OP_DECRYPT 1
=

#define MD4_DIGEST_LENGTH 16
#define MD5_DIGEST_LENGTH 16

#define SHA_DIGEST_LENG= TH 20
#define SHA256_DIGEST_LENGTH 32
=
-/**
- * Returns a singleton instance of the = mbed TLS random number generator.
- *
- * For = PolarSSL/mbed TLS 1.1+, this is the CTR_DRBG random number generator. If it=
- * hasn't been in= itialised yet, the RNG will be initialised using the default
- * entropy sources. Aside from the d= efault platform entropy sources, an

- * additional entropy source, the HAVEGE random number genera= tor will also be
- * ad= ded. During initialisation, a personalisation string will be added based
- * on the time, the PID,= and a pointer to the random context.
- */
-mb= edtls_ctr_drbg_context *rand_ctx_get(void);
+typedef void provider_t;
-#ifdef ENABLE_PREDICTION_RESIS= TANCE
-/**
- * Enable prediction resistance on= the random number generator.

- */
-void rand_= ctx_enable_prediction_resistance(void);
+typedef struct cipher_info
+{
+ const char *name;
+ psa_key_type_t psa_key_type;
+ psa_algorithm_t psa_alg;
+ int key_bytes;
+ int iv_bytes;
+ int block_size;
+} cipher_info_t;
=
-#endif
+typedef union psa_cipher_or_aead_operatio= n
+{
+ psa_cipher_operation_t cipher;
+ psa_aead_operatio= n_t aead;
+} cipher_o= peration_t;
+<= br>+typedef struct cipher_ctx
+{
+ mbedtls_svc_key_id_t key;+ psa_key_attributes_t key_= attributes;
+ cons= t cipher_info_t *cipher_info;
+ bool aead_finished;
+ cipher_operation_t operation;
+ uint8_t tag[16];
+} cipher_ctx_t;
+
+typedef struct md_info
+{
+ const= char *name;
+ psa= _algorithm_t psa_alg;
+} md_info_t;
+
+typedef struct md_ctx
+{
+ const md_info_t *md_info;
= + psa_hash_operation_t opera= tion;
+} md_ctx_t;
+
+typedef struct hmac_ctx
+{
+ mbedtls_svc_key_id_t key;
+ psa_key_attributes_t key_attributes;
+ const md_info_t *md_= info;
+ psa_mac_op= eration_t operation;
= +} hmac_ctx_t;

/**
* L= og the supplied mbed TLS error, prefixed by supplied prefix.
*

* @param flags Flags to indicate error type= and priority.
- * @par= am errval mbed TLS error code to convert to error message.+ * @param errval mbed = TLS error code.
* @param prefix Prefix to mbed TLS= error message.
*
* @returns true if no= errors are detected, false otherwise.
@@ -112,7 +126,7 @@<= /span>
* Log the supplied mbed TLS error, prefixed by function n= ame and line number.
*
* @param flags = Flags to indicate error type and priority.
- * @param errval mbed TLS error code to = convert to error message.
+ * @param errval mbed TLS error code.
* @par= am func Function name where error was reported.
= * @param line Line number where error was reported.
*

@@ -142,7 +156,8 @@
* @param errval= mbed TLS error code to convert to error message.
= *
* @returns true if no errors are detected, false otherw= ise.
+ * TODO: The lo= g function has been removed, do something about it?
*/
#define mbed_ok(errval) mbed_log_func_line_lite(D_CRYPT_ERRO= RS, errval, __func__, __LINE__)

-#endif /* CRYPTO_MBEDTLS_H_ */
+#endif /* CRYPTO_MBEDTLS4_H_ */
diff --git a/src/openvpn/crypto_mbedtls_legacy.c b/src/openvpn/= crypto_mbedtls_legacy.c
new file mode 100644
index 0000000..c847038

--- /dev/null
+++ = b/src/openvpn/crypto_mbedtls_legacy.c
@@ -0,0 +1,1133 @@
+/*
+ * OpenVPN -- An application to secure= ly tunnel IP networks
+ * over a single TCP/UDP port, with support for SSL/TLS-based=
+ * sess= ion authentication and key exchange,
+ * packet encryption, packet authentication, a= nd
+ * pa= cket compression.
+ *=
+ * Copyright (C) 2= 002-2025 OpenVPN Inc <sales@...515...>
+ * Copyright (C) 2010-2021 Sentyron B.V. <open= vpn@...2918...>
+ = *
+ * This program i= s free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Genera= l Public License version 2
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it wil= l be useful,
+ * but= WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR = A PARTICULAR PURPOSE. See the

+ * GNU General Public License for more details.
+ *

+ * You should have received a copy of the GNU Gener= al Public License along
+ * with this program; if not, see <https://www.gnu.org/licenses/>= ;.
+ */
+

+/**
+ * @file
+ * D= ata Channel Cryptography mbed TLS-specific backend interface,
+ * for mbed TLS 3.X versions.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#inc= lude "syshead.h"
+
+#if defined(= ENABLE_CRYPTO_MBEDTLS)
+
+#= if MBEDTLS_VERSION_NUMBER < 0x04000000
+
+#include "basic.h"
+#include "buffer.h"
+#include "crypto.h"
<= span style=3D"color: hsl(120, 100%, 40%);">+#include "integer.h"<= /span>
+#include "crypt= o_backend.h"
+#i= nclude "otime.h"
+#include "misc.h"
+
+#inc= lude <mbedtls/base64.h>
+#include <mbedtls/des.h>
+#include <mbedtls/error.h>
+#include <mbedtls/md5.h>
= +#include <mbedtls/cipher.h&= gt;
+#include <mbe= dtls/pem.h>
+
+#include <mbedtls/ent= ropy.h>
+#include = <mbedtls/ssl.h>
+
+
+/*
+ *
+ * Hardware engine support. Allows loading/unloading of engines.
+ *
+ */
+
+v= oid
+crypto_init_lib_= engine(const char *engine_name)
+{
+ ms= g(M_WARN, "Note: mbed TLS hardware crypto engine functionality is not = "
+ = "available");
+}
+
= +provider_t *
+crypto_load_provider(const char *prov= ider)
+{
+ if (provider)

+ {

+ msg(M_WARN, "Note: mbed TLS provide= r functionality is not available");
+ }
+ return NULL;
+}
+
+void

+crypto_unload_provider(const char *provname, pro= vider_t *provider)
+{=
+}
+
+/*
+ *
+ * Functions re= lated to the core crypto library
+ *
+ */<= /span>
+
+void
+crypto_init_lib(void)
+{
+}
+
+void

+crypto_uninit_lib(void)
+{
+}
+
+void
+crypto_clear_error(void)
<= span style=3D"color: hsl(120, 100%, 40%);">+{

+}
+
+bool=
+mbed_log_err(unsigned int = flags, int errval, const char *prefix)
+{
= + if (0 !=3D errval)
+ {
+ ch= ar errstr[256];
+ = mbedtls_strerror(errval, errstr, sizeof(errstr));
+
+ if (NULL =3D=3D prefix)
+ {
+ prefix =3D "mbed TLS error";<= br>+ }
+ msg(flags, "%s: %s"= , prefix, errstr);
+ = }
+
+ return 0 =3D=3D errval;
=
+}
+
+bool
+mbe= d_log_func_line(unsigned int flags, int errval, const char *func, int line)=
+{
+ char prefix[256];
+

+ if (snprintf(prefix, sizeof(prefix), "%s:%d&q= uot;, func, line) >=3D sizeof(prefix))
+ {
+ return mbed_log_err(flags, errval, func);
+ }
+
+ return mbed_log_err(flags, errval, prefix);
+}
+
+
+#ifdef DMALLOC<= br>+void
+crypto_init_dmalloc(void)
+{

+ msg(M_ERR, "Error: dmalloc support is not av= ailable for mbed TLS.");
+}
+#endif /= * DMALLOC */
+=
+const cipher_name_pair cip= her_name_translation_table[] =3D {
+ { "BF-CBC", "BLOWFISH-CBC" },=
+ { "BF-CFB", = "BLOWFISH-CFB64" },
+ { "CAMELLIA-128-CFB", "CAMELLIA-128-CFB128&quo= t; },
+ { "CA= MELLIA-192-CFB", "CAMELLIA-192-CFB128" },
+ { "CAMELLIA-256-CFB", &q= uot;CAMELLIA-256-CFB128" }
+};
+const= size_t cipher_name_translation_table_count =3D
+ sizeof(cipher_name_translation_table) / siz= eof(*cipher_name_translation_table);
+
+vo= id
+show_available_ci= phers(void)
+{=
+ const int *ciphers =3D= mbedtls_cipher_list();
+
+#ifndef ENABLE_= SMALL
+ printf(&qu= ot;The following ciphers and cipher modes are available for use\n"
+ "with &= quot; PACKAGE_NAME ". Each cipher shown below may be used as a\n"= ;
+ "p= arameter to the --data-ciphers (or --cipher) option. Using a\n"
+ "GCM or C= BC mode is recommended. In static key mode only CBC\n"
+ "mode is allowed.\= n\n");

+#endif
+
+ while (*ciphers !=3D 0)
+ {

+ const mbedtls_cipher_info_t *info =3D = mbedtls_cipher_info_from_type(*ciphers);
+ const char *name =3D mbedtls_cipher_info_get_n= ame(info);
+ i= f (info && name && !cipher_kt_insecure(name)
+ && (cipher_kt_= mode_aead(name) || cipher_kt_mode_cbc(name)))

+ {
+ print_cipher(name);
+ }
+ ciphers++;
+ }
+ printf("= ;\nThe following ciphers have a block size of less than 128 bits, \n"<= /span>
+ "and= are therefore deprecated. Do not use unless you have to.\n\n");
+ ciphers =3D mbedtls_= cipher_list();
+ w= hile (*ciphers !=3D 0)
+ con= st mbedtls_cipher_info_t *info =3D mbedtls_cipher_info_from_type(*ciphers);=
+ const char = *name =3D mbedtls_cipher_info_get_name(info);
+ if (info && name && ciphe= r_kt_insecure(name)
+= && (cipher_kt_mode_aead(name) || cipher_kt_mode_cbc(nam= e)))
+ {
+ print_cipher(= name);
+ }
+ ciphers++;
+ }
+ printf("\n");
= +}
+
+void
+show_av= ailable_digests(void)
+{
+ const int *d= igests =3D mbedtls_md_list();
+
+#ifndef E= NABLE_SMALL
+ prin= tf("The following message digests are available for use with\n" P= ACKAGE_NAME
+ = ". A message digest is used in conjunction with\n"
= + "the HMAC func= tion, to authenticate received packets.\n"
+ "You can specify a message dige= st as parameter to\n"
+ "the --auth option.\n\n");
+#endif
+
+ {
+ = const mbedtls_md_info_t *info =3D mbedtls_md_info_from_type(*digests);=
+
+ if (info)
+ {
+ printf("%s %d bit default key\n&q= uot;, mbedtls_md_get_name(info),
+ mbedtls_md_get_size(info) * 8);
<= span style=3D"color: hsl(120, 100%, 40%);">+ }

+ digests++;
+ }
+ printf("\n");
+}
+
+void
+show_available_engines(v= oid)
+{
+ printf("Sorry, mbed TLS = hardware crypto engine functionality is not "

+ "available\n");<= br>+}
+
+#if defined(__GNUC__) || defined(__clang__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored &= quot;-Wconversion"

+#endif
++bool
+crypto_pem_encode(const char *name, struc= t buffer *dst, const struct buffer *src,
+ struct gc_arena *gc)
+{

+ /* 1000 chars is the PEM line length limit (+1 fo= r tailing NUL) */
+ = char header[1000 + 1] =3D { 0 };
+ char footer[1000 + 1] =3D { 0 };
+
+ if (snprintf(header, sizeof(header), "-----BEGIN %s= -----\n", name) >=3D sizeof(header))
+ {
+ return false;
+ }
+ = if (snprintf(footer, sizeof(footer), "-----END %s-----\n", nam= e) >=3D sizeof(footer))
+ {
+ = return false;
+ }=
+
+ size_t out_len =3D 0;
+ if (MBEDTLS_ERR_BASE64_BUFFE= R_TOO_SMALL

+ = !=3D mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src), NULL, 0= , &out_len))
+ = {
+ return fa= lse;
+ }+
+ /* We set the size buf to out_len-1 to NOT i= nclude the 0 byte that
+ *dst =3D alloc_buf_gc(out_l= en, gc);
+ if (!mb= ed_ok(mbedtls_pem_write_buffer(header, footer, BPTR(src), BLEN(src), BPTR(d= st),
+ = BCAP(dst), &out_len))
+ || !buf_inc_len(dst, out_len - 1)= )
+ {
+ CLEAR(*dst);

<= span style=3D"color: hsl(120, 100%, 40%);">+ return false;
+ }
+
+ return true;
+}
+
+bool
+crypto_pem_decode(const char *name, stru= ct buffer *dst, const struct buffer *src)
+{
+ /* 1000 chars is the PEM line length limit (+1 for tailing NUL) */<= /span>
+ char header[1000= + 1] =3D { 0 };
+ = char footer[1000 + 1] =3D { 0 };
+
+ i= f (snprintf(header, sizeof(header), "-----BEGIN %s-----", name) &= gt;=3D sizeof(header))
+ ret= urn false;
+ }
+ if (snprintf(footer= , sizeof(footer), "-----END %s-----", name) >=3D sizeof(footer= ))
+ {
<= span style=3D"color: hsl(120, 100%, 40%);">+ return false;
+ }
+
+ /* mbed TLS requires the src to be null-terminated */
+ /* allocate a new = buffer to avoid modifying the src buffer */
+ struct gc_arena gc =3D gc_new();
+ struct buffer input =3D alloc_= buf_gc(BLEN(src) + 1, &gc);

+ buf_copy(&input, src);
+ buf_null_terminate(&input);
+
+ size_t use_len =3D 0;
+ mbedtls_pem_context ctx =3D { 0 };
= + bool ret =3D
+ mbed_ok(mbedtls_pem_read_= buffer(&ctx, header, footer, BPTR(&input), NULL, 0, &use_len));=

+ size_t buf_size= =3D 0;
+ const un= signed char *buf =3D mbedtls_pem_get_buffer(&ctx, &buf_size);
+ if (ret && !b= uf_write(dst, buf, buf_size))
+ {
+ = ret =3D false;
+ = msg(M_WARN, "PEM decode error: destination buffer too small&quo= t;);
+ }+
+ mbedtls_pem_free(&ctx);
+ gc_free(&gc);
+ return ret;

+}
+
+= /*
+ *
+ * Random number functions, used i= n cases where we want

+ * reasonably strong cryptographic random number generation
+ * without depleting our entropy = pool. Used for random

+ *
+ */
+
+/*
= + * Initialise the given ctr_dr= bg context, using a personalisation string and an
+ * entropy gathering function.
+ */

+mbedtls_ctr_drbg_context *
+rand_ctx_get(void)
+{
+ static mbedtls_entropy_context ec =3D { 0 };
= + static mbedtls_ctr_drbg_co= ntext cd_ctx =3D { 0 };
+ static bool rand_initialised =3D false;
+
+ if (!rand_initialised)
+ {
+ struct gc_arena gc =3D gc_new();
+ struct buffer pers_string =3D alloc_buf_gc(1= 00, &gc);
+
+ /*
+ * Personalisation string,= should be as unique as possible (see NIST

+ * 800-90 section 8.7.1). We have very littl= e information at this stage.
+ * Include Program Name, memory address of the context and= PID.
+ */
+ buf_printf(&am= p;pers_string, "OpenVPN %0u %p %s", platform_getpid(), &cd_ct= x,
+ = time_string(0, 0, 0, &gc));
+
+ = /* Initialise mbed TLS RNG, and built-in entropy sources */
+ mbedtls_entropy_init(&am= p;ec);

+
+ mbedtls_ctr_drbg_init(&a= mp;cd_ctx);

+ = if (!mbed_ok(mbedtls_ctr_drbg_seed(&cd_ctx, mbedtls_entropy_func, &= ec, BPTR(&pers_string),
+ BLEN(&pers_string)))= )
+ {+ msg(M_FATAL, &qu= ot;Failed to initialize random generator");
+ }
+
+= gc_free(&gc);
+ rand_initialised =3D true;
+ }
+
+ return &= amp;cd_ctx;
+}=
+
+#ifdef ENABLE_PREDICTION_RESISTANCE+void
+rand_ctx_enable_prediction_resistance(void)<= /span>
+{
+ mbedtls_ctr_drbg_context *cd_ctx = =3D rand_ctx_get();
+=
+ mbedtls_ctr_drb= g_set_prediction_resistance(cd_ctx, 1);
+}
+#endif /* ENABLE_PREDICTION_RESISTANCE */
+
+int
+rand_bytes(= uint8_t *output, int len)
+{
+ mbedtls_= ctr_drbg_context *rng_ctx =3D rand_ctx_get();
+
+ while (len > 0)
+ {
+ = const size_t blen =3D min_int(len, MBEDTLS_CTR_DRBG_MAX_REQUEST);
+ if (0 !=3D mbedtl= s_ctr_drbg_random(rng_ctx, output, blen))
+ {
+ return 0;
+ }
+
+ output = +=3D blen;
+ l= en -=3D blen;
+ }<= /span>
+
+ return 1;
+}
+
+/*
+ *
+ * Generic cipher key type functions
+ *
+ */
+static const mbedtls_cipher_info_t *
+cipher_get(const char *ciphername)
+{
+ ASSERT(ciphername);
+
+ const mbedtls_cipher_info_t *cipher =3D NULL;=
+
+ ciphername =3D translate_cipher_name_from= _openvpn(ciphername);
+ cipher =3D mbedtls_cipher_info_from_string(ciphername);
+ return cipher;

+}

+
+bool
+cipher_vali= d_reason(const char *ciphername, const char **reason)
+{
+ ASSERT(reason);
+
+ = const mbedtls_cipher_info_t *cipher =3D cipher_get(ciphername);
= +
+ if (NULL =3D=3D cipher)
+ {
+ msg(D_LOW, "Cipher algorithm '%s' = not found", ciphername);
+ *reason =3D "disabled because unknown";<= br>+ return false;
+ }
+
+ const size_t key_bytelen =3D mbedtls_cipher_info_get_k= ey_bitlen(cipher) / 8;
+ {
+ msg(D_LOW,
+ "Cipher algorithm '%s' uses a defa= ult key size (%zu bytes) "
+ "which is larger than " PACKAGE_NAME &quo= t;'s current maximum key size "
+ "(%d bytes)",
+ ciphername, key_bytelen, M= AX_CIPHER_KEY_LENGTH);
+ return false;
+ }
+
+ *reason =3D NULL;
+ return true;
+}
= +
+const char *
+cipher_kt_name(const char= *ciphername)
+{
+ const mbedtls_cipher= _info_t *cipher_kt =3D cipher_get(ciphername);
+ if (NULL =3D=3D cipher_kt)
+ {
+ return "[null-cipher]";+ }
+
+ return translate_cipher_name_to_openvpn(mbedtls_cipher_i= nfo_get_name(cipher_kt));
+}
+
<= span style=3D"color: hsl(120, 100%, 40%);">+int

+cipher_kt_key_size(const char *ciphername)
+{
+ const mbedtls_cipher_info_t *cipher_k= t =3D cipher_get(ciphername);
+
+ if (N= ULL =3D=3D cipher_kt)
+ {
+ retu= rn 0;
+ }+
+ return (int)mbedtls_cipher_info_get_key_bit= len(cipher_kt) / 8;
+= }
+
+int
+cipher_kt_iv_size(const char *ciphername)
<= span style=3D"color: hsl(120, 100%, 40%);">+{

+ const mbedtls_cipher_info_t *cipher_kt =3D ci= pher_get(ciphername);
+
+ if (NULL =3D= =3D cipher_kt)
+ {=
+ return 0;
+ }
+ return (int)mbedtls_cipher_info= _get_iv_size(cipher_kt);

+}
+
+int

+cipher_kt_block_size(const char *ciphername)
+{
+ const mbedtls_cipher_info_t *cipher_k= t =3D cipher_get(ciphername);
+ if (NULL =3D=3D cipher_kt)
+ {
+ return 0;
+ }
+ retur= n (int)mbedtls_cipher_info_get_block_size(cipher_kt);
+}
+
+int=
+cipher_kt_tag_size(= const char *ciphername)
+{
+ if (cipher= _kt_mode_aead(ciphername))
+ {
+ = return OPENVPN_AEAD_TAG_LENGTH;
+ }
+ = return 0;
+}
+
+bool
+cipher_kt_insecure(const char *ciphername)
+{
+ const mbedtls_cipher_info_t *cipher_kt =3D cipher_= get(ciphername);
+ = if (!cipher_kt)
+ = {
+ return tr= ue;
+ }
= +
+ return !(cipher_kt_block_size(ciphername) >= ;=3D 128 / 8
+#ifdef = MBEDTLS_CHACHAPOLY_C
= + || mbedtls_cipher_info_get_type(cipher_kt) =3D=3D MBEDTLS_CIP= HER_CHACHA20_POLY1305
+#endif
+ );
+}
+
+static mbedtls_cipher_mode_t
+cipher_kt_mode(const mbedtls_cipher_info_t *cipher_= kt)
+{
+ ASSERT(NULL !=3D cipher_kt);
+ return mbedtls_ci= pher_info_get_mode(cipher_kt);
+}
+=
+bool
+cipher_kt_mode_cbc(const char *ciphername= )
+{
+ const mbedtls_cipher_info_t *cip= her =3D cipher_get(ciphername);
+ return cipher && cipher_kt_mode(cipher) =3D=3D OPEN= VPN_MODE_CBC;
+}

+
+bool
+cipher_kt_mode_ofb_cfb(const char *ciphername)+{
+ const mbedtls_cipher_info_t *cipher =3D cip= her_get(ciphername);
= + return cipher
+ = && (cipher_kt_mode(cipher) =3D=3D OPENVPN_MODE_OFB=
+ || cipher_k= t_mode(cipher) =3D=3D OPENVPN_MODE_CFB);
+}
+bool
<= span style=3D"color: hsl(120, 100%, 40%);">+cipher_kt_mode_aead(const char = *ciphername)

+{
+ const mbedtls_cipher_= info_t *cipher =3D cipher_get(ciphername);
+ return cipher
+ && (cipher_kt_mode(cipher) =3D=3D O= PENVPN_MODE_GCM
+#ifd= ef MBEDTLS_CHACHAPOLY_C
+ || cipher_kt_mode(cipher) =3D=3D MBEDTLS_MODE_CHACHAPOLY=
+#endif
+ );

+}
+
+=
+/*
+ *
+ * Generic cipher context functions
+ *
+ */
+
+mbedtls_cipher= _context_t *
+cipher_= ctx_new(void)
+{
+ mbedtls_cipher_conte= xt_t *ctx;
+ ALLOC= _OBJ(ctx, mbedtls_cipher_context_t);
+ return ctx;
+}
+
+void
+cipher_ctx_free(mbedtls_cipher_context_= t *ctx)
+{
= + mbedtls_cipher_free(ctx);<= /span>
+ free(ctx);
+}
+
+void
+= cipher_ctx_init(mbedtls_cipher_context_t *ctx, const uint8_t *key, const ch= ar *ciphername,
+ = crypto_operation_t enc)
+{
+ = ASSERT(NULL !=3D ciphername && NULL !=3D ctx);
+ CLEAR(*ctx);
+
+ const mbedtls_cipher_info_t *kt =3D cipher_get(ciphernam= e);
+ ASSERT(kt);<= /span>
+ size_t key_bitle= n =3D mbedtls_cipher_info_get_key_bitlen(kt);
+
+ if (!mbed_ok(mbedtls_cipher_setup(ctx, kt)))
+ {
+ msg(M_FATAL, "mbed TLS cipher context in= it #1");
+ }<= /span>
+
+ if (!mbed_ok(mbedtls_cipher_setkey(= ctx, key, (int)key_bitlen, enc)))
+ {
+= msg(M_FATAL, "mbed TLS cipher set key");
+ }
+
+ if (mbedtls_cipher_info_get_mode(kt) =3D=3D MBEDTLS_MODE_CBC)
+ {
+ if (!mbed_ok(mbedtls_cipher_s= et_padding_mode(ctx, MBEDTLS_PADDING_PKCS7)))
+ {
+ msg(M_FATAL, "mbed TLS cipher set padding = mode");
+ = }
+ }
<= span style=3D"color: hsl(120, 100%, 40%);">+

+ /* make sure we used a big enough key */
+ ASSERT(mbedtls_cipher= _get_key_bitlen(ctx) <=3D key_bitlen);
+}
+
+int
<= span style=3D"color: hsl(120, 100%, 40%);">+cipher_ctx_iv_length(const mbed= tls_cipher_context_t *ctx)

+{
+ return = mbedtls_cipher_get_iv_size(ctx);
+}
+
+int
+cipher_ctx_get_tag(cipher_ctx_t *ctx, ui= nt8_t *tag, int tag_len)
+{
+ if (tag_l= en > SIZE_MAX)
+ = {
+ return 0= ;
+ }
+

+ if (!mbed_ok(mbedtls_cipher_write_tag(ctx, (uns= igned char *)tag, tag_len)))
+ {
+ = return 0;
+ }
+
+ return 1;
+}
+
+int
+cipher_ctx_block_size(co= nst mbedtls_cipher_context_t *ctx)
+{
+ = return (int)mbedtls_cipher_get_block_size(ctx);
+}
+
+int
+cipher_ctx_mode(const mb= edtls_cipher_context_t *ctx)
+{
+ ASSER= T(NULL !=3D ctx);
+
+ return mbedtls_ci= pher_get_cipher_mode(ctx);
+}
+
= +bool
+cipher_ctx_mode_cbc(const cipher_ctx_t *ctx)<= /span>
+{
+ return ctx && cipher_ctx_m= ode(ctx) =3D=3D OPENVPN_MODE_CBC;
+}
+
+
+bool
+cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx)<= br>+{
+ return ctx
+ && (cipher_ctx_mode(ctx) =3D=3D= OPENVPN_MODE_OFB
+ = || cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_CFB);
+}

+
+bool
+cipher_ct= x_mode_aead(const cipher_ctx_t *ctx)
+{
+ = return ctx
+ = && (cipher_ctx_mode(ctx) =3D=3D OPENVPN_MODE_GCM
+#ifdef MBEDTLS_CHACHAPOLY_C
+ || cipher_= ctx_mode(ctx) =3D=3D MBEDTLS_MODE_CHACHAPOLY
+#endif
+ );
+}
+
<= span style=3D"color: hsl(120, 100%, 40%);">+int

+cipher_ctx_reset(mbedtls_cipher_context_t *ctx,= const uint8_t *iv_buf)
+{
+ if (!mbed_= ok(mbedtls_cipher_reset(ctx)))
+ {
+ = return 0;
+ }=
+
+ if (!mbed_ok(mbedtls_cipher_set_iv= (ctx, iv_buf, (size_t)mbedtls_cipher_get_iv_size(ctx))))
+ {
+ return 0;
+ }
+
+ return 1= ;
+}
+
+int
+cipher_ctx_update_ad(cipher_ctx_t *ctx, const uint8_t *src, int src_len= )
+{
+ if (src_len > SIZE_MAX)
+ {
+ return 0;
+ }
+
= + if (!mbed_ok(mbedtls_cipher_update_ad(ctx, src, src_len)))
<= span style=3D"color: hsl(120, 100%, 40%);">+ {

+ return 0;
+ }
+
+ r= eturn 1;
+}+
+int
+cipher_ctx_update(mbedtls_cipher_context_t *ctx, uint8_t *dst, i= nt *dst_len, uint8_t *src,
+ int src_len)
+{
+= size_t s_dst_len =3D *dst_len;
+
+ = if (!mbed_ok(mbedtls_cipher_update(ctx, src, (size_t)src_len, dst, &s_d= st_len)))
+ {
+ return 0;=
+ }
+
+ *dst_len =3D s_dst_len;
+
+ return 1;
+}=
+
+int
+cipher_ctx_final(mbedtls_cipher_context_t *ctx, uint8_= t *dst, int *dst_len)
+{
+ size_t s_dst= _len =3D *dst_len;
+<= /span>
+ if (!mbed_ok(mbe= dtls_cipher_finish(ctx, dst, &s_dst_len)))
+ {
+ return 0;
+ }
+
+ *dst_len =3D s_dst= _len;
+
+ return 1;

+}
+
+i= nt
+cipher_ctx_final_= check_tag(mbedtls_cipher_context_t *ctx, uint8_t *dst, int *dst_len, uint8_= t *tag,
+ = size_t tag_len)
+{
+ siz= e_t olen =3D 0;
+
+ if (MBEDTLS_DECRYPT= !=3D mbedtls_cipher_get_operation(ctx))
+ {
+ return 0;
+ }
++ if (tag_len > SIZE_MA= X)
+ {
<= span style=3D"color: hsl(120, 100%, 40%);">+ return 0;

+ }

+
+ if (!mbed_ok(mbedtls_cipher_finish(ctx, dst, &olen)))
+ {
+ msg(D_CRYPT_ERRORS, "%s: = cipher_ctx_final() failed", __func__);
+ return 0;
+ }
+
+ if (ole= n > INT_MAX)
+ = {
+ return 0;<= /span>
+ }
+ *dst_len =3D olen;

<= span style=3D"color: hsl(120, 100%, 40%);">+

+ if (!mbed_ok(mbedtls_cipher_check_tag(ctx, (co= nst unsigned char *)tag, tag_len)))
+ {
+ return 0;
+= }
+
+ return 1;

+}
+
+#= if defined(__GNUC__) || defined(__clang__)
+#pragma GCC diagnostic pop
+#endif
+
+/*=
+ *
+ * Generic message digest informatio= n functions
+ *
+ */
+
+
+stat= ic const mbedtls_md_info_t *
+md_get(const char *digest)
+{
+ = const mbedtls_md_info_t *md =3D NULL;
+ ASSERT(digest);
+
= + md =3D mbedtls_md_info_from_string(digest);
+ if (!md)
+ {
+ msg(M_FATAL, "Message hash algorithm '%s' not = found", digest);
+ }
+ if (mbed= tls_md_get_size(md) > MAX_HMAC_KEY_LENGTH)
+ {
+ msg(M_FATAL,
+ "Message hash algorithm '%s' uses a d= efault hash size (%d bytes) which is larger than " PACKAGE_NAME=
+ "'s c= urrent maximum hash size (%d bytes)",
+ digest, mbedtls_md_get_size(md), MAX_HMA= C_KEY_LENGTH);
+ }=
+ return md;
+}
+
+bool
+= md_valid(const char *digest)
+{
+ const= mbedtls_md_info_t *md =3D mbedtls_md_info_from_string(digest);
<= span style=3D"color: hsl(120, 100%, 40%);">+ return md !=3D NULL;
=
+}
+
+const char *
+md_kt_name(const char *mdname)
+{
+ = if (!strcmp("none", mdname))
+ {
+ return "[null-digest]";
+ }
+ const mbedtls_md_info_t *kt =3D md_get(mdname);+ return mbedtls_md_get_na= me(kt);
+}
= +
+unsigned char
+md_kt_size(const char *mdname)
+{
+ if (!strcmp("none", mdname))
+ {
+ return 0;
+ }
+ const mbedtls_md_info_t *kt =3D md_get(mdname);
+ return mbedtls_md_get_size(kt);
+}
+
+/*
+= *
+ * Generic messag= e digest functions
+ = *
+ */
+

+int
+md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t = *dst)
+{
+ const mbedtls_md_info_t *kt = =3D md_get(mdname);

+= return 0 =3D=3D mbedtls_md(kt, src, src_len, dst);
+}
+
+mb= edtls_md_context_t *
= +md_ctx_new(void)
+{<= /span>
+ mbedtls_md_conte= xt_t *ctx;
+ ALLOC= _OBJ_CLEAR(ctx, mbedtls_md_context_t);
+ return ctx;
+}
+
+void
+md_ctx_free(mbedtls_md_context_t *ctx= )
+{
+ free(ctx);
+}
+
+voi= d
+md_ctx_init(mbedtl= s_md_context_t *ctx, const char *mdname)
+{
+ ASSERT(NULL !=3D ctx && NULL= !=3D kt);
++ mbedtls_md_init(ctx);
+ ASSERT(0 =3D=3D mb= edtls_md_setup(ctx, kt, 0));
+ ASSERT(0 =3D=3D mbedtls_md_starts(ctx));
+}
+
+voi= d
+md_ctx_cleanup(mbe= dtls_md_context_t *ctx)
+{
+ mbedtls_md= _free(ctx);
+}=
+
+int
+md_ctx_size(const mbedtls_md_context_t *ctx)
+{
+ if (NULL =3D=3D ctx)
+ {
+ return 0;
+ }
+ = return (int)mbedtls_md_get_size(mbedtls_md_info_from_ctx(ctx));
<= span style=3D"color: hsl(120, 100%, 40%);">+}

+
+void
+md_ctx_u= pdate(mbedtls_md_context_t *ctx, const uint8_t *src, size_t src_len)=
+{
+ ASSERT(0 =3D=3D mbedtls_md_update(ctx, s= rc, src_len));
+}
+
+void
+md_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst)
+{
+ ASSERT(0 =3D=3D mbedtls_md_finish(ct= x, dst));
+ mbedtl= s_md_free(ctx);
+}
+
+
+/*
+ *=
+ * Generic HMAC fun= ctions
+ *
= + */
+
+
+/*=
+ * TODO: re-enable dmsg fo= r crypto debug
+ */
+
+mbedtls_md_context_t *
+hmac_ctx_new(void)
+{
+ mbedtls_md_context_t *ctx;
+ ALLOC_OBJ(ctx, mbedtls_md_context_t);
+ return ctx;<= br>+}
+
+void
+hmac= _ctx_free(mbedtls_md_context_t *ctx)
+{
+ = free(ctx);
+}
+
+void
+hmac_ctx_init(mbedtls_md_context_t *ctx, const uint8_t *= key, const char *mdname)
+{
+ const mbe= dtls_md_info_t *kt =3D md_get(mdname);
+ ASSERT(NULL !=3D kt && NULL !=3D ctx);
+
+ mbedtls_md_init(ctx);
+ int key_len =3D mbedtls_md_get_siz= e(kt);
+ ASSERT(0 = =3D=3D mbedtls_md_setup(ctx, kt, 1));
+ ASSERT(0 =3D=3D mbedtls_md_hmac_starts(ctx, key, key_= len));
+
+ /* make sure we used a big e= nough key */

+ ASS= ERT(mbedtls_md_get_size(kt) <=3D key_len);
+}
+
+void=
+hmac_ctx_cleanup(mbedtls_m= d_context_t *ctx)
+{<= /span>
+ mbedtls_md_free(= ctx);
+}
+

+int
+hmac_ctx_size(mbedtls_md_context_t *ctx)
+{
+ if (NULL =3D=3D ctx)
+ {
+ return 0;
+= }
+ return mbe= dtls_md_get_size(mbedtls_md_info_from_ctx(ctx));
+}
+
+void
+hmac_ctx_reset(mbedtls_= md_context_t *ctx)
+{=
+ ASSERT(0 =3D=3D= mbedtls_md_hmac_reset(ctx));
+}
+<= br>+void
+hmac_ctx_update(mbedtls_md_context_t *ctx= , const uint8_t *src, int src_len)
+{
+ = ASSERT(0 =3D=3D mbedtls_md_hmac_update(ctx, src, src_len));
+}

+
+void
+hmac_ctx_fi= nal(mbedtls_md_context_t *ctx, uint8_t *dst)
+{
+ ASSERT(0 =3D=3D mbedtls_md_hmac_finish(ctx, dst));
+}

+
+int
+memcmp_cons= tant_time(const void *a, const void *b, size_t size)
+{
+ /* mbed TLS has a no const time memcmp function that it= exposes
+ * via = its APIs like OpenSSL does with CRYPTO_memcmp
+ * Adapt the function that mbedtls itself use= s in
+ * mbedtls_= safer_memcmp as it considers that to be safe */
+ volatile const unsigned char *A =3D (volati= le const unsigned char *)a;
+ volatile const unsigned char *B =3D (volatile const unsigned ch= ar *)b;
+ volatile= unsigned char diff =3D 0;
+
+ for (siz= e_t i =3D 0; i < size; i++)
+ {
+ = unsigned char x =3D A[i], y =3D B[i];
+ diff |=3D x ^ y;
+ }
+
+ r= eturn diff;
+}=
+
+#if defined(__GNUC__) || defined(__clang__)
+#pragma GCC diagnosti= c push
+#pragma GCC d= iagnostic ignored "-Wconversion"
+#endif
+
+/*=
+ * Generate the hash requi= red by for the \c tls1_PRF function.
+ *
+= * @param md_kt Message digest to use
+ * @param sec Secret to base the hash o= n
+ * @param sec_len = Length of the secret
+ * @param seed Seed to hash
+ * @param seed_len Length of the seed+ * @param out Outp= ut buffer
+ * @param = olen Length of the output buffer
+ */
+static void
+tl= s1_P_hash(const mbedtls_md_info_t *md_kt, const uint8_t *sec, size_t sec_le= n, const uint8_t *seed,
+ size_t seed_len, uint8_t *out, size_t olen)
+{

+ struct gc_arena gc =3D gc_new();
+ uint8_t A1[MAX_HMAC_KEY_LENGTH];=
+
+#ifdef ENABLE_DEBUG
+ /* used by the D_SHOW_KEY_SOURCE, = guarded with ENABLE_DEBUG to avoid unused
+ * variables warnings if compiled with --enable-s= mall */
+ const si= ze_t olen_orig =3D olen;
+ const uint8_t *out_orig =3D out;
+#endif
+
+ hmac_c= tx_t *ctx =3D hmac_ctx_new();
+ hmac_ctx_t *ctx_tmp =3D hmac_ctx_new();
+
+ dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s",= format_hex(sec, sec_len, 0, &gc));
+ dmsg(D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s&= quot;, format_hex(seed, seed_len, 0, &gc));
+
+ unsigned int chunk =3D mbedtls_md_get_size(md_kt);
<= span style=3D"color: hsl(120, 100%, 40%);">+ unsigned int A1_len =3D mbe= dtls_md_get_size(md_kt);

+
+ /* This is= the only place where we init an HMAC with a key that is not
+ * equal to its size, therefor= e we init the hmac ctx manually here */

+ mbedtls_md_init(ctx);
+ ASSERT(0 =3D=3D mbedtls_md_setup(ctx, md_kt, = 1));
+ ASSERT(0 = =3D=3D mbedtls_md_hmac_starts(ctx, sec, sec_len));
+
+ mbedtls_md_init(ctx_tmp);
+ ASSERT(0 =3D=3D mbedtls_md_setup(ctx_tmp, md_kt, = 1));
+ ASSERT(0 = =3D=3D mbedtls_md_hmac_starts(ctx_tmp, sec, sec_len));
+
+ hmac_ctx_update(ctx, seed, seed_len);
+ hmac_ctx_final(ctx, A1);+
+ for (;;)
+ {
+ hmac_ctx_reset(ctx);
+ hmac_ctx_reset(ctx_tmp);
+ hmac_ctx_update(ctx, A1, A1_len);
+ hmac_ctx_update(= ctx_tmp, A1, A1_len);
+ hmac_ctx_update(ctx, seed, seed_len);
+
+ if (olen > chunk)
+ {
+ hmac_ctx_final(ctx, out);
+ out +=3D chunk;
+ olen -=3D chunk;
+ hmac_ctx_final(ctx_t= mp, A1); /* calc the next A1 value */

+ }
+ else /* last one */
<= span style=3D"color: hsl(120, 100%, 40%);">+ {

+ hmac_ctx_final(ctx, A1);
+ memcpy(out, = A1, olen);
+ = break;
+ }<= /span>
+ }
+ hmac_ctx_cleanup(ctx);
<= br>+ hmac_ctx_free(ctx);
+ hmac_ctx_cleanup(ct= x_tmp);
+ hmac_ctx= _free(ctx_tmp);
+ = secure_memzero(A1, sizeof(A1));
+
+ dms= g(D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex(out_orig, = olen_orig, 0, &gc));
+ gc_free(&gc);
+}
+
= +/*
+ * Use the TLS PRF function for generating data= channel keys.
+ * Th= is code is based on the OpenSSL library.
+ *
+ * TLS generates keys as such:
+ *
+ *= master_secret[48] =3D PRF(pre_master_secret[48], "master secret"= ,
+ * = ClientHello.random[32] + ServerHello.random[32])
+ *
+ * key_block[] =3D PRF(SecurityParameters.master_secre= t[48],
+ * = "key expansion",
+ * SecurityParameters.server_random[32] +
+ * Secur= ityParameters.client_random[32]);
+ *
+ * = Notes:
+ *
= + * (1) key_block contains a fu= ll set of 4 keys.
+ *= (2) The pre-master secret is generated by the client.
+ */
+bool
+ssl_tls1_PRF(const uint8_t *label, size_t label_len, const uint8_t *sec= , size_t slen, uint8_t *out1,
+ size_t olen)
+{
+ = struct gc_arena gc =3D gc_new();
+ const md_kt_t *md5 =3D md_get("MD5");+ const md_kt_t *sha1 =3D = md_get("SHA1");
+
+ uint8_t *= out2 =3D (uint8_t *)gc_malloc(olen, false, &gc);
+
+ size_t len =3D slen / 2;
+ const uint8_t *S1 =3D sec;
+ const uint8_t *S2 =3D &(sec[len]= );
+ len +=3D (sle= n & 1); /* add for odd, make longer */
+
+ tls1_P_hash(md5, S1, len, label, label_len, out1, olen);
= + tls1_P_hash(sha1, S2, len,= label, label_len, out2, olen);
+
+ for= (size_t i =3D 0; i < olen; i++)
+ {
+ out1[i] ^=3D out2[i];
+ }
+
+ secure_memzero(ou= t2, olen);
++ dmsg(D_SHOW_KEY_SOURCE, = "tls1_PRF out[%zu]: %s", olen, format_hex(out1, olen, 0, &gc)= );
+
+ gc_free(&gc);
+ return true;

+}
+
= +#if defined(__GNUC__) || defined(__clang__)
+#pragma GCC diagnostic pop
+#endif
+
+#endif /* MBEDTLS_VERSION_NUMBER < 0x040000 */
+#endif /* ENABLE_CRYPTO_MBEDTLS */=
diff --git a/src/openvpn/crypto_mbedtls_legacy.h b/src/openvpn/cr= ypto_mbedtls_legacy.h
new file mode 100644
= index 0000000..71514fc
--- /dev/null
+++ b/= src/openvpn/crypto_mbedtls_legacy.h
@@ -0,0 +1,148 @@
+/*
+ * OpenVPN -- An application to securely= tunnel IP networks
+= * over a single TCP/UDP port, with support for SSL/TLS-based
+ * sessio= n authentication and key exchange,
+ * packet encryption, packet authentication, and=
+ * pack= et compression.
+ *
+ * Copyright (C) 200= 2-2025 OpenVPN Inc <sales@...515...>
+ * Copyright (C) 2010-2021 Sentyron B.V. <openvp= n@...2918...>
+ *<= /span>
+ * This program is = free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General= Public License version 2
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will= be useful,
+ * but = WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A= PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Genera= l Public License along
+ */
+

+/**
+ * @file
+ * Da= ta Channel Cryptography mbed TLS-specific backend interface
+ */

+
+#ifndef CRYPTO_MBEDTLS_H_
+#define CRYPTO_MBEDTLS_H_
+
+#i= nclude <stdbool.h>
+#include <mbedtls/cipher.h>
+#include <mbedtls/md.h>
+#include <mbedtls/ctr_drbg.h>
= +
+/** Generic message digest key type %context. */<= /span>
+typedef mbedtls_md_i= nfo_t md_kt_t;
+
+/** Generic cipher %cont= ext. */
+typedef mbed= tls_cipher_context_t cipher_ctx_t;
+
+/** = Generic message digest %context. */
+typedef mbedtls_md_context_t md_ctx_t;
+
+/** Generic HMAC %context. */
+typedef mbedtls_md_context_t hmac_ctx_t;+
+/* Use a dummy type for the provider */<= br>+typedef void provider_t;
+
+/** Maximum length of an IV */
= +#define OPENVPN_MAX_IV_LENGTH = MBEDTLS_MAX_IV_LENGTH
+
+/** Cipher is in = CBC mode */
+#define = OPENVPN_MODE_CBC MBEDTLS_MODE_CBC
+
+/** C= ipher is in OFB mode */
+#define OPENVPN_MODE_OFB MBEDTLS_MODE_OFB
+
+/** Cipher is in CFB mode */
+#define OPENVPN_MODE_CFB MBEDTLS_MODE_CFB
+
+/** Cipher is in GCM mode */
+#define OPENVPN_MODE_GCM MBEDTLS_MODE_GCM
+
+typedef mbedtls_operation_t crypto_operation= _t;
+
+/** Cipher should encrypt */
=
+#define OPENVPN_OP_ENCRYPT= MBEDTLS_ENCRYPT
+
+/** Cipher should decr= ypt */
+#define OPENV= PN_OP_DECRYPT MBEDTLS_DECRYPT
+
+#define M= D4_DIGEST_LENGTH 16
+#define SHA_DIGEST_LENGTH 20
+#define SHA256_DIGEST_LENGTH 32
+
+/**
+ * Returns a singleton instance of the mbed TLS random number generator= .
+ *
+ * For PolarSSL/mbed TLS 1.1+, this= is the CTR_DRBG random number generator. If it

+ * hasn't been initialised yet, the RNG wil= l be initialised using the default
+ * entropy sources. Aside from the default platform entropy = sources, an
+ * addit= ional entropy source, the HAVEGE random number generator will also be
+ * added. During initiali= sation, a personalisation string will be added based
+ * on the time, the PID, and a pointer to= the random context.
= + */
+mbedtls_ctr_drb= g_context *rand_ctx_get(void);
+
+#ifdef E= NABLE_PREDICTION_RESISTANCE
+/**
+ * Enabl= e prediction resistance on the random number generator.
+ */
+void rand_ctx_enable_prediction_resistance(void);
+
+#endif
+
+/= **
+ * Log the suppli= ed mbed TLS error, prefixed by supplied prefix.
+ *
+ * @param flags Flags to indicate error type and priorit= y.
+ * @param errval = mbed TLS error code to convert to error message.
+ * @param prefix Prefix to mbed = TLS error message.
+ = *
+ * @returns true i= f no errors are detected, false otherwise.
+ */
+bool mbed_log_err(unsigned int flags, int errval, const char *prefix= );
+
+/**
+ * Log the supplied mbed TLS error, prefixed by func= tion name and line number.
+ *
+ * @param = flags Flags to indicate error type and priority.
+ * @param errval mbed TLS error= code to convert to error message.
+ * @param func Function name where error was report= ed.
+ * @param line = Line number where error was reported.
+ *
+ * @returns true if no errors are detected, false otherwise.
+ */
+bool mbed_log_func_line(unsigned int flag= s, int errval, const char *func, int line);
+
+/** Wraps mbed_log_func_line() to prevent function calls for non-error= s */
+static inline b= ool
+mbed_log_func_li= ne_lite(unsigned int flags, int errval, const char *func, int line)<= br>+{
+ if (errval)
+ {
+ return mbed_log_func_line(flags, errval, func, line);
+ }
+ return true;

+}
+
+= /**
+ * Check errval = and log on error.
+ *=
+ * Convenience wrap= per to put around mbed TLS library calls, e.g.
+ * if (!mbed_ok (mbedtls_ssl_func())) return 0= ;
+ * or
+ * ASSERT (mbed_ok (mbedtls_ss= l_func()));

+ *
+ * @param errval m= bed TLS error code to convert to error message.
+ *
+ * @returns true if no errors are detected, false otherwise.
+ */
+#define mbed_ok(errval) mbed_log_func_l= ine_lite(D_CRYPT_ERRORS, errval, __func__, __LINE__)
+
+#endif /* CRYPTO_MBEDTLS_H_ */
diff --git a/= src/openvpn/mbedtls_compat.h b/src/openvpn/mbedtls_compat.h
index 540f370..f904184 100644

--- a/src/openvpn/mbedtls_co= mpat.h
+++ b/src/openvpn/mbedtls_compat.h
@= @ -34,6 +34,16 @@

#include "errleve= l.h"

+#include <mbedtls/asn1.h>
+#include <mbedtls/pk.h>
+
+#if MBEDTLS_VERSION_NUMBER < 0x04000000
+#include <mbedtls/ctr_drbg.h>
+#include "crypto_mbe= dtls_legacy.h"
+= #else
+#include <m= bedtls/oid.h>
+#en= dif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
+
#ifdef HAVE_PSA_CRYPTO_H
#include <psa/crypto.h>
#endif<= br>@@ -51,4 +61,176 @@
#endif
}

+#if M= BEDTLS_VERSION_NUMBER >=3D 0x04000000
+typedef struct
+{
+ = const char *name;
+= uint16_t tls_id;
= +} mbedtls_ecp_curve_info;
+
+static inlin= e int
+mbedtls_oid_ge= t_attr_short_name(const mbedtls_asn1_buf *oid, const char **desc)+{
+ /* The relevant OIDs all have equal length.= */
+ if (oid->= tag !=3D MBEDTLS_ASN1_OID || oid->len !=3D strlen(MBEDTLS_OID_AT_CN))
+ {
+ *desc =3D NULL;
+ return -1;

+ }

+
+ if (memcmp(oid->p, MBEDTLS_OID_AT_CN, oid->len) =3D=3D 0= )
+ {
+ *desc =3D "CN"= ;

+ }
+ else if (memcmp(oid->p, M= BEDTLS_OID_AT_SUR_NAME, oid->len) =3D=3D 0)

+ {
+ *desc =3D "SN";
+ }
+ else if (memcmp(oid->p, MBEDTLS_OID_AT_SERIAL_NUMBER, o= id->len) =3D=3D 0)
+ {
+ *des= c =3D "serialNumber";
+ }
+ = else if (memcmp(oid->p, MBEDTLS_OID_AT_COUNTRY, oid->len) =3D=3D 0)=
+ {
+ *desc =3D "C";<= /span>
+ }
+ else if (memcmp(oid->p, MBE= DTLS_OID_AT_LOCALITY, oid->len) =3D=3D 0)

+ {
+ *desc =3D "L";
+ }
+ else if (memcmp(oid->p, MBEDTLS_OID_AT_STATE, oid->len)= =3D=3D 0)
+ {
+ *desc =3D "= ;ST";
+ }
+ else if (memcmp(oid= ->p, MBEDTLS_OID_AT_ORGANIZATION, oid->len) =3D=3D 0)
+ {

+ *desc =3D "O";
+ }
+ else if (memcmp(oid->p, MBEDTLS_OID_AT_ORG_= UNIT, oid->len) =3D=3D 0)
+ {
+ = *desc =3D "OU";
+ }
+ e= lse if (memcmp(oid->p, MBEDTLS_OID_AT_TITLE, oid->len) =3D=3D 0)
+ {
+ *desc =3D "title";
+ }
+ else if (memcmp(oid->p, MBED= TLS_OID_AT_POSTAL_ADDRESS, oid->len) =3D=3D 0)

+ {
+ *desc =3D "postalAddress";
+ }

+ else if (memcmp(oid->p, MBEDTLS_OID_AT_PO= STAL_CODE, oid->len) =3D=3D 0)
+ {
+= *desc =3D "postalCode";
+ }
+ else if (memcmp(oid->p, MBEDTLS_OID_AT_GIVEN_NAME, oid->l= en) =3D=3D 0)
+ {<= /span>
+ *desc =3D &q= uot;GN";
+ }<= /span>
+ else if (memcmp(= oid->p, MBEDTLS_OID_AT_INITIALS, oid->len) =3D=3D 0)
+ {
+ *desc =3D "initials";
= + }
+ else if (memcmp(oid->p, MBEDTLS_OID_A= T_GENERATION_QUALIFIER, oid->len) =3D=3D 0)
+ {
+ *desc =3D "generationQualifier";
<= span style=3D"color: hsl(120, 100%, 40%);">+ }

+ else if (memcmp(oid->p, MBEDTLS_OID_AT= _UNIQUE_IDENTIFIER, oid->len) =3D=3D 0)
+ {
+ *desc =3D "uniqueIdentifier";
+ }
+ else if (memcmp(oid->p, MBEDTLS_OID_AT_DN_QUA= LIFIER, oid->len) =3D=3D 0)
+ {
+ = *desc =3D "dnQualifier";
+ }
+ else if (memcmp(oid->p, MBEDTLS_OID_AT_PSEUDONYM, oid->len)= =3D=3D 0)
+ {
+ *desc =3D "= ;pseudonym";
+ = }
+ else<= br>+ {
+ *desc =3D NULL;
+ return -1;
+ }
+ return 0;
+}
+<= /span>
+static inline int
+mbedtls_oid_get_extend= ed_key_usage(const mbedtls_asn1_buf *oid, const char **desc)
+{

+ /* The relevant OIDs all have equal length. */
+ if (oid->tag != =3D MBEDTLS_ASN1_OID || oid->len !=3D strlen(MBEDTLS_OID_SERVER_AUTH))
+ {
+ *desc =3D NULL;

<= span style=3D"color: hsl(120, 100%, 40%);">+ return -1;

+ }

+
+ if (memcmp(oid->p, MBEDTLS_OID_SERVER_AUTH, oid->len) = =3D=3D 0)
+ {
+ *desc =3D "= TLS Web Server Authentication";
+ }
+ {<= br>+ *desc =3D "TLS= Web Client Authentication";
+ }
+= else if (memcmp(oid->p, MBEDTLS_OID_CODE_SIGNING, oid->len) =3D= =3D 0)
+ {<= br>+ *desc =3D "Cod= e Signing";
+ = }
+ else if (memc= mp(oid->p, MBEDTLS_OID_EMAIL_PROTECTION, oid->len) =3D=3D 0)+ {
+ *desc =3D "E-mail Protection= ";
+ }=
+ else if (memcmp(oid-&g= t;p, MBEDTLS_OID_TIME_STAMPING, oid->len) =3D=3D 0)
+ {
+ *desc =3D "Time Stamping";+ }
+ else if (memcmp(oid->p, MBEDTLS_OI= D_OCSP_SIGNING, oid->len) =3D=3D 0)
+ {
+ *desc =3D "OCSP Signing";
+ }
+ else
+ {
+ *d= esc =3D NULL;
+ = return -1;
+ }
+
+ return 0;
+}
+#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */+
+/* Some functions that operate on private keys u= se randomness to protect against
+ * side channels. In Mbed TLS 4, they automatically use the RN= G in the PSA
+ * libr= ary, but in Mbed TLS 3, they require them as explicit arguments. */<= br>+static inline int+mbedtls_compat_pk_parse_key(m= bedtls_pk_context *ctx,
+ const unsigned char *key, size_t keylen,
+ = const unsigned char *pwd, size_t pwdlen)
+{
+#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000
+ return mbedtls_pk_parse_key(ctx, key= , keylen, pwd, pwdlen);
+#else
+ return= mbedtls_pk_parse_key(ctx, key, keylen, pwd, pwdlen, mbedtls_ctr_drbg_rando= m, rand_ctx_get());
+= #endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
+}
+
+sta= tic inline int
+mbedt= ls_compat_pk_parse_keyfile(mbedtls_pk_context *ctx, const char *path, const= char *password)
+{
+#if MBEDTLS_VERSION_N= UMBER >=3D 0x04000000
+ return mbedtls_pk_parse_keyfile(ctx, path, password);
+#else

+ return mbedtls_pk_parse_keyfile(ctx, path,= password, mbedtls_ctr_drbg_random, rand_ctx_get());
+#endif /* MBEDTLS_VERSION_NUMBER < 0x0= 4000000 */
+}<= br>+
+static inline int
+mbedtls_compat_pk_check_pair(const mbedtls_pk_co= ntext *pub, const mbedtls_pk_context *prv)
+{
+#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000
+ return mbedtls_pk_check_pair(pub, prv);<= /span>
+#else
+ return mbedtls_pk_check_pair(p= ub, prv, mbedtls_ctr_drbg_random, rand_ctx_get());

+#endif /* MBEDTLS_VERSION_NUMBER < 0x0400= 0000 */
+}
= +
#endif /* MB= EDTLS_COMPAT_H_ */
diff --git a/src/openvpn/ssl_mbedtls.c b= /src/openvpn/ssl_mbedtls.c
index 3440319..a178e0c 100644
--- a/src/openvpn/ssl_mbedtls.c
+++ b/src/ope= nvpn/ssl_mbedtls.c
@@ -93,7 +93,9 @@
A= SSERT(NULL !=3D ctx);
CLEAR(*ctx);

+#if MBEDTLS_VERSION_N= UMBER < 0x04000000
ALLOC_OBJ_CLEAR(ctx->dhm_ctx,= mbedtls_dhm_context);
+#if MBEDTLS_VERSION_NUMBER < 0x04000000
ALLO= C_OBJ_CLEAR(ctx->dhm_ctx, mbedtls_dhm_context);
+#endif
ALLOC_OBJ_CLEAR(= ctx->ca_chain, mbedtls_x509_crt);

= ctx->endpoint =3D MBEDTLS_SSL_IS_CLIENT;
@@ -128,8 +132= ,10 @@
mbedtls_x509_crt_free(ctx->crt_chain);
free(ctx->crt_chain);
+#if MBEDTLS_VERSION_NUMBER &= lt; 0x04000000
mbedtls_dhm_free(ctx->dhm_ctx);<= /span>
free(ctx->dhm_ctx);
+#endif

= mbedtls_x509_crl_free(ctx->crl);
free(ctx-&g= t;crl);
@@ -346,6 +352,34 @@
}<= br> }

+#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000
+static const mbedtls_ecp_curve_info ecp= _curve_info_table[] =3D {
+ /* TODO: Fill out the table. */
+ { "secp256r1", MBEDTLS_SSL_IANA_TLS_GRO= UP_SECP256R1 },
+ = { "secp384r1", MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 },
= + { "X25519", MBED= TLS_SSL_IANA_TLS_GROUP_X25519 },
+ { "ffdhe2048", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE2= 048 },
+ { "f= fdhe3072", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE3072 },
+ { "ffdhe4096", MBEDTLS_SS= L_IANA_TLS_GROUP_FFDHE4096 },
+ { "ffdhe6144", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE6144= },
+ { "ffdh= e8192", MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE8192 },
+};
+static const size_t ecp_curve_info_table_items =3D sizeof(= ecp_curve_info_table) / sizeof(mbedtls_ecp_curve_info);
+
+static const mbedtls_ecp_curve_info *
+mbedtls_ecp_curve_info_from_name(const c= har *name)
+{<= br>+ for (size_t i =3D 0; i = < ecp_curve_info_table_items; i++)
+ {
+ if (strcmp(name, ecp_curve_info_table[i].name) =3D=3D 0)=
+ {
+ return &ecp_curve_in= fo_table[i];
+ = }
+ }
<= span style=3D"color: hsl(120, 100%, 40%);">+ return NULL;

+}

+#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 = */
+
= void
tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, con= st char *groups)
{
@@ -407,6 +441,7 @@
void
tls_ctx_load_dh_params(struct tls_root_= ctx *ctx, const char *dh_file, bool dh_inline)
{+#if MBEDTLS_VERSION_NUMBER &l= t; 0x04000000
if (dh_inline)
{
if (!mbed_ok(mbedtls_dhm_parse_dhm(ctx->dhm_ctx, = (const unsigned char *)dh_file,
@@ -425,6 +460,9 @@<= br>
msg(D_TLS_DEBUG_LOW, "Diffie-Hellman i= nitialized with " counter_format " bit key",
(counter_type)mbedtls_dhm_get_bitlen(ctx->dhm_ctx));
+#else
+ msg(M_FATAL, "Mbed TLS 4 only su= pports pre-defined Diffie-Hellman groups.");
+#endif /* MBEDTLS_VERSION_NUMBER < 0x04000= 000 */
}

void@@ -498,29 +536,26 @@

if (pri= v_key_inline)
{
- status =3D mbedtls_pk_parse_key(ctx->priv_key, (c= onst unsigned char *)priv_key_file,
- strlen(priv_key_file) += 1, NULL, 0,
- = mbedtls_ctr_drbg_random, rand_ctx_get());
+ status =3D mbedt= ls_compat_pk_parse_key(ctx->priv_key, (const unsigned char *)priv_key_fi= le,
+ = strlen(priv_key_file) + 1, NULL, 0);
if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED =3D= =3D status)
{
char pa= ssbuf[512] =3D { 0 };
pem_password_callback(pa= ssbuf, 512, 0, NULL);
-= status =3D mbedtls_pk_parse_key(
+ status =3D mbedtls_compat_pk_parse_key= (
ctx->priv_key, (const unsigned char *= )priv_key_file, strlen(priv_key_file) + 1,
- (unsigned char *)passbuf, strlen(passb= uf), mbedtls_ctr_drbg_random, rand_ctx_get());
+ (unsigned char *)passbuf, strlen= (passbuf));
}
}
else

{
- status =3D mbedtls_pk_parse_keyfile(ctx->priv_key,= priv_key_file, NULL,
-= mbedtls_ctr_drbg_random, rand_ctx= _get());
+ sta= tus =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv_key_file, NU= LL);
if (MBEDTLS_ERR_PK_PASSWORD_REQUIRED =3D=3D s= tatus)
{
char passbuf= [512] =3D { 0 };
pem_password_callback(passbuf= , 512, 0, NULL);
- = status =3D mbedtls_pk_parse_keyfile(ctx->priv_key, priv_key_file,= passbuf,
- = mbedtls_ctr_drbg_random, rand_ctx_get());=
+ status = =3D mbedtls_compat_pk_parse_keyfile(ctx->priv_key, priv_key_file, passbu= f);
}
}
= if (!mbed_ok(status))
@@ -536,8 +571,7 @@
= return 1;
}

- if (!mbed_ok(mbedtls_pk_check_pair= (&ctx->crt_chain->pk, ctx->priv_key,
- mbedtls_= ctr_drbg_random, rand_ctx_get())))
+ if (!mbed_ok(mbedtls_compat_pk_check_pair(&ctx->c= rt_chain->pk, ctx->priv_key)))
{
msg(M_WARN, "Private key does not match the certificate"= ;);

return 1;
@@ -574,6 +608,10 @@=
mbedtls_md_type_t md_alg, unsigned in= t hashlen, const unsigned char *hash,
= unsigned char *sig)
{
+#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000
= + msg(M_WARN, "external= _pkcs1_sign is not implemented for Mbed TLS 4.");
+ return 1;
+#else
struct external_con= text *const ctx =3D ctx_voidptr;
int rv;
uint8_t *to_sign =3D NULL;

@@ -658,6 +696,7 @@
done:
free(to_sign);
= return rv;
+#endif /= * MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */
}
static inline size_t
@@ -672,6 +7= 11,10 @@
tls_ctx_use_external_signing_func(struct tls_root= _ctx *ctx, external_sign_func sign_func,
= void *sign_ctx)
{
+#if MBEDTLS_VERSION_NUMBER >=3D 0x0400= 0000
+ msg(M_WARN,= "tls_ctx_use_external_signing_func is not implemented for Mbed TLS 4.= ");
+ return = 1;
+#else
<= span> ASSERT(NULL !=3D ctx);


if = (ctx->crt_chain =3D=3D NULL)
@@ -699,6 +742,7 @@<= br> }

return 0;
= +#endif /* MBEDTLS_VERSION_NUMB= ER >=3D 0x04000000 */
}

#ifdef ENABLE_MANAGEMENT

@@ -936,6 +980,7 @@
= void
tls_ctx_personalise_random(struct tls_root_ctx= *ctx)
{
+#if MBEDTLS_VERSION_NUMBER < 0x04000000
stati= c char old_sha256_hash[32] =3D { 0 };
unsigned char sh= a256_hash[32] =3D { 0 };
mbedtls_ctr_drbg_context *cd_= ctx =3D rand_ctx_get();
@@ -958,6 +1003,7 @@
memcpy(old_sha256_hash, sha256_hash, sizeof(old_sha256_hash)= );

}
}
+#endif /* MBEDTLS_VERSION_NUMBER < 0x0= 40000 */
}

#if defined(= __GNUC__) || defined(__clang__)
@@ -1067,7 +1113,9 @@
}
#endif
mbedtls_ssl_= conf_dbg(ks_ssl->ssl_config, my_debug, NULL);
+#if MBEDTLS_VERSION_NUMBER < 0x04000000
mbedtls_ssl_conf_rng(ks_ssl->ssl_config, mbedtls_ctr_d= rbg_random, rand_ctx_get());
+#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */

mbedtls_ssl_conf_cert_profile(ks_ssl->ssl_confi= g, &ssl_ctx->cert_profile);

@@ -10= 98,12 +1146,14 @@
#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTI= NG */

/* Initialise authentication i= nformation */
+#if MB= EDTLS_VERSION_NUMBER < 0x04000000
if (is_server)
{
mbed_ok(mbedtls_ssl_conf_dh_p= aram_ctx(ks_ssl->ssl_config, ssl_ctx->dhm_ctx));
= }
+#endif
=
- mbed_ok(mb= edtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx->crt_chain, ssl_c= tx->priv_key));
+ = (void)mbed_ok(mbedtls_ssl_conf_own_cert(ks_ssl->ssl_config, ssl_ctx-&= gt;crt_chain, ssl_ctx->priv_key));

= /* Initialise SSL verification */
if (session->op= t->ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
@@ -1158,7= +1208,7 @@
/* Initialise SSL context */
ALLOC_OBJ_CLEAR(ks_ssl->ctx, mbedtls_ssl_context);

mbedtls_ssl_init(ks_ssl->ctx);

- mbed_ok(mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl-&g= t;ssl_config));
+ = (void)mbed_ok(mbedtls_ssl_setup(ks_ssl->ctx, ks_ssl->ssl_config));
/* We do verification in our own callback depending on t= he
* exact configuration. We do not rely on the defau= lt hostname
* verification. */
@@ -14= 54,6 +1504,7 @@
void
show_available_curve= s(void)
{
+#if MBEDTLS_VERSION_NUMBER < 0x04000000
cons= t mbedtls_ecp_curve_info *pcurve =3D mbedtls_ecp_curve_list();

if (NULL =3D=3D pcurve)
@@ -1468= ,6 +1519,9 @@
printf("%s\n", pcurve->= name);
pcurve++;
}
= +#else
+ msg(M_FATAL, "Mbed TLS 4 has no mec= hanism to list supported curves.");
+#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
}

const char *
= diff --git a/src/openvpn/ssl_mbedtls.h b/src/openvpn/ssl_mbedtls.h
index 8380a116..882a8e7 100644
--- a/src/open= vpn/ssl_mbedtls.h
+++ b/src/openvpn/ssl_mbedtls.h@@ -116,7 +116,9 @@

int endpo= int; /**< Whether or not this is a server or a = client */

+#if MBEDTLS_VERSION_NUMBER < 0x04000000
mbe= dtls_dhm_context *dhm_ctx; /**< Diffie-Helmann-Merkle context *= /
+#endif
<= span> mbedtls_x509_crt *crt_chain; /**< Local Certificate = chain */

mbedtls_x509_crt *ca_chain; /**<= ; CA chain for remote verification */
mbedtls_pk_conte= xt *priv_key; /**< Local private key */
diff --= git a/src/openvpn/ssl_verify_mbedtls.c b/src/openvpn/ssl_verify_mbedtls.c
index 250c806..2b5a0ca 100644
--- a/src/open= vpn/ssl_verify_mbedtls.c
+++ b/src/openvpn/ssl_verify_mbedt= ls.c
@@ -34,13 +34,22 @@

= #if defined(ENABLE_CRYPTO_MBEDTLS)

+#include <mbedtls/version.h>=
+
+#if MBEDTLS_VERSION_NUMBER < 0x04000000
+#include "crypto_= mbedtls_legacy.h"
+#include <mbedtls/sha1.h>
+#else
#include "crypto_m= bedtls.h"
+#endi= f
+
+#include "mbedtls_compat.h"=
+
#= include "ssl_verify.h"
#include <mbedtls/asn1= .h>
#include <mbedtls/error.h>
-#include <mbedtls/bignum.h>=
#include <mbedtls/oid.h>
-#include <mbedtls/sha1.h>

#define MAX_SUBJECT_LENGTH 256

@@ -168,11 +177,139 @@

return SUCCESS;
}


+#if MBEDTLS_VERSION_NUMBER >=3D 0x04000000
+/* Mbed TLS 4 has no function to print the ce= rtificate serial number and does
+ * not expose the bignum functions anymore. So in order to wri= te the serial
+ * num= ber as a decimal string, we implement bignum % 10 and bignum / 10. */
+static char
+bignum_mod_10(const uint8_t *bign= um, size_t bignum_length)

+{
+ int resu= lt =3D 0;
+ for (s= ize_t i =3D 0; i < bignum_length; i++)
+ {
+ result =3D (result * 256) % 10;
+ result =3D (result + bignum[i]) % 10;
+ }
+ return (char)result;

= +}
+
+/* Divide bignum by 10 rounded down, in place. */
+static void
+bignum_div_10(uint8_t *bignum, size_t *bignum= _length)
+{+ /*
+ * Some intuition for the algorithm b= elow:
+ *<= br>+ * We want to calculate=
+ *
+ * (bignum[0] * 256^n + = bignum[1] * 256^(n-1) + ... + bignum[n]) / 10.

+ *
+ * Let remainder =3D bignum[0] % 10 and carry =3D remaind= er * 256.
+ * The= n we can write the above as
+ *
+ = * (bignum[0] / 10) * 256^n
+ * + ((carry + bignum[1]) * 256^(n-1) + ... + bignum[n= ]) / 10.
+ *
+ * So now we have th= e first byte of our result. The second byte will be
+ * (carry + bignum[1]) / 10. Note tha= t this fits into one byte because
+ * 0 <=3D remainder < 10. We calculate the next rem= ainder and carry as
+= * remainder =3D (carry + bignum[1]) % 10 and carry =3D remainder * 256= and
+ * move on = to the next byte until we are done.
+ */
+ size_t new_length =3D 0;
+ int carry =3D 0;
+ for (size_t i =3D 0; i < *bignum_length; i++)+ {
+ uint8_t next_byte =3D (uint8_t)((= bignum[i] + carry) / 10);
+ int remainder =3D (bignum[i] + carry) % 10;
+ carry =3D remainder * 256;
+
+ /* Write the byte unless it's= a leading zero. */
+= if (new_length !=3D 0 || next_byte !=3D 0)
+ {
+ bignum[new_length++] =3D next_byte;=
+ }
+ }
+ *bignum_length =3D new_length;
+}

+
+ * Retur= ns the number of bytes needed in out, or 0 on error. To calculate the
+ * necessary buffer size,= the function can be called with out =3D NULL. */
+static size_t
+write_bignum(char *out, size_t out_size, const uint= 8_t *bignum, size_t bignum_length)
+{
+ = if (bignum_length =3D=3D 0)
+ {
+ = /* We want out to be "0". */
+ if (out !=3D NULL)
+ {
+ if (out_size >=3D 2)
+ {
+ out[0] =3D '0';=
+ out[1] =3D= '\0';
+ = }
+ = else if (out_size > 0)
+ {
= + out[0] =3D '\0';
+ }
+ }
+ return 2;
+ }
++ uint8_t *bignum_copy =3D = malloc(bignum_length);
+ {
+ return 0;
+= }
+ memcpy(big= num_copy, bignum, bignum_length);
+
+ s= ize_t bytes_needed =3D 0;
+ size_t bytes_written =3D 0;
+ while (bignum_length > 0)
+ {
+ /* We're writing the digits in reverse order. = We put them in the right order later. */
+ char digit =3D bignum_mod_10(bignum_copy, bign= um_length);
+ = if (out !=3D NULL && bytes_written < out_size - 1)
+ {

+ out[bytes_written++] =3D '= ;0' + (char)digit;
+ = bytes_needed +=3D 1;
+ bignum_div_10(bignum_copy, &bignum_length);
+ }
+
+ if (out !=3D NULL)
+ {
+ = if (bytes_written =3D=3D bytes_needed)
+ {
+ /* We had space for all digits. Now reverse them. */=
+ for (si= ze_t i =3D 0; i < bytes_written / 2; i++)
+ {
+ char tmp =3D out[i];
+ out[i] =3D out[bytes_wr= itten - 1 - i];
+ = out[bytes_written - 1 - i] =3D tmp;
+ }
+ out[bytes_written] =3D '\0';
+ }
+ else if (out_size > 0)<= /span>
+ {
= + out[0] =3D '\0= ';
+ }
+ }
+ bytes_needed +=3D 1;
+

+ free(bignum_copy);
+ return bytes_needed;
+}
+#endif /* MBEDTLS_VERSION_NUMBER >=3D 0x04000000 */

+
char *=
backend_x509_get_serial(mbedtls_x509_crt *cert, struct gc= _arena *gc)
{
char *buf =3D NULL;
size_t buflen =3D 0;
+
+= #if MBEDTLS_VERSION_NUMBER < 0x04000000
mbedtls_mpi= serial_mpi =3D { 0 };

/* Transform = asn1 integer serial into mbed TLS MPI */
@@ -198,6 +335,21 = @@
end:
mbedtls_mpi_free(&serial_= mpi);
return buf;
+#else
+ buflen =3D write_bignum(NULL, 0, cert->serial.p, cert->seria= l.len);
+ if (bufl= en =3D=3D 0)
+ {
+ msg(M_WARN, &= quot;Failed to write serial to string.");
+ return NULL;
+ }
+ buf =3D gc_malloc(buflen, true, gc);
+ if (write_bignum(buf, buflen, cert-&= gt;serial.p, cert->serial.len) !=3D buflen)
+ {
+ msg(M_WARN, "Failed to write serial to string.&qu= ot;);
+ return= NULL;
+ }<= br>+ return buf;
<= span style=3D"color: hsl(120, 100%, 40%);">+#endif /* MBEDTLS_VERSION_NUMBE= R < 0x04000000 */

}

= char *
diff --git a/src/openvpn/syshead.h b/src/openvpn/sys= head.h
index 627ba92..de9f5f3 100644
--- a/= src/openvpn/syshead.h
+++ b/src/openvpn/syshead.h@@ -475,7 +475,10 @@
#endif

#ifdef ENABLE_CRYPTO_MBEDTLS
+#include <mbedtls/version.h>
+#if MBEDTLS_VERSION_NUMBER < 0x04000= 000
#define ENABLE_PREDICTION_RESISTANCE
+#endif /* MBEDTLS_VERSION_NUMBER <= 0x04000000 */
#endif /* ENABLE_CRYPTO_MBEDTLS */
/*
diff --git a/tests/Makefile.a= m b/tests/Makefile.am
index 4b4bcaa..cdf24c8 100644<= br>--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -55,6 +55,7 @@
$(top_srcdir)/src/openvpn= /crypto_epoch.c \
$(top_srcdir)/src/openvpn/crypto_openss= l.c \
$(top_srcdir)/src/openvpn/crypto_mbedtls.c \=
+ $(top_srcdir)/src/openvpn= /crypto_mbedtls_legacy.c \
$(top_srcdir)/src/openvpn/otim= e.c \
$(top_srcdir)/src/openvpn/packet_id.c \
<= span> $(top_srcdir)/src/openvpn/platform.c

diff --git a/te= sts/unit_tests/openvpn/Makefile.am b/tests/unit_tests/openvpn/Makefile.am
index 7aeea47..1128eb4 100644
--- a/tests/un= it_tests/openvpn/Makefile.am
+++ b/tests/unit_tests/openvpn= /Makefile.am
@@ -76,6 +76,7 @@
$(top_srcd= ir)/src/openvpn/buffer.c \
$(top_srcdir)/src/openvpn/cryp= to.c \
$(top_srcdir)/src/openvpn/crypto_mbedtls.c \
+ $(top_srcdir)/src/openvp= n/crypto_mbedtls_legacy.c \
$(top_srcdir)/src/openvpn/cry= pto_openssl.c \
$(top_srcdir)/src/openvpn/crypto_epoch.c = \
$(top_srcdir)/src/openvpn/otime.c \
@@ = -110,6 +111,7 @@
$(top_srcdir)/src/openvpn/cryptoapi.c \<= /span>
$(top_srcdir)/src/openvpn/crypto_epoch.c \
$(top_srcdir)/src/openvpn/crypto_mbedtls.c \

+ $(top_srcdir)/src/openvpn/crypto_mbedtls_lega= cy.c \
$(top_srcdir)/src/openvpn/crypto_openssl.c \
$(top_srcdir)/src/openvpn/env_set.c \
$(top_= srcdir)/src/openvpn/mss.c \
@@ -158,6 +160,7 @@
<= span> $(top_srcdir)/src/openvpn/crypto.c \

$(top_srcdir)= /src/openvpn/crypto_epoch.c \
$(top_srcdir)/src/openvpn/c= rypto_mbedtls.c \
+ $= (top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \
$(top_= srcdir)/src/openvpn/crypto_openssl.c \
$(top_srcdir)/src/= openvpn/env_set.c \
$(top_srcdir)/src/openvpn/otime.c \
@@ -188,6 +191,7 @@
$(top_srcdir)/src/open= vpn/crypto.c \
$(top_srcdir)/src/openvpn/crypto_epoch.c \=
$(top_srcdir)/src/openvpn/crypto_mbedtls.c \
<= span style=3D"color: hsl(120, 100%, 40%);">+ $(top_srcdir)/src/openvpn/cryp= to_mbedtls_legacy.c \

$(top_srcdir)/src/openvpn/crypto_op= enssl.c \
$(top_srcdir)/src/openvpn/env_set.c \ $(top_srcdir)/src/openvpn/otime.c \
@@ -208,6 +212= ,7 @@
$(top_srcdir)/src/openvpn/crypto.c \
$(top_srcdir)/src/openvpn/crypto_epoch.c \

$(top_srcd= ir)/src/openvpn/crypto_mbedtls.c \
+ $(top_srcdir)/src/openvpn/crypto_mbedtls_legacy.c \<= br> $(top_srcdir)/src/openvpn/crypto_openssl.c \
$= (top_srcdir)/src/openvpn/fdmisc.c \
$(top_srcdir)/src/ope= nvpn/otime.c \
@@ -294,6 +299,7 @@
$(top_= srcdir)/src/openvpn/crypto.c \
$(top_srcdir)/src/openvpn/= crypto_epoch.c \
$(top_srcdir)/src/openvpn/crypto_mbedtls= .c \
+ $(top_srcdir)/= src/openvpn/crypto_mbedtls_legacy.c \
$(top_srcdir)/src/o= penvpn/crypto_openssl.c \
$(top_srcdir)/src/openvpn/otime= .c \
$(top_srcdir)/src/openvpn/packet_id.c \
@@ -332,6 +338,7 @@

$(top_srcdir)/src/openvpn/crypto.= c \
$(top_srcdir)/src/openvpn/crypto_epoch.c \
= $(top_srcdir)/src/openvpn/crypto_mbedtls.c \
+ $(top_srcdir)/src/openvpn/crypto_mbedtls= _legacy.c \
$(top_srcdir)/src/openvpn/crypto_openssl.c \<= /span>
$(top_srcdir)/src/openvpn/otime.c \
$(t= op_srcdir)/src/openvpn/packet_id.c \
diff --git a/tests/uni= t_tests/openvpn/test_common.h b/tests/unit_tests/openvpn/test_common.h
index da98531..18222b0 100644
--- a/tests/unit_= tests/openvpn/test_common.h
+++ b/tests/unit_tests/openvpn/= test_common.h
@@ -24,6 +24,10 @@
#include = <setjmp.h>
#include <cmocka.h>

+#if defined(ENABL= E_CRYPTO_MBEDTLS)
+#i= nclude "mbedtls_compat.h"
+#endif
+#if defined(ENABLE_CRYPTO_MBEDTLS)+ mbedtls_compat_psa_crypto= _init();
+#endif
}

/**

To view, visit change 1441. To unsubscribe, or for help writing = mail filters, visit settings.

=
Gerrit-MessageType: newpatchset
Gerrit-Project: openvpn
Gerrit-Branch: master
Gerrit-Change-Id: Ib251d546d993b96ed3bd8cb9111= bcc627cdb0fae
Gerrit-Change-Number: 1441
Gerrit-PatchSet: 2
Gerrit-Owner: MaxF <max@...2606...>
Gerrit-Reviewer: plaisthos <arne-openvpn@...1186...= .1227...>
Gerrit-CC: openvpn-devel <openvpn-devel@...1484...= ts.sourceforge.net>
Gerrit-Attention: plaisthos <arne-openvpn@...220...= ..1227...>
= --YKGksJiGtY4=--