diff --git a/.gitignore b/.gitignore index 0cf3f344..c1a8c870 100644 --- a/.gitignore +++ b/.gitignore @@ -44,9 +44,31 @@ /test/.deps /test/.libs /test/.dirstamp +/test/dh_alloc.test +/test/dh_alloc.log +/test/dh_alloc.trs /test/unit.test /test/unit.log /test/unit.trs +/test/unit_static.log +/test/unit_static.trs +/test/pbe_lifetime.test +/test/pbe_lifetime.log +/test/pbe_lifetime.trs +/test/pbe_static.test +/test/pbe_static.log +/test/pbe_static.trs +/test/engine_lifetime.test +/test/engine_lifetime.log +/test/engine_lifetime.trs +/test/engine_pbe_init.test +/test/engine_pbe_init.log +/test/engine_pbe_init.trs +/test/engine_bind.log +/test/engine_bind.trs +/test/cmac_cleanup*.test +/test/cmac_cleanup*.log +/test/cmac_cleanup*.trs /scripts/*.log *.gcno *.gcda @@ -74,3 +96,6 @@ openssl-source/ wolfssl-install/ wolfssl-source/ wolfengine-install/ + +/test/rsa_oaep_allocator.sh.log +/test/rsa_oaep_allocator.sh.trs diff --git a/Makefile.am b/Makefile.am index 3d59dc1a..37e9fd1a 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,12 +1,12 @@ SUFFIXES = -TESTS = +TESTS = test/unit_static.test test/engine_bind.test noinst_PROGRAMS = noinst_HEADERS = check_PROGRAMS = dist_noinst_SCRIPTS = DISTCLEANFILES = pkginclude_HEADERS = -EXTRA_DIST = +EXTRA_DIST = test/unit_static.test test/engine_bind.test ACLOCAL_AMFLAGS = -I m4 diff --git a/README.md b/README.md index 3265a565..8a4c218a 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ having to touch the OpenSSL code itself. * DRBG * RSA * DH + * With wolfCrypt FIPS, use named or imported parameters for key generation + and agreement. Legacy `DH_generate_parameters_ex()` returns 0. * ECC * ECDSA * ECDH diff --git a/configure.ac b/configure.ac index d07e8699..851ae5f1 100644 --- a/configure.ac +++ b/configure.ac @@ -16,6 +16,10 @@ dnl m4_include([m4/ax_check_wolfssl.m4]) AM_INIT_AUTOMAKE([1.11 -Wall -Werror -Wno-portability foreign tar-ustar subdir-objects no-define color-tests]) LT_INIT([disable-static pic-only]) +AM_CONDITIONAL([BUILD_STATIC_TESTS], [test "$enable_static" = "yes"]) +AS_IF([test "$enable_shared" != "no"], [ + AC_DEFINE([WE_HAVE_SHARED_LIBRARY], [1], [Build the shared engine library]) +]) # capture user C_EXTRA_FLAGS from ./configure line, CFLAGS may hold -g -O2 even # if user doesn't override, no way to tell @@ -52,6 +56,44 @@ AC_SUBST([WOLFENGINE_LIBRARY_VERSION_SECOND]) AC_SUBST([WOLFENGINE_LIBRARY_VERSION_THIRD]) LIBS="$LIBS -ldl" +AC_CHECK_HEADERS([dlfcn.h link.h valgrind/memcheck.h]) +AC_CACHE_CHECK([for the dladdr module-location interface], [we_cv_dladdr], [ + AC_LINK_IFELSE([AC_LANG_PROGRAM([[ + #if defined(__linux__) && !defined(_GNU_SOURCE) + #define _GNU_SOURCE + #endif + #include + ]], [[ + Dl_info info; + int (*lookup)(const void *, Dl_info *) = dladdr; + info.dli_fname = 0; + info.dli_fbase = 0; + return lookup((const void *)&lookup, &info); + ]])], [we_cv_dladdr=yes], [we_cv_dladdr=no]) +]) +AS_IF([test "$we_cv_dladdr" = "yes"], [ + AC_DEFINE([WE_HAVE_DLADDR], [1], + [The complete dladdr module-location interface is available]) +]) +AC_CHECK_FUNCS([dl_iterate_phdr]) +AS_IF([test "$ac_cv_header_link_h" = "yes" && + test "$ac_cv_func_dl_iterate_phdr" = "yes"], [ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #ifndef _GNU_SOURCE + #define _GNU_SOURCE + #endif + #include + ]], [[ + struct dl_phdr_info info; + info.dlpi_addr = 0; + info.dlpi_phdr = 0; + info.dlpi_phnum = 0; + (void)dl_iterate_phdr(0, &info); + ]])], [ + AC_DEFINE([WE_HAVE_DL_ITERATE_PHDR], [1], + [Program header iteration is available]) + ]) +]) # OpenSSL AC_CHECK_HEADERS([openssl/engine.h]) @@ -338,6 +380,69 @@ if test "$ENABLED_CMAC" = "yes" then ENABLED_DIGEST="yes" AM_CFLAGS="$AM_CFLAGS -DWE_HAVE_CMAC -DWE_HAVE_EVP_PKEY" + we_cmac_saved_CPPFLAGS="$CPPFLAGS" + AS_IF([test "$ENABLED_USERSETTINGS" = "yes"], [ + CPPFLAGS="$CPPFLAGS -DWOLFENGINE_USER_SETTINGS -I$srcdir/include" + ]) + AC_CACHE_CHECK([whether wolfSSL declares wc_CmacFree], + [we_cv_cmac_free], [ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #ifdef WOLFENGINE_USER_SETTINGS + #include "user_settings.h" + #else + #include + #endif + #include + ]], [[ + (void)&wc_CmacFree; + ]])], [we_cv_cmac_free=yes], [we_cv_cmac_free=no]) + ]) + AS_IF([test "$we_cv_cmac_free" = "no"], [ + AC_DEFINE([WE_NO_CMAC_FREE], [1], + [wolfSSL does not provide the CMAC cleanup interface]) + ]) + AC_CACHE_CHECK([whether wolfSSL CMAC keeps a buffered message], + [we_cv_cmac_buffered_state], [ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #ifdef WOLFENGINE_USER_SETTINGS + #include "user_settings.h" + #else + #include + #endif + #include + #ifndef WOLFSSL_HASH_KEEP + #error CMAC message buffering is disabled + #endif + ]], [[ + Cmac cmac; + (void)sizeof(cmac.msg); + (void)sizeof(cmac.len); + ]])], [we_cv_cmac_buffered_state=yes], + [we_cv_cmac_buffered_state=no]) + ]) + AS_IF([test "$we_cv_cmac_buffered_state" = "yes"], [ + AC_DEFINE([WE_CMAC_HAS_BUFFERED_STATE], [1], + [wolfSSL CMAC has an owned buffered message]) + ]) + AC_CACHE_CHECK([whether wolfSSL AES direct encryption returns a status], + [we_cv_aes_direct_status], [ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #ifdef WOLFENGINE_USER_SETTINGS + #include "user_settings.h" + #else + #include + #endif + #include + ]], [[ + (void)&wc_AesEncryptDirect; + return wc_AesEncryptDirect(NULL, NULL, NULL); + ]])], [we_cv_aes_direct_status=yes], [we_cv_aes_direct_status=no]) + ]) + AS_IF([test "$we_cv_aes_direct_status" = "no"], [ + AC_DEFINE([WE_AES_DIRECT_RETURNS_VOID], [1], + [wolfSSL AES direct encryption has no return value]) + ]) + CPPFLAGS="$we_cmac_saved_CPPFLAGS" fi AC_ARG_ENABLE([hmac], @@ -670,6 +775,22 @@ AC_ARG_ENABLE([pbe], if test "$ENABLED_PBE" = "yes" then + AS_IF([test "$ENABLED_DYNAMIC_ENGINE" = "yes" && + test "$we_cv_dladdr" != "yes"], [ + AC_LINK_IFELSE([AC_LANG_PROGRAM([[ + #ifndef _WIN32 + #error Windows module pinning is unavailable + #endif + #include + ]], [[ + HMODULE module = NULL; + return GetModuleHandleExA( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + (LPCSTR)(const void *)&module, &module) == 0; + ]])], [], [ + AC_MSG_ERROR([dynamic PBE requires dladdr with Dl_info or Windows module pinning; use --disable-dynamic-engine for static engine loading]) + ]) + ]) AM_CFLAGS="$AM_CFLAGS -DWE_HAVE_PBE" fi diff --git a/include/wolfengine/we_internal.h b/include/wolfengine/we_internal.h index 6cfa8b5f..09612aa9 100644 --- a/include/wolfengine/we_internal.h +++ b/include/wolfengine/we_internal.h @@ -58,7 +58,7 @@ #include #endif #include -#if OPENSSL_VERSION_NUMBER >= 0x10101000L +#ifdef WE_HAVE_CMAC #include #endif #include @@ -132,17 +132,6 @@ WOLFENGINE_LOCAL void *we_memdup(const void *data, size_t siz); #endif /* OPENSSL_VERSION_NUMBER >= 0x10100000L */ #endif /* WE_NO_OPENSSL_MALLOC */ -#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) - /* Function is a printf style function. Pretend parameter is string literal. - * - * @param s [in] Index of string literal. Index from 1. - * @param v [in] Index of first argument to check. 0 means don't. - */ - #define WE_PRINTF_FUNC(s, v) __attribute__((__format__ (__printf__, s, v))) -#else - #define WE_PRINTF_FUNC(s, v) -#endif - /* * Global random */ @@ -150,6 +139,11 @@ WOLFENGINE_LOCAL void *we_memdup(const void *data, size_t siz); extern WC_RNG* we_rng; #ifndef WE_SINGLE_THREADED extern wolfSSL_Mutex* we_rng_mutex; +WOLFENGINE_LOCAL int we_rng_mutex_is_initialized(void); +#endif +WOLFENGINE_LOCAL int we_rng_is_initialized(void); +#if defined(WE_HAVE_RANDOM) && !defined(WE_STATIC_WOLFSSL) +WOLFENGINE_LOCAL void we_rand_clear_seed(void); #endif WOLFENGINE_LOCAL int we_pkey_get_nids(const int** nids); @@ -241,11 +235,14 @@ extern RAND_METHOD* we_random_method; #ifdef WE_HAVE_HMAC +typedef int (*we_HmacInitCb)(Hmac*, void*, int); + extern EVP_PKEY_METHOD *we_hmac_pkey_method; extern EVP_PKEY_ASN1_METHOD *we_hmac_pkey_asn1_method; WOLFENGINE_LOCAL int we_init_hmac_pkey_meth(void); WOLFENGINE_LOCAL int we_init_hmac_pkey_asn1_meth(void); +WOLFENGINE_LOCAL int we_hmac_pkey_init_ex(EVP_PKEY_CTX*, we_HmacInitCb); WOLFENGINE_LOCAL int we_hmac_update(Hmac*, const void*, size_t); #endif /* WE_HAVE_HMAC */ @@ -257,11 +254,13 @@ WOLFENGINE_LOCAL int we_hmac_update(Hmac*, const void*, size_t); #ifdef WE_HAVE_CMAC #define NID_wolfengine_cmac 101 +extern EVP_CIPHER *we_cmac_ciph; extern EVP_PKEY_METHOD *we_cmac_pkey_method; extern EVP_PKEY_METHOD *we_cmac_we_pkey_method; extern EVP_PKEY_ASN1_METHOD *we_cmac_pkey_asn1_method; extern EVP_PKEY_ASN1_METHOD *we_cmac_we_pkey_asn1_method; +WOLFENGINE_LOCAL int we_init_cmac_cipher_meth(void); WOLFENGINE_LOCAL int we_init_cmac_pkey_meth(void); WOLFENGINE_LOCAL int we_init_cmac_pkey_asn1_meth(void); @@ -354,9 +353,13 @@ WOLFENGINE_LOCAL int we_init_ec_key_meths(void); */ #ifdef WE_HAVE_PBE +WOLFENGINE_LOCAL int we_prepare_pbe_keygen(void); WOLFENGINE_LOCAL int we_init_pbe_keygen(void); +WOLFENGINE_LOCAL int we_pbe_keygen_ready(void); #endif WOLFENGINE_LOCAL int wolfengine_bind(ENGINE *e, const char *id); +WOLFENGINE_LOCAL int we_engine_bind_available(void); +WOLFENGINE_LOCAL ENGINE *wolfengine_get_bound_engine(void); #endif /* INTERNAL_H */ diff --git a/include/wolfengine/we_logging.h b/include/wolfengine/we_logging.h index c7c4a573..5de2d59d 100644 --- a/include/wolfengine/we_logging.h +++ b/include/wolfengine/we_logging.h @@ -32,6 +32,13 @@ #include +#if defined(__IAR_SYSTEMS_ICC__) || defined(__GNUC__) + /* Check printf-style format strings and their arguments. */ + #define WE_PRINTF_FUNC(s, v) __attribute__((__format__ (__printf__, s, v))) +#else + #define WE_PRINTF_FUNC(s, v) +#endif + /* wolfEngine debug logging support can be compiled in by defining * WOLFENGINE_DEBUG or by using the --enable-debug configure option. * @@ -137,6 +144,7 @@ void WOLFENGINE_LEAVE(int type, const char* msg, int ret); WOLFENGINE_API void WOLFENGINE_MSG(int type, const char* fmt, ...); WOLFENGINE_LOCAL +WE_PRINTF_FUNC(2, 3) void WOLFENGINE_MSG_VERBOSE(int type, const char* fmt, ...); WOLFENGINE_API void WOLFENGINE_ERROR_LINE(int type, int err, const char* file, int line); diff --git a/include/wolfengine/we_openssl_bc.h b/include/wolfengine/we_openssl_bc.h index 3db975ae..88af4910 100644 --- a/include/wolfengine/we_openssl_bc.h +++ b/include/wolfengine/we_openssl_bc.h @@ -70,6 +70,12 @@ WOLFENGINE_LOCAL int EVP_MD_meth_set_update(EVP_MD *md, int (*update)(EVP_MD_CTX *ctx, const void *data, size_t count)); +WOLFENGINE_LOCAL +int EVP_MD_meth_set_copy(EVP_MD *md, int (*copy)(EVP_MD_CTX *to, + const EVP_MD_CTX *from)); +WOLFENGINE_LOCAL +int (*EVP_MD_meth_get_copy(const EVP_MD *md))(EVP_MD_CTX *to, + const EVP_MD_CTX *from); WOLFENGINE_LOCAL int EVP_MD_meth_set_final(EVP_MD *md, int (*final)(EVP_MD_CTX *ctx, unsigned char *md)); @@ -96,6 +102,9 @@ int EVP_CIPHER_meth_set_init(EVP_CIPHER *cipher, const unsigned char *iv, int enc)); WOLFENGINE_LOCAL +int EVP_CIPHER_meth_set_cleanup(EVP_CIPHER *cipher, + int (*cleanup)(EVP_CIPHER_CTX *ctx)); +WOLFENGINE_LOCAL int EVP_CIPHER_meth_set_do_cipher(EVP_CIPHER *cipher, int (*do_cipher) (EVP_CIPHER_CTX *ctx, unsigned char *out, diff --git a/openssl_patches/1.0.2h/tests/fips/dhtest_102h.patch b/openssl_patches/1.0.2h/tests/fips/dhtest_102h.patch new file mode 100644 index 00000000..a44885ba --- /dev/null +++ b/openssl_patches/1.0.2h/tests/fips/dhtest_102h.patch @@ -0,0 +1,20 @@ +diff --git a/crypto/dh/dhtest.c b/crypto/dh/dhtest.c +--- a/crypto/dh/dhtest.c ++++ b/crypto/dh/dhtest.c +@@ -140,5 +140,13 @@ + BN_GENCB_set(&_cb, &cb, out); +- if (((a = DH_new()) == NULL) || !DH_generate_parameters_ex(a, 1024, +- DH_GENERATOR_5, +- &_cb)) ++ if ((a = DH_new()) == NULL) ++ goto err; ++ if (a->engine != e || ++ DH_generate_parameters_ex(a, 1024, DH_GENERATOR_5, &_cb) != 0 || ++ a->p != NULL || a->q != NULL || a->g != NULL || a->engine != e) ++ goto err; ++ BIO_puts(out, "Legacy DH parameter generation rejected in FIPS mode\n"); ++ ERR_clear_error(); ++ DH_free(a); ++ a = DH_get_2048_256(); ++ if (a == NULL || a->engine != e) + goto err; diff --git a/openssl_patches/1.1.1b/tests/fips/dhtest_111b.patch b/openssl_patches/1.1.1b/tests/fips/dhtest_111b.patch new file mode 100644 index 00000000..1e93a12a --- /dev/null +++ b/openssl_patches/1.1.1b/tests/fips/dhtest_111b.patch @@ -0,0 +1,32 @@ +diff --git a/test/dhtest.c b/test/dhtest.c +--- a/test/dhtest.c ++++ b/test/dhtest.c +@@ -25,4 +25,6 @@ + static int cb(int p, int n, BN_GENCB *arg); +- +- ++ ++extern ENGINE *e; ++ ++ + static const unsigned char dhtest_1024_p[] = +@@ -193,5 +193,17 @@ + BN_GENCB_set(_cb, &cb, NULL); + if (!TEST_ptr(a = DH_new()) +- || !TEST_true(DH_generate_parameters_ex(a, 1024, +- DH_GENERATOR_5, _cb))) ++ || !TEST_ptr_eq(DH_get0_engine(a), e) ++ || !TEST_int_eq(DH_generate_parameters_ex(a, 1024, ++ DH_GENERATOR_5, _cb), 0) ++ || !TEST_ptr_null(DH_get0_p(a)) ++ || !TEST_ptr_null(DH_get0_q(a)) ++ || !TEST_ptr_null(DH_get0_g(a)) ++ || !TEST_ptr_eq(DH_get0_engine(a), e)) ++ goto err3; ++ TEST_info("Legacy DH parameter generation rejected in FIPS mode"); ++ ERR_clear_error(); ++ DH_free(a); ++ a = NULL; ++ if (!TEST_ptr(a = DH_get_2048_256()) ++ || !TEST_ptr_eq(DH_get0_engine(a), e)) + goto err3; diff --git a/src/include.am b/src/include.am index f13d94f1..e43a1f8c 100644 --- a/src/include.am +++ b/src/include.am @@ -18,6 +18,7 @@ libwolfengine_la_SOURCES += src/we_hkdf.c libwolfengine_la_SOURCES += src/we_internal.c libwolfengine_la_SOURCES += src/we_logging.c libwolfengine_la_SOURCES += src/we_mac.c +libwolfengine_la_SOURCES += src/we_cmac_compat.h libwolfengine_la_SOURCES += src/we_openssl_bc.c libwolfengine_la_SOURCES += src/we_pbe.c libwolfengine_la_SOURCES += src/we_random.c diff --git a/src/we_aes_block.c b/src/we_aes_block.c index 61374edf..161073ea 100644 --- a/src/we_aes_block.c +++ b/src/we_aes_block.c @@ -30,14 +30,112 @@ typedef struct we_AesBlock { /** The wolfSSL AES data object. */ Aes aes; + /** Raw key used to recreate the AES object when copying the context. */ + unsigned char key[AES_256_KEY_SIZE]; + /** Number of bytes in the raw key. */ + unsigned int keyLen; /** Buffer for streaming. */ unsigned char lastBlock[WC_AES_BLOCK_SIZE]; /** Number of buffered bytes. */ unsigned int over; + /** Flag to indicate whether the AES object is initialized. */ + unsigned int inited:1; /** Flag to indicate whether we are doing encrypt (1) or decrpyt (0). */ unsigned int enc:1; } we_AesBlock; +/** + * Cleanup the internal AES block object. Does not free object. + * + * @param ctx [in] EVP cipher context. + * @returns 1 on success and 0 on failure. + */ +static int we_aes_block_cleanup(EVP_CIPHER_CTX *ctx) +{ + int ret = 1; + we_AesBlock *aes; + + aes = (we_AesBlock *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if (aes == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, + "EVP_CIPHER_CTX_get_cipher_data", aes); + ret = 0; + } + + if (ret == 1) { + if (aes->inited != 0) { + wc_AesFree(&aes->aes); + } + XMEMSET(aes, 0, sizeof(we_AesBlock)); + } + + return ret; +} + +static int we_aes_block_copy(EVP_CIPHER_CTX *srcCtx, + EVP_CIPHER_CTX *dstCtx) +{ + int ret = 1; + int rc; + we_AesBlock *src; + we_AesBlock *dst; + + src = (we_AesBlock *)EVP_CIPHER_CTX_get_cipher_data(srcCtx); + dst = (we_AesBlock *)EVP_CIPHER_CTX_get_cipher_data(dstCtx); + if ((src == NULL) || (dst == NULL)) { + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, + "AES block cipher data is NULL"); + ret = 0; + } + + if (ret == 1) { + XMEMSET(dst, 0, sizeof(we_AesBlock)); + XMEMCPY(dst->key, src->key, sizeof(dst->key)); + XMEMCPY(dst->lastBlock, src->lastBlock, sizeof(dst->lastBlock)); + dst->keyLen = src->keyLen; + dst->over = src->over; + dst->enc = src->enc; + } + if ((ret == 1) && (src->inited != 0)) { + if ((src->keyLen == 0) || (src->keyLen > sizeof(src->key))) { + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, + "Invalid AES block key length"); + ret = 0; + } + } + if ((ret == 1) && (src->inited != 0)) { + rc = wc_AesInit(&dst->aes, NULL, INVALID_DEVID); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); + ret = 0; + } + else { + dst->inited = 1; + } + } + if ((ret == 1) && (src->inited != 0)) { + rc = wc_AesSetKey(&dst->aes, dst->key, dst->keyLen, + (const unsigned char *)src->aes.reg, + src->enc ? AES_ENCRYPTION : AES_DECRYPTION); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetKey", rc); + ret = 0; + } + } + if (ret == 0) { + if ((dst != NULL) && (dst->inited != 0)) { + wc_AesFree(&dst->aes); + } + if (dst != NULL) { + XMEMSET(dst, 0, sizeof(we_AesBlock)); + } + } + + return ret; +} + +#define AES_BLOCK_COPY_FLAG EVP_CIPH_CUSTOM_COPY + #endif @@ -52,7 +150,7 @@ typedef struct we_AesBlock * * @param ctx [in,out] EVP cipher context of operation. * @param key [in] AES key - 16/24/32 bytes. - * @param iv [in] Initialization Vector - 12 bytes. + * @param iv [in] Initialization Vector - 16 bytes. * @param enc [in] 1 when initializing for encrypt and 0 when decrypt. * @return 1 on success and 0 on failure. */ @@ -67,22 +165,26 @@ static int we_aes_cbc_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [ctx = %p, key = %p, " "iv = %p, enc = %d]", ctx, key, iv, enc); - if (ret == 1) { - aes = (we_AesBlock *)EVP_CIPHER_CTX_get_cipher_data(ctx); - if (aes == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, - "EVP_CIPHER_CTX_get_cipher_data", aes); - ret = 0; - } + aes = (we_AesBlock *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if (aes == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, + "EVP_CIPHER_CTX_get_cipher_data", aes); + ret = 0; } if ((ret == 1) && (key != NULL)) { - WOLFENGINE_MSG(WE_LOG_CIPHER, - "Initializing wolfCrypt Aes structure: %p", &aes->aes); - rc = wc_AesInit(&aes->aes, NULL, INVALID_DEVID); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); - ret = 0; + if (aes->inited == 0) { + WOLFENGINE_MSG(WE_LOG_CIPHER, + "Initializing wolfCrypt Aes structure: %p", + &aes->aes); + rc = wc_AesInit(&aes->aes, NULL, INVALID_DEVID); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); + ret = 0; + } + else { + aes->inited = 1; + } } if (ret == 1) { WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting AES key (%d bytes)", @@ -93,6 +195,11 @@ static int we_aes_cbc_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetKey", rc); ret = 0; } + else { + XMEMSET(aes->key, 0, sizeof(aes->key)); + XMEMCPY(aes->key, key, EVP_CIPHER_CTX_key_length(ctx)); + aes->keyLen = EVP_CIPHER_CTX_key_length(ctx); + } } } @@ -115,7 +222,7 @@ static int we_aes_cbc_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, * @param out [out] Buffer to store enciphered result. * @param in [in] Data to encrypt/decrypt. * @param len [in] Length of data to encrypt/decrypt. - * @return -1 on failure. + * @return 0 on failure. * @return 1 on success. */ static int we_aes_cbc_encrypt(we_AesBlock* aes, unsigned char *out, @@ -130,7 +237,7 @@ static int we_aes_cbc_encrypt(we_AesBlock* aes, unsigned char *out, rc = wc_AesCbcEncrypt(&aes->aes, out, in, (unsigned int)len); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesCbcEncrypt", rc); - ret = -1; + ret = 0; } WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_aes_cbc_encrypt", ret); @@ -146,7 +253,7 @@ static int we_aes_cbc_encrypt(we_AesBlock* aes, unsigned char *out, * @param out [out] Buffer to store enciphered result. * @param in [in] Data to encrypt/decrypt. * @param len [in] Length of data to encrypt/decrypt. - * @return -1 on failure. + * @return 0 on failure. * @return Number of bytes put in out on success. */ static int we_aes_cbc_decrypt(we_AesBlock* aes, unsigned char *out, @@ -163,7 +270,7 @@ static int we_aes_cbc_decrypt(we_AesBlock* aes, unsigned char *out, ret = (int)len; } else { - ret = -1; + ret = 0; } WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_aes_cbc_decrypt", ret); @@ -179,7 +286,7 @@ static int we_aes_cbc_decrypt(we_AesBlock* aes, unsigned char *out, * @param out [out] Buffer to store enciphered result. * @param in [in] Data to encrypt/decrypt. * @param len [in] Length of data to encrypt/decrypt. - * @return -1 on failure. + * @return 0 on failure. * @return Number of bytes put in out on success. */ static int we_aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, @@ -198,7 +305,7 @@ static int we_aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, if (aes == NULL) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, "EVP_CIPHER_CTX_get_cipher_data", aes); - ret = -1; + ret = 0; } if (ret == 1) { WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting AES IV"); @@ -227,7 +334,7 @@ static int we_aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, /** * Extra operations for AES-CBC. * - * No supported operations yet. + * Handles initialization and context copies. * * @param ctx [in] EVP cipher context of operation. * @param type [in] Type of operation to perform. @@ -255,6 +362,12 @@ static int we_aes_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) } if (ret == 1) { switch (type) { + case EVP_CTRL_INIT: + XMEMSET(aes, 0, sizeof(we_AesBlock)); + break; + case EVP_CTRL_COPY: + ret = we_aes_block_copy(ctx, (EVP_CIPHER_CTX *)ptr); + break; default: XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); @@ -273,6 +386,8 @@ static int we_aes_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) #define AES_CBC_FLAGS \ (EVP_CIPH_FLAG_DEFAULT_ASN1 | \ EVP_CIPH_CBC_MODE | \ + EVP_CIPH_CTRL_INIT | \ + AES_BLOCK_COPY_FLAG | \ EVP_CIPH_ALWAYS_CALL_INIT) /** AES128-CBC EVP cipher method. */ @@ -301,6 +416,15 @@ static int we_init_aescbc_meth(EVP_CIPHER *cipher) if (ret == 1) { ret = EVP_CIPHER_meth_set_init(cipher, we_aes_cbc_init); } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (ret == 1) { + ret = EVP_CIPHER_meth_set_cleanup(cipher, we_aes_block_cleanup); + } +#else + if (ret == 1) { + cipher->cleanup = we_aes_block_cleanup; + } +#endif if (ret == 1) { ret = EVP_CIPHER_meth_set_do_cipher(cipher, we_aes_cbc_cipher); } @@ -429,12 +553,18 @@ static int we_aes_ecb_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, } if ((ret == 1) && (key != NULL)) { - WOLFENGINE_MSG(WE_LOG_CIPHER, - "Initializing wolfCrypt Aes structure: %p", &aes->aes); - rc = wc_AesInit(&aes->aes, NULL, INVALID_DEVID); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); - ret = 0; + if (aes->inited == 0) { + WOLFENGINE_MSG(WE_LOG_CIPHER, + "Initializing wolfCrypt Aes structure: %p", + &aes->aes); + rc = wc_AesInit(&aes->aes, NULL, INVALID_DEVID); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); + ret = 0; + } + else { + aes->inited = 1; + } } if (ret == 1) { WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting AES key (%d bytes)", @@ -445,6 +575,11 @@ static int we_aes_ecb_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetKey", rc); ret = 0; } + else { + XMEMSET(aes->key, 0, sizeof(aes->key)); + XMEMCPY(aes->key, key, EVP_CIPHER_CTX_key_length(ctx)); + aes->keyLen = EVP_CIPHER_CTX_key_length(ctx); + } } } @@ -468,7 +603,7 @@ static int we_aes_ecb_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, * @param out [out] Buffer to store enciphered result. * @param in [in] Data to encrypt/decrypt. * @param len [in] Length of data to encrypt/decrypt. - * @return -1 on failure. + * @return 0 on failure. * @return 1 on success. */ static int we_aes_ecb_encrypt(we_AesBlock* aes, unsigned char *out, @@ -571,7 +706,7 @@ static int we_aes_ecb_encrypt(we_AesBlock* aes, unsigned char *out, * @param out [out] Buffer to store enciphered result. * @param in [in] Data to encrypt/decrypt. * @param len [in] Length of data to encrypt/decrypt. - * @return -1 on failure. + * @return 0 on failure. * @return 1 on success. */ static int we_aes_ecb_decrypt(we_AesBlock* aes, unsigned char *out, @@ -611,7 +746,7 @@ static int we_aes_ecb_decrypt(we_AesBlock* aes, unsigned char *out, len -= l; } /* Padding and not last full block or not padding and full block. */ - if ((aes->over == WC_AES_BLOCK_SIZE) || len > 0) { + if (aes->over == WC_AES_BLOCK_SIZE) { /* Decrypt block cached block. */ rc = wc_AesEcbDecrypt(&aes->aes, out, aes->lastBlock, WC_AES_BLOCK_SIZE); @@ -637,18 +772,16 @@ static int we_aes_ecb_decrypt(we_AesBlock* aes, unsigned char *out, /* Calculate full blocks. */ l = (int)len & (~(WC_AES_BLOCK_SIZE - 1)); - if (l > 0) { - rc = wc_AesEcbDecrypt(&aes->aes, out, in, l); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, - "wc_AesEcbDecrypt", rc); - ret = 0; - } - else { - WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, - "Decrypted %d bytes (AES-ECB)", l); - WOLFENGINE_BUFFER(WE_LOG_CIPHER, out, l); - } + rc = wc_AesEcbDecrypt(&aes->aes, out, in, l); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, + "wc_AesEcbDecrypt", rc); + ret = 0; + } + else { + WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, + "Decrypted %d bytes (AES-ECB)", l); + WOLFENGINE_BUFFER(WE_LOG_CIPHER, out, l); } in += l; @@ -675,7 +808,7 @@ static int we_aes_ecb_decrypt(we_AesBlock* aes, unsigned char *out, * @param out [out] Buffer to store enciphered result. * @param in [in] Data to encrypt/decrypt. * @param len [in] Length of data to encrypt/decrypt. - * @return -1 on failure. + * @return 0 on failure. * @return 1 on success. */ static int we_aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, @@ -693,7 +826,7 @@ static int we_aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, if (aes == NULL) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, "EVP_CIPHER_CTX_get_cipher_data", aes); - ret = -1; + ret = 0; } else if (aes->enc) { ret = we_aes_ecb_encrypt(aes, out, in, len); @@ -710,7 +843,7 @@ static int we_aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, /** * Extra operations for AES-ECB. * - * No supported operations yet. + * Handles initialization and context copies. * * @param ctx [in] EVP cipher context of operation. * @param type [in] Type of operation to perform. @@ -738,6 +871,12 @@ static int we_aes_ecb_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) } if (ret == 1) { switch (type) { + case EVP_CTRL_INIT: + XMEMSET(aes, 0, sizeof(we_AesBlock)); + break; + case EVP_CTRL_COPY: + ret = we_aes_block_copy(ctx, (EVP_CIPHER_CTX *)ptr); + break; default: XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); @@ -756,6 +895,8 @@ static int we_aes_ecb_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) #define AES_ECB_FLAGS \ (EVP_CIPH_ALWAYS_CALL_INIT | \ EVP_CIPH_FLAG_DEFAULT_ASN1 | \ + EVP_CIPH_CTRL_INIT | \ + AES_BLOCK_COPY_FLAG | \ EVP_CIPH_ECB_MODE) /** AES128-ECB EVP cipher method. */ @@ -784,6 +925,15 @@ static int we_init_aesecb_meth(EVP_CIPHER *cipher) if (ret == 1) { ret = EVP_CIPHER_meth_set_init(cipher, we_aes_ecb_init); } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (ret == 1) { + ret = EVP_CIPHER_meth_set_cleanup(cipher, we_aes_block_cleanup); + } +#else + if (ret == 1) { + cipher->cleanup = we_aes_block_cleanup; + } +#endif if (ret == 1) { ret = EVP_CIPHER_meth_set_do_cipher(cipher, we_aes_ecb_cipher); } diff --git a/src/we_aes_cbc_hmac.c b/src/we_aes_cbc_hmac.c index 0feb1231..fe2c6b56 100644 --- a/src/we_aes_cbc_hmac.c +++ b/src/we_aes_cbc_hmac.c @@ -38,8 +38,13 @@ typedef struct we_AesCbcHmac int pLen; /** Flag to indicate whether wolfSSL AES object initialized. */ unsigned int init:1; + /** Flags indicating installed AES and HMAC keys. */ + unsigned int keySet:1; + unsigned int hmacKeySet:1; /** Flag to indicate whether we are doing encrypt (1) or decrpyt (0). */ unsigned int enc:1; + /** Flag to indicate whether TLS AAD has been configured. */ + unsigned int tls:1; /** Flag to indicate whether we are doing TLS 1.1 or above. */ unsigned int tls11:1; } we_AesCbcHmac; @@ -53,7 +58,7 @@ typedef struct we_AesCbcHmac * * @param ctx [in,out] EVP cipher context of operation. * @param key [in] AES key - 16/24/32 bytes. - * @param iv [in] Initialization Vector - 12 bytes. + * @param iv [in] Initialization Vector - 16 bytes. * @param enc [in] 1 when initializing for encrypt and 0 when decrypt. * @return 1 on success and 0 on failure. */ @@ -63,21 +68,27 @@ static int we_aes_cbc_hmac_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, int ret = 1; int rc; we_AesCbcHmac *aes; + unsigned char digest[SHA256_DIGEST_LENGTH]; WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_aes_cbc_hmac_init"); WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [ctx = %p, key = %p, iv = %p, " "enc = %d]", ctx, key, iv, enc); - if ((iv == NULL) && (key == NULL)) { - WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "iv == NULL && key == NULL"); + aes = (we_AesCbcHmac *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if (aes == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, + "EVP_CIPHER_CTX_get_cipher_data", aes); ret = 0; } - - if (ret == 1) { - aes = (we_AesCbcHmac *)EVP_CIPHER_CTX_get_cipher_data(ctx); - if (aes == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, - "EVP_CIPHER_CTX_get_cipher_data", aes); + if ((ret == 1) && aes->keySet && (key == NULL) && + (aes->enc != (unsigned int)enc)) { + ret = 0; + } + if ((ret == 1) && aes->init && aes->hmacKeySet) { + rc = wc_HmacFinal(&aes->hmac, digest); + OPENSSL_cleanse(digest, sizeof(digest)); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_HmacFinal", rc); ret = 0; } } @@ -99,6 +110,7 @@ static int we_aes_cbc_hmac_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, rc = wc_HmacInit(&aes->hmac, NULL, INVALID_DEVID); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_HmacInit", rc); + wc_AesFree(&aes->aes); ret = 0; } } @@ -110,6 +122,13 @@ static int we_aes_cbc_hmac_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, aes->enc = enc; /* No payload yet. */ aes->pLen = 0; + aes->tls = 0; + aes->tls11 = 0; + + /* EVP restores the effective CBC IV before calling init. */ + if (iv == NULL) { + iv = EVP_CIPHER_CTX_iv(ctx); + } if (key != NULL) { /* Set the key into wolfSSL AES object. */ @@ -117,12 +136,13 @@ static int we_aes_cbc_hmac_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, EVP_CIPHER_CTX_key_length(ctx)); rc = wc_AesSetKey(&aes->aes, key, EVP_CIPHER_CTX_key_length(ctx), iv, enc ? AES_ENCRYPTION : AES_DECRYPTION); + aes->keySet = (rc == 0); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetKey", rc); ret = 0; } } - else { + else if (iv != NULL) { /* Set the IV into wolfSSL AES object. */ WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting AES IV"); rc = wc_AesSetIV(&aes->aes, iv); @@ -138,6 +158,35 @@ static int we_aes_cbc_hmac_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, return ret; } +/** + * Cleanup the internal AES-CBC HMAC object. + * + * @param ctx [in] EVP cipher context. + * @return 1 on success and 0 on failure. + */ +static int we_aes_cbc_hmac_cleanup(EVP_CIPHER_CTX *ctx) +{ + int ret = 1; + we_AesCbcHmac *aes; + + aes = (we_AesCbcHmac *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if (aes == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, + "EVP_CIPHER_CTX_get_cipher_data", aes); + ret = 0; + } + + if ((ret == 1) && aes->init) { + wc_HmacFree(&aes->hmac); + wc_AesFree(&aes->aes); + aes->init = 0; + aes->keySet = 0; + aes->hmacKeySet = 0; + } + + return ret; +} + /** * Encrypt and MAC using wolfSSL. * @@ -162,7 +211,16 @@ static int we_aes_cbc_hmac_enc(we_AesCbcHmac* aes, unsigned char *out, /* Get payload length to get TLS. */ pLen = aes->pLen; - tls = (pLen != 0); + tls = aes->tls; + off = (tls && aes->tls11) ? WC_AES_BLOCK_SIZE : 0; + if ((len > INT_MAX) || ((len % WC_AES_BLOCK_SIZE) != 0) || + (tls && ((pLen < off) || + (len != (size_t)off + + (((size_t)(pLen - off) + SHA256_DIGEST_LENGTH + + WC_AES_BLOCK_SIZE) & ~(size_t)(WC_AES_BLOCK_SIZE - 1)))))) { + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "Invalid AES-CBC-HMAC length"); + return -1; + } if (!tls) { WOLFENGINE_MSG(WE_LOG_CIPHER, "Not being called from TLS"); pLen = (int)len; @@ -178,7 +236,7 @@ static int we_aes_cbc_hmac_enc(we_AesCbcHmac* aes, unsigned char *out, ret = -1; } } - if (ret != -1) { + if ((ret != -1) && tls) { /* Record layer MACed in ctrl function. */ /* MAC the handshake message/data. */ WOLFENGINE_MSG(WE_LOG_CIPHER, "MAC handshake message/data: len = %d", @@ -218,19 +276,101 @@ static int we_aes_cbc_hmac_enc(we_AesCbcHmac* aes, unsigned char *out, rc = wc_AesCbcEncrypt(&aes->aes, out + off, in + off, (int)len - off); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesCbcEncrypt", rc); - ret = 0; + ret = -1; } else { ret = (int)len; WOLFENGINE_BUFFER(WE_LOG_CIPHER, out + off, (int)(len - off)); } } + if (tls) { + aes->pLen = 0; + aes->tls = 0; + aes->tls11 = 0; + } WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_aes_cbc_hmac_enc", ret); return ret; } +/* Return an all-ones mask for equal values. */ +static word32 we_cbc_ct_eq(word32 a, word32 b) +{ + word32 diff = a ^ b; + + return 0U - (1U ^ ((diff | (0U - diff)) >> 31)); +} + +/* Arguments are bounded by the 16-bit TLS record length. */ +static word32 we_cbc_ct_lt(word32 a, word32 b) +{ + return 0U - ((a - b) >> 31); +} + +/* Balance HMAC work and compare the MAC at public candidate offsets. */ +static int we_aes_cbc_hmac_verify_ct(Hmac* hmac, + const unsigned char* header, const unsigned char* plain, + word32 maxMsgLen, word32 msgLen, word32 pad) +{ + unsigned char candidateHeader[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char digest[SHA256_DIGEST_LENGTH]; + unsigned char dummy[WC_SHA256_BLOCK_SIZE] = {0}; + unsigned char dummyDigest[SHA256_DIGEST_LENGTH]; + word32 maxBlocks = (EVP_AEAD_TLS1_AAD_LEN + maxMsgLen + 72) / + WC_SHA256_BLOCK_SIZE; + word32 realBlocks = (EVP_AEAD_TLS1_AAD_LEN + msgLen + 72) / + WC_SHA256_BLOCK_SIZE; + word32 dummyBlocks = maxBlocks - realBlocks + 1; + word32 matched = 0; + word32 i; + word32 j; + int rc = 0; + + XMEMCPY(candidateHeader, header, sizeof(candidateHeader)); + candidateHeader[sizeof(candidateHeader) - 2] = (unsigned char)(msgLen >> 8); + candidateHeader[sizeof(candidateHeader) - 1] = (unsigned char)msgLen; + rc = wc_HmacUpdate(hmac, candidateHeader, sizeof(candidateHeader)); + if (rc == 0) { + rc = wc_HmacUpdate(hmac, plain, msgLen); + } + if (rc == 0) { + rc = wc_HmacFinal(hmac, digest); + } + /* A padding byte changes the message by at most 255 bytes, so at most + * five dummy blocks balance the SHA-256 compression count. Finalize the + * dummy HMAC so the context is ready for the next record. */ + for (i = 0; (rc == 0) && (i < 5); i++) { + word32 size = sizeof(dummy) & we_cbc_ct_lt(i, dummyBlocks); + + rc = wc_HmacUpdate(hmac, dummy, size); + } + if (rc == 0) { + rc = wc_HmacFinal(hmac, dummyDigest); + } + + if (rc == 0) { + /* Probe every possible MAC position at public offsets. */ + for (i = 0; i < 256; i++) { + word32 candidateLen = i <= maxMsgLen ? maxMsgLen - i : 0; + word32 mismatch = 0; + + for (j = 0; j < sizeof(digest); j++) { + mismatch |= digest[j] ^ plain[candidateLen + j]; + } + matched |= we_cbc_ct_eq(i, pad) & + we_cbc_ct_eq(mismatch, 0) & + we_cbc_ct_lt(i, maxMsgLen + 1); + } + } + + OPENSSL_cleanse(candidateHeader, sizeof(candidateHeader)); + OPENSSL_cleanse(digest, sizeof(digest)); + OPENSSL_cleanse(dummy, sizeof(dummy)); + OPENSSL_cleanse(dummyDigest, sizeof(dummyDigest)); + return (rc == 0) && (matched != 0); +} + /** * Decrypt and verify MAC using wolfSSL. * @@ -247,22 +387,34 @@ static int we_aes_cbc_hmac_dec(we_AesCbcHmac* aes, unsigned char *out, int ret = 0; int rc; int off = 0; - unsigned char pb; int pLen; int tls; - unsigned char mac[SHA256_DIGEST_LENGTH]; - int i; + word32 payloadLen; + word32 maxMsgLen; + word32 msgLen; + word32 pad; + word32 invalid; + word32 i; + word32 scan; WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_aes_cbc_hmac_dec"); /* Get payload length. */ pLen = aes->pLen; tls = (pLen != 0); - if (aes->tls11) { + off = (tls && aes->tls11) ? WC_AES_BLOCK_SIZE : 0; + if ((len > INT_MAX) || (len < (size_t)off) || + (((len - (size_t)off) % WC_AES_BLOCK_SIZE) != 0) || + (tls && ((len - (size_t)off < SHA256_DIGEST_LENGTH + 1) || + (len != (size_t)((aes->tlsAAD[pLen - 2] << 8) | + aes->tlsAAD[pLen - 1]))))) { + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "Invalid AES-CBC-HMAC length"); + ret = -1; + } + if ((ret != -1) && tls && aes->tls11) { /* TLS v1.1 and v1.2 have IV before message. */ WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting AES IV, aes->tls11 = %d", aes->tls11); - off = WC_AES_BLOCK_SIZE; rc = wc_AesSetIV(&aes->aes, in); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetIV", rc); @@ -286,72 +438,34 @@ static int we_aes_cbc_hmac_dec(we_AesCbcHmac* aes, unsigned char *out, } } if ((ret != -1) && tls) { - /* TODO: not constant time. */ - /* Remove padding. */ - pb = out[off + ret - 1]; - if (pb >= WC_AES_BLOCK_SIZE) { - ret = -1; - } - for (i = 1; (ret != -1) && (i <= pb); i++) { - if (out[off + ret - 1 - i] != pb) - ret = -1; - } - if (ret != -1) { - /* Record must hold the padding and MAC or the length underflows. */ - if (ret < pb + 1 + SHA256_DIGEST_LENGTH) { - ret = -1; - } - else { - /* Remove padding and MAC length. */ - ret -= pb + 1 + SHA256_DIGEST_LENGTH; - } + payloadLen = (word32)ret; + maxMsgLen = payloadLen - SHA256_DIGEST_LENGTH - 1; + pad = out[off + payloadLen - 1]; + msgLen = maxMsgLen - pad; + invalid = msgLen >> 31; + msgLen &= 0U - (1U ^ invalid); + scan = payloadLen < 256 ? payloadLen : 256; + for (i = 0; i < scan; i++) { + word32 mask = we_cbc_ct_lt(i, pad + 1); + + invalid |= (out[off + payloadLen - 1 - i] ^ pad) & mask; } - /* Update record header to have correct message length. */ - aes->tlsAAD[aes->pLen - 2] = ret >> 8; - aes->tlsAAD[aes->pLen - 1] = ret; - - /* MAC the record header. */ - WOLFENGINE_MSG(WE_LOG_CIPHER, "Generate MAC over record header: " - "len = %d", aes->pLen); - rc = we_hmac_update(&aes->hmac, aes->tlsAAD, aes->pLen); - if (rc != 1) { - WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "we_hmac_update", rc); - ret = -1; - } - } - /* TODO: not constant time. */ - if (ret != -1) { - /* MAC the message/input. */ - WOLFENGINE_MSG(WE_LOG_CIPHER, "Generate MAC over message/input, " - "len = %d", ret); - rc = we_hmac_update(&aes->hmac, out + off, ret); - if (rc != 1) { - WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "we_hmac_update", rc); + rc = we_aes_cbc_hmac_verify_ct(&aes->hmac, aes->tlsAAD, + out + off, maxMsgLen, msgLen, pad); + if ((rc == 0) || (invalid != 0)) { + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "MAC check failed"); ret = -1; } - } - if (ret != -1) { - /* Calculate MAC. */ - rc = wc_HmacFinal(&aes->hmac, mac); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_HmacFinal", rc); - ret = -1; + else { + ret = (int)msgLen; } } - if (ret != -1) { - WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "Generated MAC:"); - WOLFENGINE_BUFFER(WE_LOG_CIPHER, mac, SHA256_DIGEST_LENGTH); - /* Check MAC. */ - pb = 0; - for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { - pb |= mac[i] ^ out[off + ret + i]; - } - if (pb != 0) { - WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "MAC check failed"); - ret = -1; - } + if (tls) { + aes->pLen = 0; + aes->tls = 0; + aes->tls11 = 0; } WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_aes_cbc_hmac_dec", ret); @@ -375,24 +489,33 @@ static int we_aes_cbc_hmac_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { int ret = 1; - we_AesCbcHmac* aes; + we_AesCbcHmac* aes = NULL; WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_aes_cbc_hmac_cipher"); WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [ctx = %p, out = %p, in = %p, " "len = %zu]", ctx, out, in, len); - /* Get the AES-CBC object to work with. */ - aes = (we_AesCbcHmac *)EVP_CIPHER_CTX_get_cipher_data(ctx); - if (aes == NULL) { + if ((in == NULL) && (len == 0)) { + ret = 0; + } + else { + /* Get the AES-CBC object to work with. */ + aes = (we_AesCbcHmac *)EVP_CIPHER_CTX_get_cipher_data(ctx); + } + if ((ret != 0) && (aes == NULL)) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, "EVP_CIPHER_CTX_get_cipher_data", aes); ret = -1; } - else if (aes->enc) { + else if ((ret != 0) && ((!aes->keySet) || (in == NULL) || + (out == NULL) || (aes->tls && !aes->hmacKeySet))) { + ret = -1; + } + else if ((ret != 0) && aes->enc) { ret = we_aes_cbc_hmac_enc(aes, out, in, len); } - else { + else if (ret != 0) { ret = we_aes_cbc_hmac_dec(aes, out, in, len); } @@ -419,6 +542,9 @@ static int we_aes_cbc_hmac_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, unsigned char *tls; int tlsVer; int len; + unsigned char header[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char digest[SHA256_DIGEST_LENGTH]; + we_AesCbcHmac *copy; char errBuff[WOLFENGINE_MAX_LOG_WIDTH]; WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_aes_cbc_hmac_ctrl"); @@ -437,11 +563,31 @@ static int we_aes_cbc_hmac_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, } if (ret == 1) { switch (type) { + case EVP_CTRL_INIT: + XMEMSET(aes, 0, sizeof(*aes)); + break; + case EVP_CTRL_COPY: + copy = NULL; + if (ptr != NULL) { + copy = (we_AesCbcHmac *)EVP_CIPHER_CTX_get_cipher_data( + (EVP_CIPHER_CTX *)ptr); + } + if (copy != NULL) { + OPENSSL_cleanse(copy, sizeof(*copy)); + } + ret = 0; + break; case EVP_CTRL_AEAD_SET_MAC_KEY: WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_AEAD_SET_MAC_KEY"); + if (!aes->init || (arg < 0) || + ((ptr == NULL) && (arg != 0))) { + ret = 0; + break; + } /* Set the HMAC key. */ rc = wc_HmacSetKey(&aes->hmac, WC_SHA256, (const byte*)ptr, arg); + aes->hmacKeySet = (rc == 0); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_HmacSetKey", rc); ret = 0; @@ -450,48 +596,60 @@ static int we_aes_cbc_hmac_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, case EVP_CTRL_AEAD_TLS1_AAD: WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_AEAD_TLS1_AAD"); tls = (unsigned char *)ptr; - if (arg != EVP_AEAD_TLS1_AAD_LEN) { + if ((arg != EVP_AEAD_TLS1_AAD_LEN) || (ptr == NULL) || + !aes->hmacKeySet) { WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "AAD len != EVP_AEAD_TLS1_AAD_LEN"); - ret = -1; + ret = 0; } if (ret == 1) { /* Get the verion from the record layer. */ tlsVer = (tls[arg - 4] << 8) | tls[arg - 3]; - /* Record whether it is TLS v1.1 or above. */ - aes->tls11 = (tlsVer >= TLS1_1_VERSION); WOLFENGINE_MSG(WE_LOG_CIPHER, "tlsVer = %d, aes->enc = %d", tlsVer, aes->enc); if (aes->enc) { /* Get length from record layer. */ len = (tls[arg - 2] << 8) | tls[arg - 1]; - /* Store payload length. */ - aes->pLen = len; - if (aes->tls11) { + XMEMCPY(header, tls, sizeof(header)); + if (tlsVer >= TLS1_1_VERSION) { /* Must be space for IV. */ if (len < WC_AES_BLOCK_SIZE) { - ret = -1; + ret = 0; } else { /* Remove IV and update record header. */ len -= WC_AES_BLOCK_SIZE; - tls[arg - 2] = len >> 8; - tls[arg - 1] = len; + header[arg - 2] = len >> 8; + header[arg - 1] = len; + } + } + if ((ret == 1) && aes->tls) { + /* Drop a rejected record's header from the MAC. */ + rc = wc_HmacFinal(&aes->hmac, digest); + OPENSSL_cleanse(digest, sizeof(digest)); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, + "wc_HmacFinal", rc); + ret = 0; } } if (ret == 1) { /* MAC the record header. */ WOLFENGINE_MSG(WE_LOG_CIPHER, "Updating MAC with record header"); - rc = we_hmac_update(&aes->hmac, tls, arg); + rc = we_hmac_update(&aes->hmac, header, arg); if (rc != 1) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "we_hmac_update", rc); - ret = -1; + ret = 0; } } if (ret == 1) { + aes->pLen = (tls[arg - 2] << 8) | tls[arg - 1]; + aes->tls = 1; + aes->tls11 = (tlsVer >= TLS1_1_VERSION); + XMEMCPY(tls, header, sizeof(header)); /* Calculate length with padding. */ ret = ((len + SHA256_DIGEST_LENGTH + WC_AES_BLOCK_SIZE) & -WC_AES_BLOCK_SIZE) - len; @@ -502,6 +660,8 @@ static int we_aes_cbc_hmac_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, WOLFENGINE_MSG(WE_LOG_CIPHER, "Storing record header " "for later"); aes->pLen = arg; + aes->tls = 1; + aes->tls11 = (tlsVer >= TLS1_1_VERSION); XMEMCPY(aes->tlsAAD, ptr, arg); /* MAC size. */ ret = SHA256_DIGEST_LENGTH; @@ -526,9 +686,11 @@ static int we_aes_cbc_hmac_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, #define AES_CBC_HMAC_FLAGS \ (EVP_CIPH_FLAG_CUSTOM_CIPHER | \ EVP_CIPH_ALWAYS_CALL_INIT | \ + EVP_CIPH_CTRL_INIT | \ EVP_CIPH_CBC_MODE | \ EVP_CIPH_FLAG_DEFAULT_ASN1 | \ - EVP_CIPH_FLAG_AEAD_CIPHER) + EVP_CIPH_FLAG_AEAD_CIPHER | \ + EVP_CIPH_CUSTOM_COPY) /** AES128-CBC HMAC SHA256 EVP cipher method. */ EVP_CIPHER* we_aes128_cbc_hmac_ciph = NULL; @@ -554,6 +716,15 @@ static int we_init_aescbc_hmac_meth(EVP_CIPHER *cipher) if (ret == 1) { ret = EVP_CIPHER_meth_set_init(cipher, we_aes_cbc_hmac_init); } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (ret == 1) { + ret = EVP_CIPHER_meth_set_cleanup(cipher, we_aes_cbc_hmac_cleanup); + } +#else + if (ret == 1) { + cipher->cleanup = we_aes_cbc_hmac_cleanup; + } +#endif if (ret == 1) { ret = EVP_CIPHER_meth_set_do_cipher(cipher, we_aes_cbc_hmac_cipher); } diff --git a/src/we_aes_ccm.c b/src/we_aes_ccm.c index d5e17ac7..8325a22f 100644 --- a/src/we_aes_ccm.c +++ b/src/we_aes_ccm.c @@ -85,6 +85,10 @@ typedef struct we_AesCcm int L; /** Flag to indicate whether object initialized. */ unsigned int init:1; + /** Flag to indicate successful wolfCrypt AES initialization. */ + unsigned int aesInit:1; + /** Tag generated or explicitly supplied for the current operation. */ + unsigned int tagSet:1; /** Flag to indicate whether we are doing encrypt (1) or decrpyt (0). */ unsigned int enc:1; /** Flag to indicate whether doing this for TLS */ @@ -119,6 +123,9 @@ static int we_aes_ccm_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, ret = 0; } + if ((ret == 1) && (enc || (aes->enc != (unsigned int)enc))) { + aes->tagSet = 0; + } if ((ret == 1) && (((key == NULL) && (iv == NULL)) || (!aes->init))) { WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting defaults for we_AesCcm struct"); /* Default L size for OpenSSL is 8, used to calc nonce/iv size */ @@ -128,7 +135,9 @@ static int we_aes_ccm_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, aes->ivSet = 0; /* No tag set. */ aes->tagLen = 0; + aes->tagSet = 0; /* Start with no AAD. */ + OPENSSL_free(aes->aad); aes->aad = NULL; aes->aadLen = 0; aes->enc = enc; @@ -137,6 +146,16 @@ static int we_aes_ccm_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, /* Not doing CCM for TLS unless ctrl function called. */ aes->tls = 0; } + if ((ret == 1) && (key != NULL) && (!aes->aesInit)) { + rc = wc_AesInit(&aes->aes, NULL, INVALID_DEVID); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); + ret = 0; + } + else { + aes->aesInit = 1; + } + } if ((ret == 1) && (key != NULL)) { /* Set the AES-CCM key. */ WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting AES-CCM key (%d bytes)", @@ -153,12 +172,36 @@ static int we_aes_ccm_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, WOLFENGINE_MSG(WE_LOG_CIPHER, "Caching IV into aes->iv"); XMEMCPY(aes->iv, iv, aes->ivLen); } + if (ret == 1) { + /* Preserve a pending TLS header, but leave spent TLS mode on reinit. */ + if (aes->aad == NULL) { + aes->tls = 0; + } + aes->enc = enc; + } WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_aes_ccm_init", ret); return ret; } +static int we_aes_ccm_cleanup(EVP_CIPHER_CTX *ctx) +{ + we_AesCcm *aes = (we_AesCcm *)EVP_CIPHER_CTX_get_cipher_data(ctx); + + if (aes != NULL) { + OPENSSL_free(aes->aad); + aes->aad = NULL; + aes->aadLen = 0; + if (aes->aesInit) { + wc_AesFree(&aes->aes); + aes->aesInit = 0; + } + } + + return 1; +} + /** * Encrypt/decrypt the data for TLS. * One-shot encrypt/decrypt - not streaming. @@ -203,10 +246,10 @@ static int we_aes_ccm_tls_cipher(we_AesCcm *aes, unsigned char *out, /* Explicit nonce: encrypt uses the saved AAD sequence number, decrypt the * record. */ if (ret == 1) { - if (aes->enc && ((aes->aad == NULL) || - (aes->aadLen < EVP_CCM_TLS_EXPLICIT_IV_LEN))) { + if ((aes->aad == NULL) || + (aes->aadLen != EVP_AEAD_TLS1_AAD_LEN)) { WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, - "TLS AAD not set before AES-CCM encrypt"); + "TLS AAD not set before AES-CCM operation"); ret = -1; } else if (aes->enc) { @@ -358,19 +401,20 @@ static int we_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, ret = (int)len; } } - else if ((ret == 1) && (len > 0)) { + else if ((ret == 1) && ((len > 0) || (in != NULL))) { if (aes->tagLen == 0) { - /* Default to full size tag. */ - aes->tagLen = EVP_CCM_TLS_TAG_LEN; + /* OpenSSL defaults non-TLS CCM tags to 12 bytes. */ + aes->tagLen = 12; } if (aes->enc) { + aes->tagSet = 0; if (!aes->ivSet) { /* Set extern IV. */ WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting AES-CCM Nonce"); rc = wc_AesCcmSetNonce(&aes->aes, aes->iv, aes->ivLen); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, - "wc_AesCcmSetExtIV", rc); + "wc_AesCcmSetNonce", rc); ret = -1; } } @@ -394,17 +438,22 @@ static int we_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, /* Cache nonce/IV. */ XMEMCPY(aes->iv, aes->aes.reg, aes->ivLen); + aes->tagSet = 1; /* Return encrypted data length */ ret = (int)len; } } + else if (!aes->tagSet) { + ret = -1; + } else { + aes->tagSet = 0; /* Decrypt the data. */ rc = wc_AesCcmDecrypt(&aes->aes, out, in, (word32)len, aes->iv, aes->ivLen, aes->tag, aes->tagLen, aes->aad, aes->aadLen); if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesCcmDecrypt_ex", rc); + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesCcmDecrypt", rc); ret = -1; } if (ret == 1) { @@ -412,10 +461,6 @@ static int we_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "Decrypted %zu bytes " "(AES-CCM):", len); WOLFENGINE_BUFFER(WE_LOG_CIPHER, out, (unsigned int)len); - WOLFENGINE_MSG(WE_LOG_CIPHER, "Caching nonce/IV in aes->iv"); - - /* Cache nonce/IV. */ - XMEMCPY(aes->iv, aes->aes.reg, aes->ivLen); /* Return decrypted data length */ ret = (int)len; } @@ -425,10 +470,9 @@ static int we_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, OPENSSL_free(aes->aad); aes->aad = NULL; aes->aadLen = 0; - } else if ((ret == 1) && (in == NULL)) { - /* no error, but no input data or AAD to process, return 0 length */ - WOLFENGINE_MSG(WE_LOG_CIPHER, "No input data or AAd to process, " - "returning 0"); + } + else if (ret == 1) { + WOLFENGINE_MSG(WE_LOG_CIPHER, "No input data to process, returning 0"); ret = 0; } @@ -440,11 +484,9 @@ static int we_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, /** * Extra operations for AES-CCM. * Supported operations include: - * - EVP_CTRL_SET_IV (version 3.0+): get IV from wolfengine object * - EVP_CTRL_AEAD_SET_IVLEN: set the length of an IV/nonce * - EVP_CTRL_GET_IVLEN: get the total IV/nonce length * - EVP_CTRL_CCM_SET_IV_FIXED: set the fixed part of an IV/nonce - * - EVP_CTRL_CCM_IV_GEN: set the generated IV/nonce * - EVP_CTRL_AEAD_GET_TAG: get the tag value after encrypt * - EVP_CTRL_AEAD_SET_TAG: set the tag value before decrypt * - EVP_CTRL_AEAD_TLS1_AAD: set AAD for TLS @@ -452,7 +494,7 @@ static int we_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, * @param ctx [in.out] EVP cipher context of operation. * @param type [in] Type of operation to perform. * @param arg [in] Integer argument. - * @param ptr [in] Pointer argument. + * @param ptr [in,out] Pointer argument, direction depends on type. * @return 1 on success and 0 on failure. */ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) @@ -474,14 +516,17 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) } if (ret == 1) { switch (type) { + case EVP_CTRL_INIT: + XMEMSET(aes, 0, sizeof(*aes)); + break; case EVP_CTRL_CCM_SET_L: WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_CCM_SET_L"); /* Set the length field, L * arg [in] value to use for length field (L) * ptr [in] Unused */ - if ((arg <= 0) || - arg < CCM_LEN_FIELD_MIN_SZ || arg > CCM_LEN_FIELD_MAX_SZ) { + if ((arg < CCM_LEN_FIELD_MIN_SZ) || + (arg > CCM_LEN_FIELD_MAX_SZ)) { WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "Invalid CCM length field"); ret = 0; @@ -497,7 +542,8 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) * arg [in] length of IV/nonce to use * ptr [in] Unused */ - if ((arg <= 0) || (arg > CCM_NONCE_MAX_SZ)) { + if ((arg < CCM_NONCE_MIN_SZ) || + (arg > CCM_NONCE_MAX_SZ)) { WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "Invalid nonce length"); ret = 0; } @@ -510,7 +556,7 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) case EVP_CTRL_GET_IVLEN: WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_GET_IVLEN"); - /* Set the generated IV + /* Get the IV length * ptr [out] length of iv */ *(int *)ptr = aes->ivLen; @@ -522,7 +568,10 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) * arg [in] size of fixed part of IV/nonce * ptr [in] fixed part of IV/nonce data */ - if (arg == EVP_CCM_TLS_FIXED_IV_LEN) { + if (ptr == NULL) { + ret = 0; + } + else if (arg == EVP_CCM_TLS_FIXED_IV_LEN) { WOLFENGINE_MSG(WE_LOG_CIPHER, "Setting TLS fixed IV len"); XMEMCPY(aes->iv, ptr, arg); XMEMCPY(EVP_CIPHER_CTX_iv_noconst(ctx), aes->iv, arg); @@ -536,13 +585,15 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_AEAD_GET_TAG"); /* Get the tag from encryption. * arg [in] size of buffer - * ptr [in] buffer to copy into + * ptr [out] buffer to copy into */ - if ((!aes->enc) || (arg <= 0) || (arg > aes->tagLen)) { + if ((!aes->enc) || (!aes->tagSet) || (arg <= 0) || + (arg > aes->tagLen)) { ret = 0; } else { XMEMCPY(ptr, aes->tag, arg); + aes->tagSet = 0; } break; @@ -552,13 +603,18 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) * arg [in] size of tag * ptr [in] tag data to copy */ - if ((arg <= 0) || (arg > WC_AES_BLOCK_SIZE)) { - WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "Invalid tag size"); + if ((arg < 4) || (arg > WC_AES_BLOCK_SIZE) || + ((arg & 1) != 0) || (aes->enc && (ptr != NULL))) { + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "Invalid tag parameters"); ret = 0; } else { if (!aes->enc && (ptr != NULL)) { XMEMCPY(aes->tag, ptr, arg); + aes->tagSet = 1; + } + else if (aes->enc || (arg != aes->tagLen)) { + aes->tagSet = 0; } aes->tagLen = arg; } @@ -631,6 +687,18 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) } break; + case EVP_CTRL_COPY: + if (ptr != NULL) { + we_AesCcm *dst = (we_AesCcm *) + EVP_CIPHER_CTX_get_cipher_data((EVP_CIPHER_CTX *)ptr); + + if ((dst != NULL) && (dst != aes)) { + OPENSSL_cleanse(dst, sizeof(*dst)); + } + } + ret = 0; + break; + default: XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); @@ -650,7 +718,9 @@ static int we_aes_ccm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) (EVP_CIPH_FLAG_CUSTOM_CIPHER | \ EVP_CIPH_CUSTOM_IV_LENGTH | \ EVP_CIPH_CUSTOM_IV | \ + EVP_CIPH_CUSTOM_COPY | \ EVP_CIPH_ALWAYS_CALL_INIT | \ + EVP_CIPH_CTRL_INIT | \ EVP_CIPH_FLAG_AEAD_CIPHER | \ EVP_CIPH_FLAG_DEFAULT_ASN1 | \ EVP_CIPH_CCM_MODE) @@ -681,6 +751,13 @@ static int we_init_aesccm_meth(EVP_CIPHER *cipher) if (ret == 1) { ret = EVP_CIPHER_meth_set_init(cipher, we_aes_ccm_init); } + if (ret == 1) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + ret = EVP_CIPHER_meth_set_cleanup(cipher, we_aes_ccm_cleanup); +#else + cipher->cleanup = we_aes_ccm_cleanup; +#endif + } if (ret == 1) { ret = EVP_CIPHER_meth_set_do_cipher(cipher, we_aes_ccm_cipher); } diff --git a/src/we_aes_ctr.c b/src/we_aes_ctr.c index 11ced4e4..e73cbea7 100644 --- a/src/we_aes_ctr.c +++ b/src/we_aes_ctr.c @@ -35,6 +35,8 @@ typedef struct we_AesCtr /* The wolfSSL AES data object. */ Aes aes; word32 inited; + unsigned char key[32]; + word32 keyLen; } we_AesCtr; @@ -43,7 +45,7 @@ typedef struct we_AesCtr * * @param ctx [in,out] EVP cipher context of operation. * @param key [in] AES key - 16/24/32 bytes. - * @param iv [in] Initialization Vector - 12 bytes. + * @param iv [in] Initialization Vector/counter - 16 bytes. * @param enc [in] 1 when initializing for encrypt and 0 when decrypt. * @return 1 on success and 0 on failure. */ @@ -75,7 +77,9 @@ static int we_aes_ctr_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); ret = 0; } - aes->inited = 1; + else { + aes->inited = 1; + } } if ((ret == 1) && (key != NULL)) { if (tmpIv == NULL) { @@ -87,8 +91,15 @@ static int we_aes_ctr_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, AES_ENCRYPTION); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetKey", rc); + OPENSSL_cleanse(aes->key, sizeof(aes->key)); + aes->keyLen = 0; ret = 0; } + else { + OPENSSL_cleanse(aes->key, sizeof(aes->key)); + aes->keyLen = EVP_CIPHER_CTX_key_length(ctx); + XMEMCPY(aes->key, key, aes->keyLen); + } } if ((ret == 1) && (iv != NULL)) { rc = wc_AesSetIV(&aes->aes, iv); @@ -110,6 +121,91 @@ static int we_aes_ctr_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, return ret; } +/** + * Cleanup the internal AES-CTR object. Does not free object. + * + * @param ctx [in] EVP cipher context. + * @returns 1 on success and 0 on failure. + */ +static int we_aes_ctr_cleanup(EVP_CIPHER_CTX *ctx) +{ + int ret = 1; + we_AesCtr *aes; + + aes = (we_AesCtr *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if (aes == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, + "EVP_CIPHER_CTX_get_cipher_data", aes); + ret = 0; + } + + if ((ret == 1) && (aes->inited != 0)) { + wc_AesFree(&aes->aes); + } + if (aes != NULL) { + OPENSSL_cleanse(aes, sizeof(*aes)); + } + + return ret; +} + +static int we_aes_ctr_copy(EVP_CIPHER_CTX *ctx, EVP_CIPHER_CTX *dstCtx) +{ + we_AesCtr *src = (we_AesCtr *)EVP_CIPHER_CTX_get_cipher_data(ctx); + we_AesCtr *dst; + unsigned char counter[WC_AES_BLOCK_SIZE]; + unsigned char discard[WC_AES_BLOCK_SIZE] = { 0 }; + word32 left; + word32 num; + int ret = 1; + int i; + + if (dstCtx == NULL || src == NULL) { + return 0; + } + dst = (we_AesCtr *)EVP_CIPHER_CTX_get_cipher_data(dstCtx); + if (dst == NULL || dst == src) { + return 0; + } + left = src->aes.left; + num = (WC_AES_BLOCK_SIZE - left) % WC_AES_BLOCK_SIZE; + /* OpenSSL copied the wrapper, but backend resources need fresh ownership. */ + XMEMSET(&dst->aes, 0, sizeof(dst->aes)); + dst->inited = 0; + if (src->inited != 0) { + ret = wc_AesInit(&dst->aes, NULL, INVALID_DEVID) == 0; + if (ret == 1) { + dst->inited = 1; + } + } + if (ret == 1 && src->keyLen != 0) { + XMEMCPY(counter, EVP_CIPHER_CTX_iv(ctx), sizeof(counter)); + ret = left <= WC_AES_BLOCK_SIZE && + src->keyLen <= sizeof(src->key); + /* A partial block has already advanced the counter once. */ + if (ret == 1 && num != 0) { + for (i = sizeof(counter) - 1; i >= 0; i--) { + if (counter[i]-- != 0) { + break; + } + } + } + if (ret == 1) { + ret = wc_AesSetKey(&dst->aes, src->key, src->keyLen, counter, + AES_ENCRYPTION) == 0; + } + if (ret == 1 && num != 0) { + ret = wc_AesCtrEncrypt(&dst->aes, discard, discard, num) == 0; + } + } + OPENSSL_cleanse(discard, sizeof(discard)); + if (ret == 0) { + /* OpenSSL skips cipher cleanup after a failed custom copy. */ + we_aes_ctr_cleanup(dstCtx); + } + return ret; +} + /** * Encrypt/decrypt the data using wolfSSL. * @@ -131,7 +227,7 @@ static int we_aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_aes_ctr_cipher"); WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [ctx = %p, out = %p, in = %p, " - "len = %d]", ctx, out, in, len); + "len = %zu]", ctx, out, in, len); /* Get the AES-CTR object to work with. */ aes = (we_AesCtr *)EVP_CIPHER_CTX_get_cipher_data(ctx); @@ -159,7 +255,7 @@ static int we_aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, ret = (int)len; } } - else if (in == NULL) { + else { ret = 0; } } @@ -172,7 +268,7 @@ static int we_aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, /** * Extra operations for AES-CTR. * - * No supported operations yet. + * Initialize or copy independent cipher state. * * @param ctx [in] EVP cipher context of operation. * @param type [in] Type of operation to perform. @@ -191,7 +287,6 @@ static int we_aes_ctr_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) "arg = %d, ptr = %p]", ctx, type, arg, ptr); (void)arg; - (void)ptr; /* Get the AES-CTR data to work with. */ aes = (we_AesCtr *)EVP_CIPHER_CTX_get_cipher_data(ctx); @@ -204,7 +299,12 @@ static int we_aes_ctr_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) switch (type) { case EVP_CTRL_INIT: { - XMEMSET(aes, 0, sizeof(we_AesCtr)); + XMEMSET(aes, 0, sizeof(*aes)); + break; + } + case EVP_CTRL_COPY: + { + ret = we_aes_ctr_copy(ctx, (EVP_CIPHER_CTX *)ptr); break; } default: @@ -222,11 +322,13 @@ static int we_aes_ctr_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) } /** Flags for AES-CTR method. */ +#define AES_CTR_COPY_FLAG EVP_CIPH_CUSTOM_COPY #define AES_CTR_FLAGS \ (EVP_CIPH_ALWAYS_CALL_INIT | \ EVP_CIPH_CTRL_INIT | \ EVP_CIPH_FLAG_CUSTOM_CIPHER | \ EVP_CIPH_FLAG_DEFAULT_ASN1 | \ + AES_CTR_COPY_FLAG | \ EVP_CIPH_CTR_MODE) /** AES128-CTR EVP cipher method. */ @@ -254,6 +356,13 @@ static int we_init_aesctr_meth(EVP_CIPHER *cipher) if (ret == 1) { ret = EVP_CIPHER_meth_set_init(cipher, we_aes_ctr_init); } + if (ret == 1) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + ret = EVP_CIPHER_meth_set_cleanup(cipher, we_aes_ctr_cleanup); +#else + cipher->cleanup = we_aes_ctr_cleanup; +#endif + } if (ret == 1) { ret = EVP_CIPHER_meth_set_do_cipher(cipher, we_aes_ctr_cipher); } diff --git a/src/we_aes_gcm.c b/src/we_aes_gcm.c index 7fbfcaf8..551cf6c9 100644 --- a/src/we_aes_gcm.c +++ b/src/we_aes_gcm.c @@ -19,7 +19,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include + #include +#include /* May not be available in FIPS builds of wolfSSL */ #ifndef GCM_NONCE_MAX_SZ @@ -33,6 +36,15 @@ #ifdef WE_HAVE_AESGCM +#define WE_GCM_BACKEND_FAILURE 100 + +static void we_aes_gcm_set_error(const char* operation) +{ + ERR_put_error(ERR_LIB_USER, 0, WE_GCM_BACKEND_FAILURE, + __FILE__, __LINE__); + ERR_add_error_data(2, "wolfEngine AES-GCM: ", operation); +} + /* * AES-GCM */ @@ -135,6 +147,10 @@ static int we_aes_gcm_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, } if (ret == 1) { + /* Preserve a pending TLS header, but leave spent TLS mode on reinit. */ + if (aes->aad == NULL) { + aes->tls = 0; + } aes->enc = enc; } @@ -143,7 +159,6 @@ static int we_aes_gcm_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, return ret; } -#if OPENSSL_VERSION_NUMBER >= 0x10100000L /** * Cleanup the internal AES-GCM object. Does not free object. * @@ -161,9 +176,7 @@ static int we_aes_gcm_cleanup(EVP_CIPHER_CTX *ctx) /* Get the AES-GCM data to work with. */ aes = (we_AesGcm *)EVP_CIPHER_CTX_get_cipher_data(ctx); if (aes == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, - "EVP_CIPHER_CTX_get_cipher_data", aes); - ret = 0; + return 1; } if (ret == 1) { @@ -185,7 +198,6 @@ static int we_aes_gcm_cleanup(EVP_CIPHER_CTX *ctx) return ret; } -#endif /** * Increment the 64-bit invocation field at the end of the IV/nonce. @@ -237,9 +249,10 @@ static int we_aes_gcm_tls_cipher(we_AesGcm *aes, unsigned char *out, ret = -1; } /* TLS AAD carries the record sequence number and must be set first. */ - if ((ret == 1) && aes->enc && (aes->aad == NULL)) { + if ((ret == 1) && ((aes->aad == NULL) || + (aes->aadLen != EVP_AEAD_TLS1_AAD_LEN))) { WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, - "TLS AAD not set before AES-GCM encrypt"); + "TLS AAD not set before AES-GCM operation"); ret = -1; } /* Doing the TLS variation. */ @@ -262,6 +275,7 @@ static int we_aes_gcm_tls_cipher(we_AesGcm *aes, unsigned char *out, aes->aadLen); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesGcmEncrypt_ex", rc); + we_aes_gcm_set_error("encryption failed"); ret = -1; } /* Advance the explicit nonce for the next record, matching OpenSSL. */ @@ -295,6 +309,10 @@ static int we_aes_gcm_tls_cipher(we_AesGcm *aes, unsigned char *out, EVP_GCM_TLS_TAG_LEN, aes->aad, aes->aadLen); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesGcmDecrypt", rc); + /* DTLS silently discards records that fail authentication. */ + if (rc != AES_GCM_AUTH_E) { + we_aes_gcm_set_error("decryption failed"); + } ret = -1; } if (ret == 1) { @@ -334,23 +352,32 @@ static int we_aes_gcm_update_aad(we_AesGcm* aes, const unsigned char* in, { int ret; unsigned char *p; + size_t newLen; WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_aes_gcm_update_aad"); WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [aes = %p, in = %p, len = %zu]", aes, in, len); - /* Resize stored AAD and append new data. */ - p = (unsigned char*)OPENSSL_realloc(aes->aad, aes->aadLen + (int)len); - if (p == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, "OPENSSL_realloc", p); + if ((aes->aadLen < 0) || (len > (size_t)INT_MAX) || + (len > (size_t)(INT_MAX - aes->aadLen))) { + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, "AES-GCM AAD length too large"); ret = -1; } else { - /* Copy in new data after existing data. */ - aes->aad = p; - XMEMCPY(aes->aad + aes->aadLen, in, len); - aes->aadLen += len; - ret = (int)len; + /* Resize stored AAD and append new data. */ + newLen = (size_t)aes->aadLen + len; + p = (unsigned char*)OPENSSL_realloc(aes->aad, newLen); + if (p == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_CIPHER, "OPENSSL_realloc", p); + ret = -1; + } + else { + /* Copy in new data after existing data. */ + aes->aad = p; + XMEMCPY(aes->aad + aes->aadLen, in, len); + aes->aadLen = (int)newLen; + ret = (int)len; + } } WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_aes_gcm_update_aad", ret); @@ -376,7 +403,7 @@ static int we_aes_gcm_update(we_AesGcm* aes, const unsigned char* in, int ret; WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_aes_gcm_update"); - WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [aes = %p, in = %p, len = %d, " + WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [aes = %p, in = %p, len = %zu, " "out = %p]", aes, in, len, out); if (len != 0 && in != NULL) { @@ -435,6 +462,7 @@ static int we_aes_gcm_final(we_AesGcm* aes) ret = wc_AesGcmSetExtIV(&aes->aes, aes->iv, aes->ivLen); if (ret != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesGcmSetExtIV", ret); + we_aes_gcm_set_error("IV setup failed"); ret = -1; } else { @@ -454,10 +482,11 @@ static int we_aes_gcm_final(we_AesGcm* aes) if (ret != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesGcmEncrypt_ex", ret); + we_aes_gcm_set_error("encryption failed"); ret = -1; } else { - WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "Encrypted %zu bytes " + WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "Encrypted %d bytes " "(AES-GCM):", aes->tmpLen); WOLFENGINE_BUFFER(WE_LOG_CIPHER, aes->tmp, aes->tmpLen); WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "AES-GCM tag:"); @@ -471,10 +500,11 @@ static int we_aes_gcm_final(we_AesGcm* aes) aes->tagLen, aes->aad, aes->aadLen); if (ret != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesGcmDecrypt", ret); + we_aes_gcm_set_error("decryption failed"); ret = -1; } else { - WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "Decrypted %zu bytes " + WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "Decrypted %d bytes " "(AES-GCM):", aes->tmpLen); WOLFENGINE_BUFFER(WE_LOG_CIPHER, aes->tmp, aes->tmpLen); } @@ -563,7 +593,7 @@ static int we_aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, * - EVP_CTRL_GET_IVLEN: get the total IV/nonce length * - EVP_CTRL_AEAD_SET_IVLEN: set the length of an IV/nonce * - EVP_CTRL_GCM_SET_IV_FIXED: set the fixed part of an IV/nonce - * - EVP_CTRL_GCM_IV_GEN: set the generated IV/nonce + * - EVP_CTRL_GCM_IV_GEN: get the generated IV/nonce * - EVP_CTRL_AEAD_GET_TAG: get the tag value after encrypt * - EVP_CTRL_AEAD_SET_TAG: set the tag value before decrypt * - EVP_CTRL_AEAD_TLS1_AAD: set AAD for TLS @@ -571,7 +601,7 @@ static int we_aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, * @param ctx [in.out] EVP cipher context of operation. * @param type [in] Type of operation to perform. * @param arg [in] Integer argument. - * @param ptr [in] Pointer argument. + * @param ptr [in,out] Pointer argument; direction depends on type. * @return 1 on success and 0 on failure. */ static int we_aes_gcm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) @@ -615,6 +645,23 @@ static int we_aes_gcm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) aes->outputBuf = NULL; break; + case EVP_CTRL_COPY: + /* OpenSSL passes the live source as ctx and the copied + * destination as ptr. Clear only the destination's copied + * pointers before rejecting the unsupported copy. */ + if (ptr != NULL) { + we_AesGcm *dst = (we_AesGcm *) + EVP_CIPHER_CTX_get_cipher_data((EVP_CIPHER_CTX *)ptr); + + if (dst != NULL) { + OPENSSL_cleanse(dst, sizeof(*dst)); + } + } + WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, + "AES-GCM context copy not supported"); + ret = 0; + break; + case EVP_CTRL_AEAD_SET_IVLEN: WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_AEAD_SET_IVLEN"); /* Set the IV/nonce length to use @@ -695,9 +742,9 @@ static int we_aes_gcm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) case EVP_CTRL_GCM_IV_GEN: WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_GCM_IV_GEN"); - /* Set the generated IV + /* Get the generated IV * arg [in] size of generated IV/nonce - * ptr [in] generated IV/nonce data + * ptr [out] generated IV/nonce data */ if ((arg <= 0) || (arg > GCM_NONCE_MAX_SZ) || (ptr == NULL) || (arg > aes->ivLen) || (!aes->ivFixed)) { @@ -716,7 +763,7 @@ static int we_aes_gcm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) WOLFENGINE_MSG(WE_LOG_CIPHER, "EVP_CTRL_AEAD_GET_TAG"); /* Get the tag from encryption. * arg [in] size of buffer - * ptr [in] buffer to copy into + * ptr [out] buffer to copy into */ if ((!aes->enc) || (arg <= 0) || (arg > aes->tagLen)) { ret = 0; @@ -827,6 +874,7 @@ static int we_aes_gcm_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) #define AES_GCM_FLAGS \ (EVP_CIPH_FLAG_CUSTOM_CIPHER | \ EVP_CIPH_CUSTOM_IV | \ + EVP_CIPH_CUSTOM_COPY | \ EVP_CIPH_CUSTOM_IV_LENGTH | \ EVP_CIPH_ALWAYS_CALL_INIT | \ EVP_CIPH_CTRL_INIT | \ @@ -860,11 +908,9 @@ static int we_init_aesgcm_meth(EVP_CIPHER *cipher) if (ret == 1) { ret = EVP_CIPHER_meth_set_init(cipher, we_aes_gcm_init); } -#if OPENSSL_VERSION_NUMBER >= 0x10100000L if (ret == 1) { ret = EVP_CIPHER_meth_set_cleanup(cipher, we_aes_gcm_cleanup); } -#endif if (ret == 1) { ret = EVP_CIPHER_meth_set_do_cipher(cipher, we_aes_gcm_cipher); } diff --git a/src/we_cmac_compat.h b/src/we_cmac_compat.h new file mode 100644 index 00000000..7f503568 --- /dev/null +++ b/src/we_cmac_compat.h @@ -0,0 +1,24 @@ +/* CMAC cleanup compatibility, private to the engine. */ +#ifndef WOLFENGINE_CMAC_COMPAT_H +#define WOLFENGINE_CMAC_COMPAT_H + +/** Release CMAC state using the module's supported cleanup interface. */ +static void we_cmac_free(Cmac *cmac) +{ +#if defined(WE_NO_CMAC_FREE) || (defined(HAVE_FIPS) && \ + (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION <= 2))) +#ifdef WE_CMAC_HAS_BUFFERED_STATE + if (cmac->msg != NULL) { + OPENSSL_cleanse(cmac->msg, cmac->len); + /* Legacy wc_CMAC_Grow allocates with the default heap. */ + XFREE(cmac->msg, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } +#endif + wc_AesFree(&cmac->aes); + OPENSSL_cleanse(cmac, sizeof(*cmac)); +#else + (void)wc_CmacFree(cmac); +#endif +} + +#endif /* WOLFENGINE_CMAC_COMPAT_H */ diff --git a/src/we_des3_cbc.c b/src/we_des3_cbc.c index efc6a2f8..3a535df4 100644 --- a/src/we_des3_cbc.c +++ b/src/we_des3_cbc.c @@ -39,6 +39,8 @@ typedef struct we_Des3Cbc unsigned int init:1; /** Flag to indicate whether we are doing encrypt (1) or decrypt (0). */ unsigned int enc:1; + unsigned char key[DES3_KEY_SIZE]; + unsigned int keySet:1; } we_Des3Cbc; /** @@ -75,7 +77,7 @@ static int we_des3_cbc_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, } } - if ((ret == 1) && (key != NULL)) { + if ((ret == 1) && (key != NULL) && (!des3->init)) { WOLFENGINE_MSG(WE_LOG_CIPHER, "Initializing wolfCrypt Des3 " "structure: %p", &des3->des3); rc = wc_Des3Init(&des3->des3, NULL, INVALID_DEVID); @@ -83,8 +85,9 @@ static int we_des3_cbc_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_Des3Init", rc); ret = 0; } - - des3->init = 1; + else { + des3->init = 1; + } } if (ret == 1) { @@ -96,8 +99,14 @@ static int we_des3_cbc_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, enc ? DES_ENCRYPTION : DES_DECRYPTION); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_Des3_SetKey", rc); + OPENSSL_cleanse(des3->key, sizeof(des3->key)); + des3->keySet = 0; ret = 0; } + else { + XMEMCPY(des3->key, key, sizeof(des3->key)); + des3->keySet = 1; + } } } @@ -106,6 +115,66 @@ static int we_des3_cbc_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, return ret; } +/** + * Cleanup the internal DES3-CBC object. + * + * @param ctx [in] EVP cipher context. + * @return 1 on success and 0 on failure. + */ +static int we_des3_cbc_cleanup(EVP_CIPHER_CTX *ctx) +{ + int ret = 1; + we_Des3Cbc *des3; + + WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_des3_cbc_cleanup"); + + des3 = (we_Des3Cbc *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if ((des3 != NULL) && des3->init) { + wc_Des3Free(&des3->des3); + } + if (des3 != NULL) { + OPENSSL_cleanse(des3, sizeof(*des3)); + } + + WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_des3_cbc_cleanup", ret); + + return ret; +} + +static int we_des3_cbc_copy(EVP_CIPHER_CTX *ctx, EVP_CIPHER_CTX *dstCtx) +{ + we_Des3Cbc *src = (we_Des3Cbc *)EVP_CIPHER_CTX_get_cipher_data(ctx); + we_Des3Cbc *dst; + int ret = 1; + + if (src == NULL || dstCtx == NULL) { + return 0; + } + dst = (we_Des3Cbc *)EVP_CIPHER_CTX_get_cipher_data(dstCtx); + if (dst == NULL || dst == src) { + return 0; + } + /* OpenSSL copied buffering and IVs, but backend ownership is independent. */ + XMEMSET(&dst->des3, 0, sizeof(dst->des3)); + dst->init = 0; + if (src->init) { + ret = wc_Des3Init(&dst->des3, NULL, INVALID_DEVID) == 0; + if (ret == 1) { + dst->init = 1; + } + } + if (ret == 1 && src->keySet) { + ret = wc_Des3_SetKey(&dst->des3, src->key, + EVP_CIPHER_CTX_iv(ctx), + src->enc ? DES_ENCRYPTION : DES_DECRYPTION) == 0; + } + if (ret == 0) { + /* OpenSSL skips cipher cleanup after a failed custom copy. */ + we_des3_cbc_cleanup(dstCtx); + } + return ret; +} + /** * Encrypt the data using wolfSSL. * @@ -185,7 +254,7 @@ static int we_des3_cbc_decrypt(EVP_CIPHER_CTX *ctx, we_Des3Cbc* des3, rc = wc_Des3_CbcDecrypt(&des3->des3, out, in, (word32)len); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, - "wc_Des3_CbcEncrypt 1", rc); + "wc_Des3_CbcDecrypt", rc); ret = 0; } else { @@ -246,7 +315,8 @@ static int we_des3_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, } } if (ret == 1) { - XMEMCPY(EVP_CIPHER_CTX_iv_noconst(ctx), des3->des3.reg, DES_IV_SIZE); + XMEMCPY(EVP_CIPHER_CTX_iv_noconst(ctx), des3->des3.reg, + DES_BLOCK_SIZE); } WOLFENGINE_LEAVE(WE_LOG_CIPHER, "we_des3_cbc_cipher", ret); @@ -257,7 +327,7 @@ static int we_des3_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, /** * Extra operations for DES3-CBC. * - * No supported operations yet. + * Initializes private cipher state. * * @param ctx [in] EVP cipher context of operation. * @param type [in] Type of operation to perform. @@ -273,10 +343,9 @@ static int we_des3_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) WOLFENGINE_ENTER(WE_LOG_CIPHER, "we_des3_cbc_ctrl"); WOLFENGINE_MSG_VERBOSE(WE_LOG_CIPHER, "ARGS [ctx = %p, type = %d, " - "arg = %p, ptr = %p]", ctx, type, arg, ptr); + "arg = %d, ptr = %p]", ctx, type, arg, ptr); (void)arg; - (void)ptr; /* Get the DES3-CBC data to work with. */ des3 = (we_Des3Cbc *)EVP_CIPHER_CTX_get_cipher_data(ctx); @@ -287,6 +356,12 @@ static int we_des3_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) } if (ret == 1) { switch (type) { + case EVP_CTRL_INIT: + XMEMSET(des3, 0, sizeof(*des3)); + break; + case EVP_CTRL_COPY: + ret = we_des3_cbc_copy(ctx, (EVP_CIPHER_CTX *)ptr); + break; default: XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); @@ -313,6 +388,8 @@ static int we_des3_cbc_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) */ #define DES3_CBC_FLAGS \ (EVP_CIPH_FLAG_DEFAULT_ASN1 | \ + EVP_CIPH_CTRL_INIT | \ + EVP_CIPH_CUSTOM_COPY | \ EVP_CIPH_CBC_MODE) /** DES3-CBC EVP cipher method. */ @@ -340,6 +417,13 @@ static int we_init_des3cbc_meth(EVP_CIPHER *cipher) if (ret == 1) { ret = EVP_CIPHER_meth_set_init(cipher, we_des3_cbc_init); } + if (ret == 1) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + ret = EVP_CIPHER_meth_set_cleanup(cipher, we_des3_cbc_cleanup); +#else + cipher->cleanup = we_des3_cbc_cleanup; +#endif + } if (ret == 1) { ret = EVP_CIPHER_meth_set_do_cipher(cipher, we_des3_cbc_cipher); } diff --git a/src/we_dh.c b/src/we_dh.c index 98163cd9..4a4588cb 100644 --- a/src/we_dh.c +++ b/src/we_dh.c @@ -33,6 +33,11 @@ #define DEFAULT_PRIME_LEN 1024 +static int we_dh_prime_len_valid(int primeLen) +{ + return (primeLen == 1024) || (primeLen == 2048) || (primeLen == 3072); +} + /** * Data required to complete DH operations. */ @@ -304,6 +309,22 @@ static int we_dh_set_parameters(const DH *dh, we_Dh *engineDh) engineDh->qLen = qBufLen; } } + else if (ret == 1) { + if (engineDh->q != NULL) { + OPENSSL_free(engineDh->q); + engineDh->q = NULL; + } + engineDh->qLen = 0; + + /* Reinitialize the key because setting q to NULL does not clear an + * existing q on every supported wolfCrypt version. */ + wc_FreeDhKey(&engineDh->key); + rc = wc_InitDhKey(&engineDh->key); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_KE, "wc_InitDhKey", rc); + ret = 0; + } + } if (ret == 1) { /* Set p, g and q parameters into wolfSSL DH key. */ @@ -447,10 +468,10 @@ static int we_dh_generate_key_int(DH *dh, we_Dh *engineDh) rc); ret = 0; } - } #if defined(WE_DH_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) - wc_UnLockMutex(we_rng_mutex); + wc_UnLockMutex(we_rng_mutex); #endif + } } } @@ -758,7 +779,7 @@ static int we_dh_convert_params(DhKey *wolfDh, DH *osslDh) } if (ret == 1) { /* Allocate buffer for generator. */ - g = (unsigned char*)OPENSSL_malloc(pLen); + g = (unsigned char*)OPENSSL_malloc(gLen == 0 ? 1 : gLen); if (g == NULL) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_KE, "OPENSSL_malloc(g)", g); ret = 0; @@ -784,7 +805,7 @@ static int we_dh_convert_params(DhKey *wolfDh, DH *osslDh) ret = 0; } } - if (ret == 1) { + if ((ret == 1) && (qLen > 0)) { /* Allocate a big number and set value to be: Group prime. */ qBn = BN_bin2bn(q, qLen, NULL); if (qBn == NULL) { @@ -874,10 +895,10 @@ static int we_dh_paramgen_int(DH *dh, we_Dh *engineDh) WOLFENGINE_ERROR_FUNC(WE_LOG_KE, "wc_DhGenerateParams", rc); ret = 0; } - } #if defined(WE_DH_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) - wc_UnLockMutex(we_rng_mutex); + wc_UnLockMutex(we_rng_mutex); #endif + } if (ret == 1) { WOLFENGINE_MSG(WE_LOG_KE, "Converting DH params to OpenSSL DH"); @@ -895,35 +916,109 @@ static int we_dh_paramgen_int(DH *dh, we_Dh *engineDh) * * @param dh [in,out] OpenSSL DH object. * @param primeLen [in] Length of prime. - * @param g [in] Generator to use. (ignored) - * @param cb [in] Callback to show generation progress. (ignored) + * @param g [in] Generator to use. + * @param cb [in] Callback to show generation progress. * @returns 1 on success and 0 on failure. */ static int we_dh_generate_params(DH *dh, int primeLen, int g, BN_GENCB *cb) { - int ret = 1; - we_Dh *engineDh; + int ret = 0; +#ifndef HAVE_FIPS + we_Dh *engineDh = NULL; + DH *params = NULL; + const BIGNUM *paramP = NULL; + const BIGNUM *paramQ = NULL; + const BIGNUM *paramG = NULL; + BIGNUM *p = NULL; + BIGNUM *q = NULL; + BIGNUM *generator = NULL; +#endif WOLFENGINE_ENTER(WE_LOG_KE, "we_dh_generate_parameters"); WOLFENGINE_MSG_VERBOSE(WE_LOG_KE, "ARGS [dh = %p, primeLen = %d, g = %d, " "cb = %p]", dh, primeLen, g, cb); - /* Cannot set g or callback to wolfSSL parameter generation. */ +#ifdef HAVE_FIPS + (void)dh; + (void)primeLen; (void)g; (void)cb; - - /* Retrieve internal DH object. */ - engineDh = (we_Dh *)DH_get_ex_data(dh, WE_DH_EX_DATA_IDX); - if (engineDh == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_KE, "DH_get_ex_data", engineDh); + WOLFENGINE_ERROR_MSG(WE_LOG_KE, "Legacy DH parameter generation is not " + "supported in FIPS mode"); +#else + ret = 1; + if (!we_dh_prime_len_valid(primeLen)) { + WOLFENGINE_ERROR_MSG(WE_LOG_KE, "Invalid DH prime bit length"); + ret = 0; + } + if ((ret == 1) && (DH_get0_q(dh) != NULL)) { + WOLFENGINE_ERROR_MSG(WE_LOG_KE, "Cannot replace DH parameters with q"); ret = 0; } if (ret == 1) { - engineDh->primeLen = primeLen; - /* Generate the parameters with wolfSSL and copy into OpenSSL object. */ - ret = we_dh_paramgen_int(dh, engineDh); + engineDh = (we_Dh *)DH_get_ex_data(dh, WE_DH_EX_DATA_IDX); + if (engineDh == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_KE, "DH_get_ex_data", engineDh); + ret = 0; + } + } + + if (ret == 1) { + params = DH_new_method(NULL); + if (params == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_KE, "DH_new_method", params); + ret = 0; + } + } + if (ret == 1) { + ret = DH_set_method(params, DH_OpenSSL()); + if (ret != 1) { + WOLFENGINE_ERROR_FUNC(WE_LOG_KE, "DH_set_method", ret); + } + } + if (ret == 1) { + ret = DH_generate_parameters_ex(params, primeLen, g, cb); + if (ret != 1) { + WOLFENGINE_ERROR_FUNC(WE_LOG_KE, "DH_generate_parameters_ex", + ret); + } + } + if (ret == 1) { + DH_get0_pqg(params, ¶mP, ¶mQ, ¶mG); + p = BN_dup(paramP); + if (paramQ != NULL) + q = BN_dup(paramQ); + generator = BN_dup(paramG); + if ((p == NULL) || ((paramQ != NULL) && (q == NULL)) || + (generator == NULL)) { + WOLFENGINE_ERROR_MSG(WE_LOG_KE, "Failed to duplicate DH params"); + ret = 0; + } + } + if (ret == 1) { + ret = DH_set0_pqg(dh, p, q, generator); + if (ret != 1) { + WOLFENGINE_ERROR_FUNC(WE_LOG_KE, "DH_set0_pqg", ret); + } + else { + p = NULL; + q = NULL; + generator = NULL; + } } + if (ret == 1) { + ret = we_dh_set_parameters(dh, engineDh); + if (ret != 1) { + WOLFENGINE_ERROR_FUNC(WE_LOG_KE, "we_dh_set_parameters", ret); + } + } + + BN_free(generator); + BN_free(q); + BN_free(p); + DH_free(params); +#endif WOLFENGINE_LEAVE(WE_LOG_KE, "we_dh_generate_parameters", ret); @@ -1028,7 +1123,7 @@ static void we_dh_pkey_cleanup(EVP_PKEY_CTX *ctx) * - EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR: intended to set the generator, "g", * but doesn't actually do this, as wolfCrypt doesn't allow you to specify * the generator used in DH key creation. - * - EVP_PKEY_CTRL_DH_PAD: pad out secret to input length. + * - EVP_PKEY_CTRL_DH_PAD: pad secret to the DH modulus size. * - EVP_PKEY_CTRL_PEER_KEY: intended to set the peer key, but doesn't actually * do this, as we can get the peer key directly from the ctx when needed. * @@ -1036,7 +1131,8 @@ static void we_dh_pkey_cleanup(EVP_PKEY_CTX *ctx) * @param type [in] Type of operation to perform. * @param num [in] Integer parameter. * @param ptr [in] Pointer parameter. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_dh_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) { @@ -1064,7 +1160,7 @@ static int we_dh_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) WOLFENGINE_MSG(WE_LOG_KE, "EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN"); /* These are the sizes allowed by wolfCrypt. */ - if (num != 1024 && num != 2048 && num != 3072) { + if (!we_dh_prime_len_valid(num)) { WOLFENGINE_ERROR_MSG(WE_LOG_KE, "Invalid DH prime bit length."); ret = 0; @@ -1085,7 +1181,7 @@ static int we_dh_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) ret = 0; break; case EVP_PKEY_CTRL_DH_PAD: - dh->pad = num; + dh->pad = num != 0; break; case EVP_PKEY_CTRL_PEER_KEY: WOLFENGINE_MSG(WE_LOG_KE, "EVP_PKEY_CTRL_PEER_KEY"); @@ -1098,7 +1194,7 @@ static int we_dh_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); WOLFENGINE_ERROR_MSG(WE_LOG_KE, errBuff); - ret = 0; + ret = -2; break; } } @@ -1112,13 +1208,14 @@ static int we_dh_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) * Extra operations for working with DH. * Supported operations include: * - "dh_param": set the named parameters. - * - "dh_pad": pad out secret to input length. + * - "dh_pad": pad secret to the DH modulus size. * - "dh_paramgen_prime_len": set the length of the prime, "p." * * @param ctx [in] Public key context of operation. * @param type [in] Type of operation to perform. * @param value [in] String representing value. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_dh_pkey_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char* value) { @@ -1218,7 +1315,7 @@ static int we_dh_pkey_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, } /* Set padding requirement for secret output. */ else if (XSTRCMP(type, "dh_pad") == 0) { - dh->pad = XATOI(value); + dh->pad = XATOI(value) != 0; } else if (XSTRCMP(type, "dh_paramgen_prime_len") == 0) { ret = we_dh_pkey_ctrl(ctx, EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, @@ -1229,7 +1326,7 @@ static int we_dh_pkey_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl string %s", type); WOLFENGINE_ERROR_MSG(WE_LOG_KE, errBuff); - ret = 0; + ret = -2; } } @@ -1403,6 +1500,7 @@ static int we_dh_pkey_derive(EVP_PKEY_CTX *ctx, unsigned char *secret, DH *peerDh = NULL; const BIGNUM *peerPub = NULL; size_t totalLen = *secretLen; + size_t dhLen = 0; WOLFENGINE_ENTER(WE_LOG_KE, "we_dh_pkey_derive"); WOLFENGINE_MSG_VERBOSE(WE_LOG_KE, "ARGS [ctx = %p, secret = %p, " @@ -1433,16 +1531,25 @@ static int we_dh_pkey_derive(EVP_PKEY_CTX *ctx, unsigned char *secret, WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_KE, "EVP_PKEY_get0_DH", ourDh); ret = 0; } + else { + dhLen = (size_t)DH_size(ourDh); + } } if ((ret == 1) && (secret == NULL)) { /* Return the length of the secret only. */ - *secretLen = DH_size(ourDh); + *secretLen = dhLen; } else if (ret == 1) { + if (engineDh->pad && (totalLen < dhLen)) { + WOLFENGINE_ERROR_MSG(WE_LOG_KE, "DH secret buffer too small"); + ret = 0; + } + /* Get the peer's key. */ - peerKey = EVP_PKEY_CTX_get0_peerkey(ctx); - if (peerKey == NULL) { + if (ret == 1) + peerKey = EVP_PKEY_CTX_get0_peerkey(ctx); + if ((ret == 1) && (peerKey == NULL)) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_KE, "EVP_PKEY_CTX_get0_peerkey", peerKey); ret = 0; @@ -1480,13 +1587,11 @@ static int we_dh_pkey_derive(EVP_PKEY_CTX *ctx, unsigned char *secret, } } - /* When padding required and total buffer size is bigger than secret - * generated, ensure the buffer is zero padded at the front. */ - if ((ret == 1) && engineDh->pad && (totalLen != *secretLen)) { - XMEMMOVE(secret + totalLen - *secretLen, secret, *secretLen); - XMEMSET(secret, 0, totalLen - *secretLen); - /* Return the original length. */ - *secretLen = (int)totalLen; + /* Pad the generated secret to the DH modulus size. */ + if ((ret == 1) && engineDh->pad && (dhLen > *secretLen)) { + XMEMMOVE(secret + dhLen - *secretLen, secret, *secretLen); + XMEMSET(secret, 0, dhLen - *secretLen); + *secretLen = dhLen; } } diff --git a/src/we_digest.c b/src/we_digest.c index ea49637c..5473dd6c 100644 --- a/src/we_digest.c +++ b/src/we_digest.c @@ -21,6 +21,7 @@ #include +#define WE_DIGEST_UPDATE_MAX (1024U * 1024U) #if defined(WE_HAVE_SHA1) && defined(WE_SHA1_DIRECT) @@ -63,16 +64,26 @@ static int we_sha_init(EVP_MD_CTX *ctx) static int we_sha_update(EVP_MD_CTX *ctx, const void *data, size_t len) { int ret = 1, rc; + const byte *input = (const byte *)data; WOLFENGINE_ENTER(WE_LOG_DIGEST, "we_sha_update"); WOLFENGINE_MSG_VERBOSE(WE_LOG_DIGEST, "ARGS [ctx = %p, data = %p, " "len = %zu]", ctx, data, len); - rc = wc_ShaUpdate((wc_Sha*)EVP_MD_CTX_md_data(ctx), - (const byte*)data, (word32)len); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_ShaUpdate", rc); - ret = 0; + while ((ret == 1) && (len > 0)) { + word32 chunkLen = len > WE_DIGEST_UPDATE_MAX ? + WE_DIGEST_UPDATE_MAX : (word32)len; + + rc = wc_ShaUpdate((wc_Sha*)EVP_MD_CTX_md_data(ctx), input, + chunkLen); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_ShaUpdate", rc); + ret = 0; + } + else { + input += chunkLen; + len -= chunkLen; + } } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_sha_update", ret); @@ -141,7 +152,7 @@ int we_init_sha_meth(void) WOLFENGINE_ENTER(WE_LOG_DIGEST, "we_init_sha_meth"); - ret = (we_sha1_md = EVP_MD_meth_new(NID_sha, EVP_PKEY_NONE)) != NULL; + ret = (we_sha1_md = EVP_MD_meth_new(NID_sha1, EVP_PKEY_NONE)) != NULL; if (ret == 1) { ret = EVP_MD_meth_set_init(we_sha1_md, we_sha_init); } @@ -166,6 +177,7 @@ int we_init_sha_meth(void) if ((ret != 1) && (we_sha1_md != NULL)) { EVP_MD_meth_free(we_sha1_md); + we_sha1_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha_meth", ret); @@ -216,16 +228,26 @@ static int we_sha224_init(EVP_MD_CTX *ctx) static int we_sha224_update(EVP_MD_CTX *ctx, const void *data, size_t len) { int ret = 1, rc; + const byte *input = (const byte *)data; WOLFENGINE_ENTER(WE_LOG_DIGEST, "we_sha224_update"); WOLFENGINE_MSG_VERBOSE(WE_LOG_DIGEST, "ARGS [ctx = %p, data = %p, " "len = %zu]", ctx, data, len); - rc = wc_Sha224Update((wc_Sha224*)EVP_MD_CTX_md_data(ctx), - (const byte*)data, (word32)len); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_Sha224Update", rc); - ret = 0; + while ((ret == 1) && (len > 0)) { + word32 chunkLen = len > WE_DIGEST_UPDATE_MAX ? + WE_DIGEST_UPDATE_MAX : (word32)len; + + rc = wc_Sha224Update((wc_Sha224*)EVP_MD_CTX_md_data(ctx), input, + chunkLen); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_Sha224Update", rc); + ret = 0; + } + else { + input += chunkLen; + len -= chunkLen; + } } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_sha224_update", ret); @@ -320,6 +342,7 @@ int we_init_sha224_meth(void) if ((ret != 1) && (we_sha224_md != NULL)) { EVP_MD_meth_free(we_sha224_md); + we_sha224_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha224_meth", ret); @@ -370,16 +393,26 @@ static int we_sha256_init(EVP_MD_CTX *ctx) static int we_sha256_update(EVP_MD_CTX *ctx, const void *data, size_t len) { int ret = 1, rc; + const byte *input = (const byte *)data; WOLFENGINE_ENTER(WE_LOG_DIGEST, "we_sha256_update"); WOLFENGINE_MSG_VERBOSE(WE_LOG_DIGEST, "ARGS [ctx = %p, data = %p, " "len = %zu]", ctx, data, len); - rc = wc_Sha256Update((wc_Sha256*)EVP_MD_CTX_md_data(ctx), - (const byte*)data, (word32)len); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_Sha256Update", rc); - ret = 0; + while ((ret == 1) && (len > 0)) { + word32 chunkLen = len > WE_DIGEST_UPDATE_MAX ? + WE_DIGEST_UPDATE_MAX : (word32)len; + + rc = wc_Sha256Update((wc_Sha256*)EVP_MD_CTX_md_data(ctx), input, + chunkLen); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_Sha256Update", rc); + ret = 0; + } + else { + input += chunkLen; + len -= chunkLen; + } } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_sha256_update", ret); @@ -473,6 +506,7 @@ int we_init_sha256_meth(void) if ((ret != 1) && (we_sha256_md != NULL)) { EVP_MD_meth_free(we_sha256_md); + we_sha256_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha256_meth", ret); @@ -787,7 +821,7 @@ static int we_sha3_512_init(EVP_MD_CTX *ctx) * Digest some more data using wolfSSL. * * @param ctx [in] EVP digest context of operation. - * @param data [in] More data to digest with SHA-256. + * @param data [in] More data to digest with the selected algorithm. * @param len [in] Length of data to digest. * @return 1 on success and 0 on failure. */ @@ -796,6 +830,7 @@ static int we_digest_update(EVP_MD_CTX *ctx, const void *data, size_t len) { int ret = 1, rc; we_Digest *digest; + const byte *input = (const byte *)data; WOLFENGINE_ENTER(WE_LOG_DIGEST, "we_digest_update"); WOLFENGINE_MSG_VERBOSE(WE_LOG_DIGEST, "ARGS [ctx = %p, data = %p, " @@ -863,18 +898,25 @@ static int we_digest_update(EVP_MD_CTX *ctx, const void *data, size_t len) } if (tmp != NULL) { + OPENSSL_cleanse(tmp, WC_SHA512_BLOCK_SIZE); XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); } } else #endif - if (ret == 1) { - rc = wc_HashUpdate(&digest->hash, digest->hashType, (const byte*)data, - (word32)len); + while ((ret == 1) && (len > 0)) { + word32 chunkLen = len > WE_DIGEST_UPDATE_MAX ? + WE_DIGEST_UPDATE_MAX : (word32)len; + + rc = wc_HashUpdate(&digest->hash, digest->hashType, input, chunkLen); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_HashUpdate", rc); ret = 0; } + else { + input += chunkLen; + len -= chunkLen; + } } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_digest_update", ret); @@ -882,11 +924,154 @@ static int we_digest_update(EVP_MD_CTX *ctx, const void *data, size_t len) return ret; } +/** + * Copy a digest operation using wolfSSL. + * + * @param dstCtx [in, out] Destination EVP digest context. + * @param srcCtx [in] Source EVP digest context. + * @return 1 on success and 0 on failure. + */ +static int we_digest_copy(EVP_MD_CTX *dstCtx, const EVP_MD_CTX *srcCtx) +{ + int ret = 1; + int rc = BAD_FUNC_ARG; + we_Digest *dst; + const we_Digest *src; + + WOLFENGINE_ENTER(WE_LOG_DIGEST, "we_digest_copy"); + WOLFENGINE_MSG_VERBOSE(WE_LOG_DIGEST, "ARGS [dstCtx = %p, srcCtx = %p]", + dstCtx, srcCtx); + + if (dstCtx == srcCtx) { + WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_digest_copy", ret); + return ret; + } + + dst = (we_Digest *)EVP_MD_CTX_md_data(dstCtx); + src = (const we_Digest *)EVP_MD_CTX_md_data(srcCtx); + if ((dst == NULL) && (src == NULL)) { + /* Some EVP_PKEY methods copy a context before allocating md_data. */ + WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_digest_copy", ret); + return ret; + } + else if ((dst == NULL) || (src == NULL)) { + WOLFENGINE_ERROR_MSG(WE_LOG_DIGEST, "digest was NULL"); + ret = 0; + } + else if ((src->hashType == 0) && + EVP_MD_CTX_test_flags(srcCtx, EVP_MD_CTX_FLAG_NO_INIT)) { + /* HMAC reuses cleansed digest storage without initializing it. */ + XMEMSET(dst, 0, sizeof(*dst)); + WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_digest_copy", ret); + return ret; + } + if (ret == 1) { + dst->hashType = WC_HASH_TYPE_NONE; + + /* Keep wrapper metadata while clearing the active hash context. */ +#ifdef WE_HAVE_SHA1 + if (src->hashType == WC_HASH_TYPE_SHA) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha)); + rc = wc_ShaCopy((wc_Sha *)&src->hash, (wc_Sha *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA224 + if (src->hashType == WC_HASH_TYPE_SHA224) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha224)); + rc = wc_Sha224Copy((wc_Sha224 *)&src->hash, + (wc_Sha224 *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA256 + if (src->hashType == WC_HASH_TYPE_SHA256) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha256)); + rc = wc_Sha256Copy((wc_Sha256 *)&src->hash, + (wc_Sha256 *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA384 + if (src->hashType == WC_HASH_TYPE_SHA384) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha384)); + rc = wc_Sha384Copy((wc_Sha384 *)&src->hash, + (wc_Sha384 *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA512 + if (src->hashType == WC_HASH_TYPE_SHA512) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha512)); + rc = wc_Sha512Copy((wc_Sha512 *)&src->hash, + (wc_Sha512 *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA3_224 + if (src->hashType == WC_HASH_TYPE_SHA3_224) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha3)); + rc = wc_Sha3_224_Copy((wc_Sha3 *)&src->hash, + (wc_Sha3 *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA3_256 + if (src->hashType == WC_HASH_TYPE_SHA3_256) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha3)); + rc = wc_Sha3_256_Copy((wc_Sha3 *)&src->hash, + (wc_Sha3 *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA3_384 + if (src->hashType == WC_HASH_TYPE_SHA3_384) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha3)); + rc = wc_Sha3_384_Copy((wc_Sha3 *)&src->hash, + (wc_Sha3 *)&dst->hash); + } + else +#endif +#ifdef WE_HAVE_SHA3_512 + if (src->hashType == WC_HASH_TYPE_SHA3_512) { + XMEMSET(&dst->hash, 0, sizeof(wc_Sha3)); + rc = wc_Sha3_512_Copy((wc_Sha3 *)&src->hash, + (wc_Sha3 *)&dst->hash); + } + else +#endif + { + rc = BAD_FUNC_ARG; + } + + if (rc == 0) { + dst->hashType = src->hashType; + } + else { + WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_*Copy", rc); + dst->hashType = src->hashType; + rc = wc_HashFree(&dst->hash, dst->hashType); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_DIGEST, "wc_HashFree", rc); + } + else { + OPENSSL_cleanse(&dst->hash, sizeof(dst->hash)); + dst->hashType = WC_HASH_TYPE_NONE; + } + ret = 0; + } + } + + WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_digest_copy", ret); + + return ret; +} + /** * Finalize the digest operation. * * @param ctx [in] EVP digest context of operation. - * @param md [in] SHA-256 digest of data. + * @param md [out] Digest output for the selected algorithm. * @return 1 on success and 0 on failure. */ static int we_digest_final(EVP_MD_CTX *ctx, unsigned char *md) @@ -966,6 +1151,9 @@ static int we_init_digest_meth(EVP_MD *method) WOLFENGINE_MSG_VERBOSE(WE_LOG_DIGEST, "ARGS [method = %p]", method); ret = EVP_MD_meth_set_update(method, we_digest_update); + if (ret == 1) { + ret = EVP_MD_meth_set_copy(method, we_digest_copy); + } if (ret == 1) { ret = EVP_MD_meth_set_final(method, we_digest_final); } @@ -1031,6 +1219,7 @@ int we_init_sha_meth(void) if ((ret != 1) && (we_sha1_md != NULL)) { EVP_MD_meth_free(we_sha1_md); + we_sha1_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha_meth", ret); @@ -1066,12 +1255,17 @@ int we_init_ecdsa_sha1_meth(void) if (ret == 1) { ret = EVP_MD_meth_set_result_size(we_ecdsa_sha1_md, WC_SHA_DIGEST_SIZE); } + if (ret == 1) { + ret = EVP_MD_meth_set_input_blocksize(we_ecdsa_sha1_md, + WC_SHA_BLOCK_SIZE); + } if (ret == 1) { ret = we_init_digest_meth(we_ecdsa_sha1_md); } if ((ret != 1) && (we_ecdsa_sha1_md != NULL)) { EVP_MD_meth_free(we_ecdsa_sha1_md); + we_ecdsa_sha1_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_ecdsa_sha1_meth", ret); @@ -1113,6 +1307,7 @@ int we_init_sha224_meth(void) if ((ret != 1) && (we_sha224_md != NULL)) { EVP_MD_meth_free(we_sha224_md); + we_sha224_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha224_meth", ret); @@ -1153,6 +1348,7 @@ int we_init_sha256_meth(void) if ((ret != 1) && (we_sha256_md != NULL)) { EVP_MD_meth_free(we_sha256_md); + we_sha256_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha256_meth", ret); @@ -1193,6 +1389,7 @@ int we_init_sha384_meth(void) if ((ret != 1) && (we_sha384_md != NULL)) { EVP_MD_meth_free(we_sha384_md); + we_sha384_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha384_meth", ret); @@ -1233,6 +1430,7 @@ int we_init_sha512_meth(void) if ((ret != 1) && (we_sha512_md != NULL)) { EVP_MD_meth_free(we_sha512_md); + we_sha512_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha512_meth", ret); @@ -1275,6 +1473,7 @@ int we_init_sha3_224_meth(void) if ((ret != 1) && (we_sha3_224_md != NULL)) { EVP_MD_meth_free(we_sha3_224_md); + we_sha3_224_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha3_224_meth", ret); @@ -1317,6 +1516,7 @@ int we_init_sha3_256_meth(void) if ((ret != 1) && (we_sha3_256_md != NULL)) { EVP_MD_meth_free(we_sha3_256_md); + we_sha3_256_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha3_256_meth", ret); @@ -1359,6 +1559,7 @@ int we_init_sha3_384_meth(void) if ((ret != 1) && (we_sha3_384_md != NULL)) { EVP_MD_meth_free(we_sha3_384_md); + we_sha3_384_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha3_384_meth", ret); @@ -1401,6 +1602,7 @@ int we_init_sha3_512_meth(void) if ((ret != 1) && (we_sha3_512_md != NULL)) { EVP_MD_meth_free(we_sha3_512_md); + we_sha3_512_md = NULL; } WOLFENGINE_LEAVE(WE_LOG_DIGEST, "we_init_sha3_512_meth", ret); diff --git a/src/we_ecc.c b/src/we_ecc.c index c39bb3ac..20aaf6ff 100644 --- a/src/we_ecc.c +++ b/src/we_ecc.c @@ -132,7 +132,7 @@ static int we_ec_set_private(ecc_key *key, int curveId, const EC_KEY *ecKey) unsigned char* privBuf = NULL; WOLFENGINE_ENTER(WE_LOG_PK, "we_ec_set_private"); - WOLFENGINE_MSG_VERBOSE(WE_LOG_PK, "ARGS [key = %p, curveId = %p, " + WOLFENGINE_MSG_VERBOSE(WE_LOG_PK, "ARGS [key = %p, curveId = %d, " "ecKey = %p]", key, curveId, ecKey); /* Get the EC key private key as binary data. */ @@ -321,6 +321,8 @@ typedef struct we_Ecc #endif } we_Ecc; +static void we_ec_cleanup(EVP_PKEY_CTX *ctx); + /** * Initialize and set the data required to complete an EC operation. * @@ -332,6 +334,9 @@ static int we_ec_init(EVP_PKEY_CTX *ctx) int ret, rc; we_Ecc *ecc; int keyInited = 0; +#ifndef WE_ECC_USE_GLOBAL_RNG + int rngInited = 0; +#endif WOLFENGINE_ENTER(WE_LOG_PK, "we_ec_init"); WOLFENGINE_MSG_VERBOSE(WE_LOG_PK, "ARGS [ctx = %p]", ctx); @@ -358,7 +363,10 @@ static int we_ec_init(EVP_PKEY_CTX *ctx) #ifndef WE_ECC_USE_GLOBAL_RNG if (ret == 1) { rc = wc_InitRng(&ecc->rng); - if (rc != 0) { + if (rc == 0) { + rngInited = 1; + } + else { ret = 0; } } @@ -385,7 +393,9 @@ static int we_ec_init(EVP_PKEY_CTX *ctx) if (ret == 0 && ecc != NULL) { #ifndef WE_ECC_USE_GLOBAL_RNG - wc_FreeRng(&ecc->rng); + if (rngInited) { + wc_FreeRng(&ecc->rng); + } #endif /* Make sure wolfSSL EC key is freed if initialized. */ if (keyInited) { @@ -430,6 +440,7 @@ static int we_ec_p192_init(EVP_PKEY_CTX *ctx) WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "EC_GROUP_new_by_curve_name", ecc->group); ret = 0; + we_ec_cleanup(ctx); } } @@ -466,6 +477,7 @@ static int we_ec_p224_init(EVP_PKEY_CTX *ctx) WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "EC_GROUP_new_by_curve_name", ecc->group); ret = 0; + we_ec_cleanup(ctx); } } @@ -503,6 +515,7 @@ static int we_ec_p256_init(EVP_PKEY_CTX *ctx) WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "EC_GROUP_new_by_curve_name", ecc->group); ret = 0; + we_ec_cleanup(ctx); } } @@ -540,6 +553,7 @@ static int we_ec_p384_init(EVP_PKEY_CTX *ctx) WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "EC_GROUP_new_by_curve_name", ecc->group); ret = 0; + we_ec_cleanup(ctx); } } @@ -578,6 +592,7 @@ static int we_ec_p521_init(EVP_PKEY_CTX *ctx) WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "EC_GROUP_new_by_curve_name", ecc->group); ret = 0; + we_ec_cleanup(ctx); } } @@ -602,15 +617,88 @@ static int we_ec_copy(EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src) static int we_ec_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) #endif { + int ret = 1; + we_Ecc *srcEcc; + we_Ecc *dstEcc = NULL; + WOLFENGINE_ENTER(WE_LOG_PK, "we_ec_copy"); - /* Nothing to copy as src is empty. */ - (void)src; - (void)dst; + srcEcc = (we_Ecc *)EVP_PKEY_CTX_get_data(src); + EVP_PKEY_CTX_set_data(dst, NULL); + + if (srcEcc != NULL) { + ret = we_ec_init(dst); + } + if (ret == 1 && srcEcc != NULL) { + dstEcc = (we_Ecc *)EVP_PKEY_CTX_get_data(dst); + dstEcc->curveId = srcEcc->curveId; + dstEcc->curveName = srcEcc->curveName; +#ifdef WE_HAVE_ECDSA + dstEcc->md = srcEcc->md; +#endif +#ifdef WE_HAVE_ECKEYGEN + if (srcEcc->group != NULL) { + dstEcc->group = EC_GROUP_dup(srcEcc->group); + if (dstEcc->group == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "EC_GROUP_dup", + dstEcc->group); + ret = 0; + } + } +#endif +#ifdef WE_HAVE_ECDH + dstEcc->coFactor = srcEcc->coFactor; + dstEcc->kdfType = srcEcc->kdfType; + dstEcc->kdfMd = srcEcc->kdfMd; + dstEcc->kdfOutLen = srcEcc->kdfOutLen; + if (ret == 1 && srcEcc->peerKey != NULL) { + if (srcEcc->peerKeyLen <= 0) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Invalid peer key length"); + ret = 0; + } + else { + dstEcc->peerKey = OPENSSL_malloc(srcEcc->peerKeyLen); + if (dstEcc->peerKey == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "OPENSSL_malloc", + dstEcc->peerKey); + ret = 0; + } + else { + XMEMCPY(dstEcc->peerKey, srcEcc->peerKey, + srcEcc->peerKeyLen); + dstEcc->peerKeyLen = srcEcc->peerKeyLen; + } + } + } + if (ret == 1 && srcEcc->kdfUkm != NULL) { + if (srcEcc->kdfUkmLen <= 0) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Invalid KDF UKM length"); + ret = 0; + } + else { + dstEcc->kdfUkm = OPENSSL_malloc(srcEcc->kdfUkmLen); + if (dstEcc->kdfUkm == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "OPENSSL_malloc", + dstEcc->kdfUkm); + ret = 0; + } + else { + XMEMCPY(dstEcc->kdfUkm, srcEcc->kdfUkm, + srcEcc->kdfUkmLen); + dstEcc->kdfUkmLen = srcEcc->kdfUkmLen; + } + } + } +#endif + } + + if (ret == 0 && dstEcc != NULL) { + we_ec_cleanup(dst); + } - WOLFENGINE_LEAVE(WE_LOG_PK, "we_ec_copy", 1); + WOLFENGINE_LEAVE(WE_LOG_PK, "we_ec_copy", ret); - return 1; + return ret; } /** @@ -638,6 +726,10 @@ static void we_ec_cleanup(EVP_PKEY_CTX *ctx) OPENSSL_free(ecc->peerKey); ecc->peerKey = NULL; } + if (ecc->kdfUkm != NULL) { + OPENSSL_free(ecc->kdfUkm); + ecc->kdfUkm = NULL; + } #endif #ifndef WE_ECC_USE_GLOBAL_RNG wc_FreeRng(&ecc->rng); @@ -833,6 +925,10 @@ static int we_pkey_ecdsa_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, ecc->pubKeySet = 1; } } + if (ret != 1) { + /* Setup failures are errors, not invalid signatures. */ + ret = -1; + } /* wolfSSL FIPS is not checking SEQUENCE length. */ if ((ret == 1) && ((sig == NULL) || (sigLen < 2))) { WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Signature too short"); @@ -986,10 +1082,12 @@ static int we_ec_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) if (len < 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_ecc_get_curve_size_from_id", len); + ret = 0; } /* New OpenSSL EC_KEY object to hold new key. */ - ret = (ecKey = EC_KEY_new()) != NULL; + if (ret == 1) + ret = (ecKey = EC_KEY_new()) != NULL; } if (ret == 1) { @@ -1082,6 +1180,11 @@ static int we_ecdh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keyLen) /* Get the internal EC key object. */ ret = (ecc = (we_Ecc *)EVP_PKEY_CTX_get_data(ctx)) != NULL; + if ((ret == 1) && (!ecc->privKeySet)) { + /* Get the OpenSSL EC_KEY object and set curve id. */ + ret = we_ec_get_ec_key(ctx, &ecKey, ecc); + } + if (ret == 1) { ret = we_ecc_check_curve_usage(ecc->curveId); if (ret != 1) { @@ -1090,18 +1193,28 @@ static int we_ecdh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keyLen) } if ((ret == 1) && (!ecc->privKeySet)) { - /* Get the OpenSSL EC_KEY object and set curve id. */ - ret = we_ec_get_ec_key(ctx, &ecKey, ecc); - if (ret == 1) { - /* Set private key in wolfSSL object. */ - ret = we_ec_set_private(&ecc->key, ecc->curveId, ecKey); - } + /* Set private key in wolfSSL object. */ + ret = we_ec_set_private(&ecc->key, ecc->curveId, ecKey); if (ret == 1) { /* Only do this once as private will not change. */ ecc->privKeySet = 1; } } + if ((ret == 1) && (ecc->kdfType == EVP_PKEY_ECDH_KDF_X9_63) && + ((ecc->kdfMd == NULL) || (ecc->kdfOutLen <= 0) || + (we_nid_to_wc_hash_type(EVP_MD_type(ecc->kdfMd)) == + WC_HASH_TYPE_NONE))) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Invalid ECDH KDF configuration"); + ret = 0; + } + if ((ret == 1) && (key != NULL) && + (ecc->kdfType == EVP_PKEY_ECDH_KDF_X9_63) && + (*keyLen < (size_t)ecc->kdfOutLen)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "ECDH KDF output buffer too small"); + ret = 0; + } + if ((ret == 1) && (key == NULL)) { if (ecc->kdfType == EVP_PKEY_ECDH_KDF_NONE) { /* Return secret size in bytes. */ @@ -1109,6 +1222,7 @@ static int we_ecdh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keyLen) if (rc < 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_ecc_get_curve_size_from_id", rc); + ret = 0; } else { *keyLen = (size_t)rc; @@ -1120,6 +1234,19 @@ static int we_ecdh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keyLen) *keyLen = ecc->kdfOutLen; } } + if ((ret == 1) && (key != NULL) && + ((ecc->peerKey == NULL) || (ecc->peerKeyLen <= 0))) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Peer key not set"); + ret = 0; + } + if ((ret == 1) && (key != NULL)) { + rc = wc_ecc_get_curve_size_from_id(ecc->curveId); + if ((rc <= 0) || (ecc->peerKeyLen != (2 * rc + 1)) || + (ecc->peerKey[0] != POINT_CONVERSION_UNCOMPRESSED)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Invalid peer key encoding"); + ret = 0; + } + } if ((ret == 1) && (key != NULL)) { /* Create a new wolfSSL ECC key and set peer's public key. */ rc = wc_ecc_init(&peer); @@ -1168,6 +1295,7 @@ static int we_ecdh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keyLen) /* Maximum output size supported for curves supported. */ unsigned char out[72]; + word32 outputLen = (word32)ecc->kdfOutLen; /* Get buffer length. */ len = (word32)sizeof(out); @@ -1186,18 +1314,22 @@ static int we_ecdh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keyLen) we_nid_to_wc_hash_type(EVP_MD_type(ecc->kdfMd)); /* KDF secret to key. */ rc = wc_X963_KDF(hash, out, len, ecc->kdfUkm, - ecc->kdfUkmLen, key, (word32)*keyLen); + ecc->kdfUkmLen, key, outputLen); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_X963_KDF", rc); ret = 0; } + else { + len = outputLen; + } } + OPENSSL_cleanse(out, sizeof(out)); } - } #if defined(WE_ECC_USE_GLOBAL_RNG) && defined(ECC_TIMING_RESISTANT) \ && !defined(WE_SINGLE_THREADED) - wc_UnLockMutex(we_rng_mutex); + wc_UnLockMutex(we_rng_mutex); #endif + } } if (ret == 1) { /* Return length of secret. */ @@ -1227,7 +1359,8 @@ static int we_ecdh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keyLen) * @param type [in] Type of operation to perform. * @param num [in] Integer parameter. * @param ptr [in] Pointer parameter. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) { @@ -1235,7 +1368,11 @@ static int we_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) we_Ecc *ecc; #ifdef WE_HAVE_ECDH EVP_PKEY *peerKey; + EVP_PKEY *localKey; EC_KEY *ecPeerKey = NULL; + const EC_KEY *ecLocalKey; + const EC_GROUP *localGroup; + const EC_GROUP *peerGroup; #endif char errBuff[WOLFENGINE_MAX_LOG_WIDTH]; @@ -1318,14 +1455,32 @@ static int we_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) peerKey = (EVP_PKEY *)ptr; /* Get the OpenSSL EC_KEY object. */ #if OPENSSL_VERSION_NUMBER >= 0x30000000L - ret = (ecPeerKey = (EC_KEY*)EVP_PKEY_get0_EC_KEY(peerKey)) != - NULL; + if (peerKey != NULL) + ecPeerKey = (EC_KEY*)EVP_PKEY_get0_EC_KEY(peerKey); #else - ret = (ecPeerKey = EVP_PKEY_get0_EC_KEY(peerKey)) != NULL; + if (peerKey != NULL) + ecPeerKey = EVP_PKEY_get0_EC_KEY(peerKey); #endif + ret = ecPeerKey != NULL; + if (ret == 1) { + localKey = EVP_PKEY_CTX_get0_pkey(ctx); + ecLocalKey = localKey != NULL ? + EVP_PKEY_get0_EC_KEY(localKey) : NULL; + localGroup = ecLocalKey != NULL ? + EC_KEY_get0_group(ecLocalKey) : NULL; + peerGroup = EC_KEY_get0_group(ecPeerKey); + if ((localGroup == NULL) || (peerGroup == NULL) || + (EC_GROUP_cmp(localGroup, peerGroup, NULL) != 0)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, + "Peer key curve does not match"); + ret = 0; + } + } if (ret == 1) { /* Replace the peerKey data. */ OPENSSL_free(ecc->peerKey); + ecc->peerKey = NULL; + ecc->peerKeyLen = 0; /* Get the EC key public key as an uncompressed point. */ ecc->peerKeyLen = (int)EC_KEY_key2buf(ecPeerKey, POINT_CONVERSION_UNCOMPRESSED, &ecc->peerKey, NULL); @@ -1362,17 +1517,37 @@ static int we_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) break; case EVP_PKEY_CTRL_EC_KDF_MD: - ecc->kdfMd = (const EVP_MD *)ptr; + if ((ptr != NULL) && + (we_nid_to_wc_hash_type( + EVP_MD_type((const EVP_MD *)ptr)) == + WC_HASH_TYPE_NONE)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Invalid KDF digest"); + ret = 0; + } + else { + ecc->kdfMd = (const EVP_MD *)ptr; + } break; case EVP_PKEY_CTRL_GET_EC_KDF_MD: *(const EVP_MD **)ptr = ecc->kdfMd; break; case EVP_PKEY_CTRL_EC_KDF_OUTLEN: - ecc->kdfOutLen = num; + if (num <= 0) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Invalid KDF output length"); + ret = 0; + } + else { + ecc->kdfOutLen = num; + } break; case EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN: - ret = ecc->kdfOutLen; + if (ptr == NULL) { + ret = 0; + } + else { + *(int *)ptr = ecc->kdfOutLen; + } break; case EVP_PKEY_CTRL_EC_KDF_UKM: @@ -1396,7 +1571,7 @@ static int we_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; break; } } @@ -1413,12 +1588,16 @@ static int we_ec_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) * * @param ctx [in] Public key context of operation. * @param type [in] String representation of value. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_ec_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { int ret = 1; +#ifdef WE_HAVE_ECKEYGEN + int curveNid; +#endif char errBuff[WOLFENGINE_MAX_LOG_WIDTH]; we_Ecc *ecc; @@ -1428,25 +1607,62 @@ static int we_ec_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, ret = 0; } + if ((ret == 1) && ((type == NULL) || (value == NULL))) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Missing EC control value"); + ret = 0; + } + if (ret == 1) { - if (XSTRNCMP(type, "ecdh_cofactor_mode", 19) == 0) { + if (XSTRCMP(type, "ecdh_cofactor_mode") == 0) { WOLFENGINE_MSG(WE_LOG_PK, "received type: ecdh_cofactor_mode"); ecc->coFactor = (XATOI(value) == 1); } - else if (XSTRNCMP(type, "ecdh_kdf_md", 19) == 0) { - ecc->kdfMd = EVP_get_digestbyname(value); + else if (XSTRCMP(type, "ecdh_kdf_md") == 0) { + const EVP_MD *md = EVP_get_digestbyname(value); + WOLFENGINE_MSG(WE_LOG_PK, "received type: ecdh_kdf_md"); - if (ecc->kdfMd == NULL) { + if ((md == NULL) || + (we_ec_ctrl(ctx, EVP_PKEY_CTRL_EC_KDF_MD, 0, (void *)md) != + 1)) { XSNPRINTF(errBuff, sizeof(errBuff), "Invalid digest %s", value); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); ret = 0; } } + #ifdef WE_HAVE_ECKEYGEN + else if (XSTRCMP(type, "ec_paramgen_curve") == 0) { + curveNid = OBJ_txt2nid(value); + if (curveNid == NID_undef) + curveNid = EC_curve_nist2nid(value); + if (curveNid == NID_undef) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Unknown EC curve"); + ret = 0; + } + else { + ret = we_ec_ctrl(ctx, EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, + curveNid, NULL); + } + } + else if (XSTRCMP(type, "ec_param_enc") == 0) { + if (XSTRCMP(value, "named_curve") != 0) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, + "Unsupported EC parameter encoding"); + ret = -2; + } + else if (ecc->group == NULL) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "EC group not set"); + ret = 0; + } + else { + EC_GROUP_set_asn1_flag(ecc->group, OPENSSL_EC_NAMED_CURVE); + } + } + #endif else { XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl string %s", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; } } @@ -1781,6 +1997,9 @@ static int we_ec_key_keygen(EC_KEY *key) WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_ecc_init", rc); ret = 0; } + else { + pEcc = &ecc; + } } } #ifndef WE_ECC_USE_GLOBAL_RNG @@ -1795,8 +2014,6 @@ static int we_ec_key_keygen(EC_KEY *key) } #endif if (ret == 1) { - pEcc = &ecc; - /* Generate key. */ #if defined(WE_ECC_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) rc = wc_LockMutex(we_rng_mutex); @@ -1911,6 +2128,9 @@ static int we_ec_key_compute_key(unsigned char **psec, size_t *pseclen, WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_ecc_init", rc); ret = 0; } + else { + pKey = &key; + } } #if !defined(HAVE_FIPS) || \ (defined(HAVE_FIPS_VERSION) && HAVE_FIPS_VERSION != 2) @@ -1936,8 +2156,6 @@ static int we_ec_key_compute_key(unsigned char **psec, size_t *pseclen, } #endif /* !HAVE_FIPS || (HAVE_FIPS_VERSION && HAVE_FIPS_VERSION != 2) */ if (ret == 1) { - pKey = &key; - /* Set private key into wolfSSL key object. */ ret = we_ec_set_private(pKey, curveId, ecdh); } @@ -1981,11 +2199,11 @@ static int we_ec_key_compute_key(unsigned char **psec, size_t *pseclen, WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_ecc_shared_secret", rc); ret = 0; } - } #if defined(WE_ECC_USE_GLOBAL_RNG) && defined(ECC_TIMING_RESISTANT) \ && !defined(WE_SINGLE_THREADED) - wc_UnLockMutex(we_rng_mutex); + wc_UnLockMutex(we_rng_mutex); #endif + } } if (ret == 1) { WOLFENGINE_MSG(WE_LOG_PK, "Calculated ECDH shared secret"); @@ -2187,11 +2405,15 @@ static ECDSA_SIG* we_ecdsa_do_sign_ex(const unsigned char *d, int dlen, sBN = BN_bin2bn(s_bin, s_size, sBN); if (rBN == NULL || sBN == NULL) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "BN_bin2bn", NULL); + BN_clear_free(rBN); + BN_clear_free(sBN); err = 1; } else { rc = ECDSA_SIG_set0(sig, rBN, sBN); if (rc != 1) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "ECDSA_SIG_set0", rc); + BN_clear_free(rBN); + BN_clear_free(sBN); err = 1; } } @@ -2433,11 +2655,11 @@ static int we_ec_key_sign(int type, const unsigned char *dgst, int dLen, if (ret == 1 && sig == NULL) { /* Return signature size in bytes. */ *sigLen = wc_ecc_sig_size(&key); - WOLFENGINE_MSG(WE_LOG_PK, "sig is NULL, returning size: %zu", *sigLen); + WOLFENGINE_MSG(WE_LOG_PK, "sig is NULL, returning size: %u", *sigLen); } if (ret == 1 && sig != NULL) { /* Sign hash with wolfSSL. */ - outLen = *sigLen; + outLen = (word32)wc_ecc_sig_size(&key); #if defined(WE_ECC_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) rc = wc_LockMutex(we_rng_mutex); if (rc != 0) { @@ -2496,6 +2718,14 @@ static int we_ec_key_verify(int type, const unsigned char *dgst, int dLen, ecc_key *pKey = NULL; const EC_GROUP *group; int curveId; + ECDSA_SIG *decodedSig = NULL; + const unsigned char *sigIn; + unsigned char encodedSig[ECC_MAX_SIG_SIZE]; + unsigned char *sigOut; + int encodedLen; + const BIGNUM *r; + const BIGNUM *s; + const BIGNUM *order; WOLFENGINE_ENTER(WE_LOG_PK, "we_ec_key_verify"); WOLFENGINE_MSG_VERBOSE(WE_LOG_PK, "ARGS [type = %d, dgst = %p, dLen = %d, " @@ -2520,12 +2750,45 @@ static int we_ec_key_verify(int type, const unsigned char *dgst, int dLen, /* Set public key into wolfSSL key object. */ ret = we_ec_set_public(&key, curveId, ecKey); } + if (ret != 1) { + /* Setup failures are errors, not invalid signatures. */ + ret = -1; + } + if (ret == 1) { + ret = -1; + if (sig != NULL && sigLen > 0 && sigLen <= (int)sizeof(encodedSig)) { + sigIn = sig; + decodedSig = d2i_ECDSA_SIG(NULL, &sigIn, sigLen); + if (decodedSig != NULL && sigIn == sig + sigLen && + i2d_ECDSA_SIG(decodedSig, NULL) == sigLen) { + sigOut = encodedSig; + encodedLen = i2d_ECDSA_SIG(decodedSig, &sigOut); + if (encodedLen == sigLen && + XMEMCMP(sig, encodedSig, sigLen) == 0) { + /* Encoding errors must not depend on backend results. */ + ECDSA_SIG_get0(decodedSig, &r, &s); + if (!BN_is_negative(r) && !BN_is_negative(s)) { + ret = 1; + } + } + } + } + } if (ret == 1) { /* Verify hash with wolfSSL. */ rc = wc_ecc_verify_hash(sig, sigLen, dgst, dLen, &res, &key); if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_ecc_verify_hash", rc); ret = -1; + if (rc == MP_ZERO_E || rc == MP_VAL) { + order = EC_GROUP_get0_order(group); + if (order != NULL && (BN_is_zero(r) || BN_cmp(r, order) >= 0 || + BN_is_zero(s) || BN_cmp(s, order) >= 0)) { + ret = 0; + } + } + if (ret == -1) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_ecc_verify_hash", rc); + } } } if (ret == 1) { @@ -2540,6 +2803,7 @@ static int we_ec_key_verify(int type, const unsigned char *dgst, int dLen, } } + ECDSA_SIG_free(decodedSig); wc_ecc_free(pKey); WOLFENGINE_LEAVE(WE_LOG_PK, "we_ec_key_verify", ret); @@ -2604,7 +2868,7 @@ struct ecdh_method { * Compute shared secret with a private-key and a peer's public-key. * If key-derivation function is given, calls it with shared secret. * - * @param out [in] buffer to hold computed key. + * @param out [out] buffer to hold computed key. * @param outlen [in] size of out buffer. * @param pub_key [in] peer's public key. * @param ecdh [in] private key. @@ -2647,7 +2911,7 @@ static int we_ecdh_compute_key(void* out, size_t outlen, ret = (int)outlen; } else { - WOLFENGINE_ERROR_FUNC(WE_LOG_KE, "KDF", ret); + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_KE, "KDF", NULL); ret = -1; } } @@ -2658,7 +2922,7 @@ static int we_ecdh_compute_key(void* out, size_t outlen, } if (secret != NULL) { - OPENSSL_free(secret); + OPENSSL_clear_free(secret, secretLen); } WOLFENGINE_LEAVE(WE_LOG_KE, "we_ecdh_compute_key", ret); diff --git a/src/we_hkdf.c b/src/we_hkdf.c index 3c7fd5e0..8f0fd7d7 100644 --- a/src/we_hkdf.c +++ b/src/we_hkdf.c @@ -46,6 +46,8 @@ typedef struct we_Hkdf { unsigned char info[WE_MAX_INFO_SIZE]; /** Size of info in bytes. */ size_t infoSz; + /** Whether a key has been configured. */ + int keySet; } we_Hkdf; /** @@ -112,6 +114,32 @@ static void we_hkdf_cleanup(EVP_PKEY_CTX *ctx) WOLFENGINE_LEAVE(WE_LOG_PK, "we_hkdf_cleanup", 1); } +/** + * Reset the HKDF parameters for a new derive operation. + * + * @param ctx [in] PKEY context. + * @returns 1 on success. + */ +static int we_hkdf_derive_init(EVP_PKEY_CTX *ctx) +{ + we_Hkdf *hkdf; + + WOLFENGINE_ENTER(WE_LOG_PK, "we_hkdf_derive_init"); + + hkdf = (we_Hkdf *)EVP_PKEY_CTX_get_data(ctx); + if (hkdf->key != NULL) { + OPENSSL_clear_free(hkdf->key, hkdf->keySz); + } + if (hkdf->salt != NULL) { + OPENSSL_clear_free(hkdf->salt, hkdf->saltSz); + } + OPENSSL_cleanse(hkdf, sizeof(*hkdf)); + + WOLFENGINE_LEAVE(WE_LOG_PK, "we_hkdf_derive_init", 1); + + return 1; +} + /** * Derive the key from the key and info. * @@ -143,10 +171,23 @@ static int we_hkdf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, ret = 0; } /* Check a key was set - no point otherwise! */ - if ((ret == 1) && (hkdf->keySz == 0)) { + if ((ret == 1) && (hkdf->keySet == 0)) { WOLFENGINE_ERROR_MSG(WE_LOG_PK, "No key from app."); ret = 0; } + if ((ret == 1) && + (hkdf->mode != EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY)) { + rc = wc_HashGetDigestSize(hkdf->mdType); + if (rc <= 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_HashGetDigestSize", rc); + ret = 0; + } + else if ((*keySz > (size_t)(word32)-1) || + (*keySz > ((size_t)rc * 255U))) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "HKDF output is too large."); + ret = 0; + } + } if ((ret == 1) && (hkdf->mode == EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND)) { PRIVATE_KEY_UNLOCK(); rc = wc_HKDF(hkdf->mdType, hkdf->key, (word32)hkdf->keySz, hkdf->salt, @@ -159,16 +200,30 @@ static int we_hkdf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, } } else if ((ret == 1) && (hkdf->mode == EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY)) { - PRIVATE_KEY_UNLOCK(); - rc = wc_HKDF_Extract(hkdf->mdType, hkdf->salt, (word32)hkdf->saltSz, - hkdf->key, (word32)hkdf->keySz, key); - PRIVATE_KEY_LOCK(); - if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_HKDF_Extract", rc); + rc = wc_HashGetDigestSize(hkdf->mdType); + if (rc <= 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_HashGetDigestSize", rc); ret = 0; } - if (ret == 1) { - *keySz = (size_t)wc_HashGetDigestSize(hkdf->mdType); + else if (key == NULL) { + *keySz = (size_t)rc; + } + else if (*keySz < (size_t)rc) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "HKDF output buffer is too small."); + ret = 0; + } + else { + PRIVATE_KEY_UNLOCK(); + rc = wc_HKDF_Extract(hkdf->mdType, hkdf->salt, + (word32)hkdf->saltSz, hkdf->key, (word32)hkdf->keySz, key); + PRIVATE_KEY_LOCK(); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_HKDF_Extract", rc); + ret = 0; + } + if (ret == 1) { + *keySz = (size_t)wc_HashGetDigestSize(hkdf->mdType); + } } } else if ((ret == 1) && (hkdf->mode == EVP_PKEY_HKDEF_MODE_EXPAND_ONLY)) { @@ -201,12 +256,14 @@ static int we_hkdf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, * @param type [in] Type of operation to perform. * @param num [in] Integer argument. * @param ptr [in] Pointer argument. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) { we_Hkdf *hkdf; int ret = 1; + int mdType; char errBuff[WOLFENGINE_MAX_LOG_WIDTH]; WOLFENGINE_ENTER(WE_LOG_PK, "we_hkdf_ctrl"); @@ -240,37 +297,53 @@ static int we_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) case EVP_PKEY_CTRL_HKDF_MD: WOLFENGINE_MSG(WE_LOG_PK, "type: EVP_PKEY_CTRL_HKDF_MD"); /* ptr: EVP md object. */ - /* Convert EVP_MD to */ - hkdf->mdType = we_nid_to_wc_hash_type(EVP_MD_type(ptr)); + if (ptr == NULL) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Digest must not be NULL"); + ret = 0; + } + else { + mdType = we_nid_to_wc_hash_type(EVP_MD_type(ptr)); + if (mdType == WC_HASH_TYPE_NONE) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Digest not supported"); + ret = 0; + } + else { + hkdf->mdType = mdType; + } + } break; case EVP_PKEY_CTRL_HKDF_KEY: WOLFENGINE_MSG(WE_LOG_PK, "type: EVP_PKEY_CTRL_HKDF_KEY"); /* num: Number of bytes in buffer. * ptr: Buffer holding key data. */ - /* Number of bytes must be positive. */ + /* Number of bytes must not be negative. */ if (num < 0) { - WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Key size must be positive"); + WOLFENGINE_ERROR_MSG(WE_LOG_PK, + "Key size must not be negative"); ret = 0; } - if ((ret == 1) && (hkdf->key != NULL)) { + if (hkdf->key != NULL) { /* Setting key - dispose of old key. */ OPENSSL_clear_free(hkdf->key, hkdf->keySz); } + hkdf->key = NULL; + hkdf->keySz = 0; + hkdf->keySet = 0; if (ret == 1) { - /* Clear info as this is a new operation. */ - OPENSSL_cleanse(hkdf->info, hkdf->infoSz); - hkdf->infoSz = 0; - /* Copy the key. */ - hkdf->key = OPENSSL_memdup(ptr, num); - if (hkdf->key == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "OPENSSL_memdup(key)", - hkdf->key); - ret = 0; + /* Copy the key when it is not empty. */ + if (num != 0) { + hkdf->key = OPENSSL_memdup(ptr, num); + if (hkdf->key == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, + "OPENSSL_memdup(key)", hkdf->key); + ret = 0; + } } - else { + if (ret == 1) { /* Store size of key. */ - hkdf->keySz = num; + hkdf->keySz = num; + hkdf->keySet = 1; } } break; @@ -284,15 +357,13 @@ static int we_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Seed size must be positive"); ret = 0; } - if ((ret == 1) && (hkdf->salt != NULL)) { + if (hkdf->salt != NULL) { /* Setting salt - dispose of old salt. */ OPENSSL_clear_free(hkdf->salt, hkdf->saltSz); - hkdf->salt = NULL; } + hkdf->salt = NULL; + hkdf->saltSz = 0; if (ret == 1) { - /* Clear info as this is a new operation. */ - OPENSSL_cleanse(hkdf->info, hkdf->infoSz); - hkdf->infoSz = 0; /* Copy the salt if there not 0 length. */ if (num != 0) { hkdf->salt = OPENSSL_memdup(ptr, num); @@ -334,7 +405,7 @@ static int we_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; break; } @@ -359,12 +430,14 @@ static int we_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) * @param ctx [in] PKEY context. * @param type [in] Type of operation to perform. * @param value [in] Pointer argument. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_hkdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { int ret = 1; + int mdType; we_Hkdf *hkdf; char errBuff[WOLFENGINE_MAX_LOG_WIDTH]; @@ -407,7 +480,14 @@ static int we_hkdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, ret = 0; } else { - hkdf->mdType = we_nid_to_wc_hash_type(EVP_MD_type(md)); + mdType = we_nid_to_wc_hash_type(EVP_MD_type(md)); + if (mdType == WC_HASH_TYPE_NONE) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Digest not supported"); + ret = 0; + } + else { + hkdf->mdType = mdType; + } } } else if (XSTRNCMP(type, "key", 4) == 0) { @@ -432,7 +512,7 @@ static int we_hkdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, /* Unsupported string. */ XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %s", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; } WOLFENGINE_LEAVE(WE_LOG_PK, "we_hkdf_ctrl_str", ret); @@ -465,7 +545,8 @@ int we_init_hkdf_meth(void) EVP_PKEY_meth_set_init(we_hkdf_method, we_hkdf_init); EVP_PKEY_meth_set_cleanup(we_hkdf_method, we_hkdf_cleanup); EVP_PKEY_meth_set_ctrl(we_hkdf_method, we_hkdf_ctrl, we_hkdf_ctrl_str); - EVP_PKEY_meth_set_derive(we_hkdf_method, NULL, we_hkdf_derive); + EVP_PKEY_meth_set_derive(we_hkdf_method, we_hkdf_derive_init, + we_hkdf_derive); } if (ret == 0 && we_hkdf_method != NULL) { diff --git a/src/we_internal.c b/src/we_internal.c index d7527d9b..72209287 100644 --- a/src/we_internal.c +++ b/src/we_internal.c @@ -63,6 +63,89 @@ void *we_memdup(const void *data, size_t siz) /** Engine bound to. */ static ENGINE *bound = NULL; +static int we_binding = 0; +#ifdef WE_HAVE_PBE +static int we_pbe_ready = 0; +#endif + +#ifndef WE_SINGLE_THREADED +#if defined(_MSC_VER) +#include +static volatile LONG we_bind_lock = 0; +#elif defined(__GNUC__) || defined(__clang__) +static int we_bind_lock = 0; +#else +#error Threaded engine binding requires compiler atomic operations +#endif +#endif /* !WE_SINGLE_THREADED */ + +static void we_lock_bind(void) +{ +#ifndef WE_SINGLE_THREADED +#if defined(_MSC_VER) + while (InterlockedCompareExchange(&we_bind_lock, 1, 0) != 0) { + YieldProcessor(); + } +#else + while (__atomic_exchange_n(&we_bind_lock, 1, __ATOMIC_ACQUIRE) != 0) { + } +#endif +#endif /* !WE_SINGLE_THREADED */ +} + +static void we_unlock_bind(void) +{ +#ifndef WE_SINGLE_THREADED +#if defined(_MSC_VER) + InterlockedExchange(&we_bind_lock, 0); +#else + __atomic_store_n(&we_bind_lock, 0, __ATOMIC_RELEASE); +#endif +#endif +} + +int we_engine_bind_available(void) +{ + int available; + + we_lock_bind(); + available = (we_binding == 0) && (bound == NULL); + we_unlock_bind(); + return available; +} + +/** + * Acquire the bound engine during an active engine PKEY operation. + * + * The caller must already hold a functional engine reference. + * + * @returns Referenced engine to release with ENGINE_finish(), or NULL. + */ +ENGINE *wolfengine_get_bound_engine(void) +{ + ENGINE *engine; + + we_lock_bind(); + engine = (we_binding == 0) ? bound : NULL; + we_unlock_bind(); + + if ((engine != NULL) && (ENGINE_init(engine) != 1)) + engine = NULL; + + return engine; +} + +#ifdef WE_HAVE_PBE +int we_pbe_keygen_ready(void) +{ + int ready; + + we_lock_bind(); + ready = we_pbe_ready; + we_unlock_bind(); + return ready; +} +#endif #if defined(WE_HAVE_EVP_PKEY) || defined(WE_USE_HASH) /** List of public key types supported as ids. */ @@ -161,6 +244,30 @@ static int we_globalRngInited = 0; wolfSSL_Mutex we_global_rng_mutex; /* Pointer to mutex for protecting use of global random number generator.*/ wolfSSL_Mutex* we_rng_mutex = &we_global_rng_mutex; +/* Global RNG mutex has been initialized. */ +static int we_globalRngMutexInited = 0; +#endif + +/** + * Get whether the global random number generator is initialized. + * + * @returns 1 when initialized and 0 otherwise. + */ +int we_rng_is_initialized(void) +{ + return we_globalRngInited; +} + +#ifndef WE_SINGLE_THREADED +/** + * Get whether the global random number generator mutex is initialized. + * + * @returns 1 when initialized and 0 otherwise. + */ +int we_rng_mutex_is_initialized(void) +{ + return we_globalRngMutexInited; +} #endif /** @@ -186,9 +293,12 @@ static int we_init_random(void) rc = wc_InitMutex(&we_global_rng_mutex); if (rc != 0) { wc_FreeRng(&we_globalRng); - WOLFENGINE_ERROR_FUNC(WE_LOG_ENGINE, "wc_InitRng", rc); + WOLFENGINE_ERROR_FUNC(WE_LOG_ENGINE, "wc_InitMutex", rc); ret = 0; } + else { + we_globalRngMutexInited = 1; + } } #endif if (ret == 1) { @@ -209,11 +319,15 @@ static void we_final_random(void) WOLFENGINE_ENTER(WE_LOG_ENGINE, "we_final_random"); if (we_globalRngInited) { - #ifndef WE_SINGLE_THREADED - wc_FreeMutex(&we_global_rng_mutex); + #if defined(WE_HAVE_RANDOM) && !defined(WE_STATIC_WOLFSSL) + we_rand_clear_seed(); #endif wc_FreeRng(&we_globalRng); we_globalRngInited = 0; + #ifndef WE_SINGLE_THREADED + we_globalRngMutexInited = 0; + wc_FreeMutex(&we_global_rng_mutex); + #endif } WOLFENGINE_LEAVE(WE_LOG_ENGINE, "we_final_random", 1); @@ -250,7 +364,7 @@ static const int we_digest_nids[] = { #ifdef WE_HAVE_SHA3_512 NID_sha3_512, #endif -#if defined(WE_HAVE_ECC) && defined(WE_HAVE_SHA1) +#if defined(WE_HAVE_ECDSA) && defined(WE_HAVE_SHA1) NID_ecdsa_with_SHA1, #endif }; @@ -587,6 +701,11 @@ static int we_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, case NID_aes_256_ccm: *cipher = we_aes256_ccm_ciph; break; +#endif +#ifdef WE_HAVE_CMAC + case NID_cmac: + *cipher = we_cmac_ciph; + break; #endif default: XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported cipher NID: %d", @@ -1009,12 +1128,6 @@ static int wolfengine_init(ENGINE *e) } #endif #endif -#ifdef WE_HAVE_PBE - if (ret == 1) { - ret = we_init_pbe_keygen(); - } -#endif - #endif WOLFENGINE_LEAVE(WE_LOG_ENGINE, "wolfengine_init", ret); @@ -1022,18 +1135,96 @@ static int wolfengine_init(ENGINE *e) return ret; } -/** - * Destroy all data allocated by wolfengine. - * - * @param e [in] Engine object. - * @returns 1 for success always. - */ -static int wolfengine_destroy(ENGINE *e) +/** Clear engine-owned PKEY method pointers after OpenSSL releases them. */ +static void wolfengine_pkey_methods_clear(void) { - WOLFENGINE_ENTER(WE_LOG_ENGINE, "wolfengine_destroy"); +#ifdef WE_HAVE_HMAC +#ifndef WE_HAVE_EVP_PKEY + EVP_PKEY_meth_free(we_hmac_pkey_method); +#endif + we_hmac_pkey_method = NULL; + we_hmac_pkey_asn1_method = NULL; +#endif +#ifdef WE_HAVE_CMAC +#ifndef WE_HAVE_EVP_PKEY + EVP_PKEY_meth_free(we_cmac_pkey_method); + EVP_PKEY_meth_free(we_cmac_we_pkey_method); +#endif + we_cmac_pkey_method = NULL; + we_cmac_we_pkey_method = NULL; + we_cmac_pkey_asn1_method = NULL; + we_cmac_we_pkey_asn1_method = NULL; +#endif +#if defined(WE_HAVE_TLS1_PRF) && defined(WE_HAVE_EVP_PKEY) + we_tls1_prf_method = NULL; +#endif +#if defined(WE_HAVE_HKDF) && defined(WE_HAVE_EVP_PKEY) + we_hkdf_method = NULL; +#endif +#if defined(WE_HAVE_DH) && defined(WE_HAVE_EVP_PKEY) + we_dh_pkey_method = NULL; +#endif +#if defined(WE_HAVE_RSA) && defined(WE_HAVE_EVP_PKEY) + we_rsa_pkey_method = NULL; +#endif +#if defined(WE_HAVE_ECC) && defined(WE_HAVE_EVP_PKEY) + we_ec_method = NULL; +#ifdef WE_HAVE_ECKEYGEN +#ifdef WE_HAVE_EC_P192 + we_ec_p192_method = NULL; +#endif +#ifdef WE_HAVE_EC_P224 + we_ec_p224_method = NULL; +#endif +#ifdef WE_HAVE_EC_P256 + we_ec_p256_method = NULL; +#endif +#ifdef WE_HAVE_EC_P384 + we_ec_p384_method = NULL; +#endif +#ifdef WE_HAVE_EC_P521 + we_ec_p521_method = NULL; +#endif +#endif /* WE_HAVE_ECKEYGEN */ +#endif /* WE_HAVE_ECC && WE_HAVE_EVP_PKEY */ +} +/** Release key methods before a failed bind can publish another owner. */ +static void wolfengine_pkey_methods_rollback(ENGINE *e) +{ +#ifdef WE_HAVE_EVP_PKEY + const int *nids; + EVP_PKEY_METHOD *method; + EVP_PKEY_ASN1_METHOD *asn1; + int count; + int i; + + /* OpenSSL must not release these methods when the failed engine is freed. */ + ENGINE_set_pkey_meths(e, NULL); + ENGINE_set_pkey_asn1_meths(e, NULL); + count = we_pkey_get_nids(&nids); + for (i = 0; i < count; i++) { + method = NULL; + if (we_pkey(e, &method, NULL, nids[i]) == 1) { + EVP_PKEY_meth_free(method); + } + } + count = we_pkey_asn1_get_nids(&nids); + for (i = 0; i < count; i++) { + asn1 = NULL; + if (we_pkey_asn1(e, &asn1, NULL, nids[i]) == 1) { + EVP_PKEY_asn1_free(asn1); + } + } +#else (void)e; +#endif + wolfengine_pkey_methods_clear(); +} +/** Free all global data allocated by wolfengine. */ +static void wolfengine_cleanup(void) +{ #ifdef WE_HAVE_DH DH_meth_free(we_dh_method); we_dh_method = NULL; @@ -1042,15 +1233,21 @@ static int wolfengine_destroy(ENGINE *e) RSA_meth_free(we_rsa_method); we_rsa_method = NULL; #endif /* WE_HAVE_RSA */ -#ifdef WE_HAVE_ECC +#ifdef WE_HAVE_ECDSA #if OPENSSL_VERSION_NUMBER < 0x10100000L - ECDSA_METHOD_free(we_ecdsa_method); - we_ecdsa_method = NULL; + if (we_ecdsa_method != NULL) { + ECDSA_METHOD_free(we_ecdsa_method); + we_ecdsa_method = NULL; + } #endif +#endif +#ifdef WE_HAVE_ECC /* For 1.1.1 and above we_ec_method is freed by OpenSSL_cleanup(). */ #ifdef WE_HAVE_EC_KEY - EC_KEY_METHOD_free(we_ec_key_method); - we_ec_key_method = NULL; + if (we_ec_key_method != NULL) { + EC_KEY_METHOD_free(we_ec_key_method); + we_ec_key_method = NULL; + } #endif #endif #if defined(WE_HAVE_ECDH) @@ -1108,6 +1305,10 @@ static int wolfengine_destroy(ENGINE *e) EVP_CIPHER_meth_free(we_aes256_ccm_ciph); we_aes256_ccm_ciph = NULL; #endif +#ifdef WE_HAVE_CMAC + EVP_CIPHER_meth_free(we_cmac_ciph); + we_cmac_ciph = NULL; +#endif #ifdef WE_HAVE_SHA1 EVP_MD_meth_free(we_sha1_md); we_sha1_md = NULL; @@ -1153,11 +1354,42 @@ static int wolfengine_destroy(ENGINE *e) we_final_random(); #endif - bound = NULL; +} + +/** + * Destroy all data allocated by wolfengine. + * + * @param e [in] Engine object. + * @returns 1 on success and 0 while binding is in progress. + */ +static int wolfengine_destroy(ENGINE *e) +{ + int ret = 1; - WOLFENGINE_LEAVE(WE_LOG_ENGINE, "wolfengine_destroy", 1); + we_lock_bind(); + if (bound != e) { + we_unlock_bind(); + return 1; + } + if (we_binding != 0) { + we_unlock_bind(); + return 0; + } + we_binding = 1; + we_unlock_bind(); - return 1; + WOLFENGINE_ENTER(WE_LOG_ENGINE, "wolfengine_destroy"); + wolfengine_cleanup(); + wolfengine_pkey_methods_clear(); + + WOLFENGINE_LEAVE(WE_LOG_ENGINE, "wolfengine_destroy", ret); + + we_lock_bind(); + bound = NULL; + we_binding = 0; + we_unlock_bind(); + + return ret; } #define WOLFENGINE_CMD_ENABLE_DEBUG ENGINE_CMD_BASE @@ -1386,23 +1618,6 @@ static const ECDSA_METHOD *we_ecdsa(void) #endif #endif /* WE_HAVE_ECDSA */ -#ifdef HAVE_FIPS -static void we_fips_cb(int ok, int err, const char* hash) -{ - printf("*******************************************\n"); - printf("we_fips_cb: ok = %d, err = %d\n", ok, err); - printf("error message = %s\n", wc_GetErrorString(err)); - printf("hash = %s\n", hash); - - if (err == IN_CORE_FIPS_E) { - printf("FIPS module integrity check failure. Copy above hash value " - "into verifyCore[] in wolfSSL's (NOT wolfEngine) fips_test.c " - "and rebuild wolfSSL.\n"); - } - printf("*******************************************\n"); -} -#endif - /** * Bind the wolfengine into an engine object. * @@ -1413,27 +1628,28 @@ static void we_fips_cb(int ok, int err, const char* hash) int wolfengine_bind(ENGINE *e, const char *id) { int ret = 1; + int initialized = 0; - WOLFENGINE_ENTER(WE_LOG_ENGINE, "wolfengine_bind"); - -#ifdef HAVE_FIPS - wolfCrypt_SetCb_fips(we_fips_cb); -#endif - - if ((id != NULL) && - (XSTRNCMP(id, wolfengine_id, XSTRLEN(wolfengine_id)) != 0)) { - ret = 0; + if ((e == NULL) || + ((id != NULL) && (XSTRCMP(id, wolfengine_id) != 0))) { + return 0; } - - if ((ret == 1) && (bound != NULL)) { - /* Don't add methods a second time. */ - ret = 0; + we_lock_bind(); + if ((we_binding != 0) || (bound != NULL)) { + we_unlock_bind(); + return 0; } + /* Keep user callbacks outside the state lock. */ + we_binding = 1; + we_unlock_bind(); + + WOLFENGINE_ENTER(WE_LOG_ENGINE, "wolfengine_bind"); if (ret == 1) { ret = ENGINE_set_id(e, wolfengine_id); } if (ret == 1) { + initialized = 1; ret = wolfengine_init(e); } if (ret == 1 && ENGINE_set_name(e, wolfengine_name) == 0) { @@ -1487,23 +1703,46 @@ int wolfengine_bind(ENGINE *e, const char *id) } #endif /* WE_HAVE_ECC && WE_HAVE_ECDH */ #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */ - if (ret == 1 && ENGINE_set_destroy_function(e, wolfengine_destroy) == 0) { - ret = 0; - } if (ret == 1 && ENGINE_set_cmd_defns(e, wolfengine_cmd_defns) == 0) { ret = 0; } if (ret == 1 && ENGINE_set_ctrl_function(e, wolfengine_ctrl) == 0) { ret = 0; } + if (ret == 1 && ENGINE_set_destroy_function(e, wolfengine_destroy) == 0) { + ret = 0; + } +#ifdef WE_HAVE_CMAC if (ret == 1) { - /* Successfully bound the methods to the engine. */ - bound = e; + ret = we_init_cmac_cipher_meth(); + } +#endif +#ifdef WE_HAVE_PBE + /* Publish only after all fallible engine setup has succeeded. */ + if (ret == 1) { + ret = we_init_pbe_keygen(); + } +#endif + + if ((ret == 0) && (initialized == 1)) { + wolfengine_pkey_methods_rollback(e); + wolfengine_cleanup(); } WOLFENGINE_LEAVE(WE_LOG_ENGINE, "wolfengine_bind", ret); + we_lock_bind(); + if (ret == 1) { + bound = e; +#ifdef WE_HAVE_PBE + /* Registered callbacks retain their lifetime after engine release. */ + we_pbe_ready = 1; +#endif + } + we_binding = 0; + we_unlock_bind(); + return ret; } diff --git a/src/we_mac.c b/src/we_mac.c index 4e50886a..0c759170 100644 --- a/src/we_mac.c +++ b/src/we_mac.c @@ -19,16 +19,15 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include + #include +#include /* Note on CMAC implementation. - * Alias used as EVP_PKEY created with OpenSSL and wolfEngine both have the - * wolfEngine method. Need to distinguish between the two as different data - * types are stored: - * OpenSSL - CMAC_CTX - * wolfEngine - ASN1_OCTET_STRING - * CMAC_CTX doesn't allow getting key data so can't be used by wolfEngine. + * Engine-created PKEYs retain CMAC_CTX owned by OpenSSL's global ASN.1 method. + * A private cipher safely carries the key while wolfCrypt performs the CMAC. */ #if defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC) @@ -39,6 +38,210 @@ /** CMAC algorithm */ #define WE_CMAC_ALGO 2 +#ifdef WE_HAVE_CMAC +#include "we_cmac_compat.h" + +/** Private cipher used to retain CMAC key material in an OpenSSL CMAC_CTX. */ +typedef struct we_CmacCipher +{ + Aes aes; + unsigned char key[AES_256_KEY_SIZE]; + unsigned char iv[WC_AES_BLOCK_SIZE]; + int keySz; + int initialized; +} we_CmacCipher; + +/** Private CMAC key-carrier cipher. Not included in the advertised NID list. */ +EVP_CIPHER *we_cmac_ciph = NULL; + +/** Release the wolfCrypt AES state held by the private CMAC cipher. */ +static int we_cmac_cipher_cleanup(EVP_CIPHER_CTX *ctx) +{ + we_CmacCipher *aes; + + aes = (we_CmacCipher *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if (aes == NULL) + return 0; + + if (aes->initialized) { + wc_AesFree(&aes->aes); + aes->initialized = 0; + } + OPENSSL_cleanse(aes, sizeof(*aes)); + return 1; +} + +/** Initialize or reset the private CMAC key-carrier cipher. */ +static int we_cmac_cipher_init(EVP_CIPHER_CTX *ctx, + const unsigned char *key, const unsigned char *iv, int enc) +{ + static const unsigned char zeroIv[WC_AES_BLOCK_SIZE] = { 0 }; + int ret = 1; + int rc; + int keySz; + we_CmacCipher *aes; + + aes = (we_CmacCipher *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if ((aes == NULL) || (enc != 1)) + ret = 0; + + if ((ret == 1) && (key != NULL)) { + keySz = EVP_CIPHER_CTX_key_length(ctx); + if ((keySz != AES_128_KEY_SIZE) && (keySz != AES_192_KEY_SIZE) && + (keySz != AES_256_KEY_SIZE)) { + ret = 0; + } + if ((ret == 1) && aes->initialized) { + wc_AesFree(&aes->aes); + aes->initialized = 0; + } + if (ret == 1) { + rc = wc_AesInit(&aes->aes, NULL, INVALID_DEVID); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesInit", rc); + ret = 0; + } + else { + aes->initialized = 1; + } + } + if (ret == 1) { + if (iv == NULL) + iv = zeroIv; + rc = wc_AesSetKey(&aes->aes, key, keySz, iv, AES_ENCRYPTION); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetKey", rc); + wc_AesFree(&aes->aes); + aes->initialized = 0; + ret = 0; + } + } + if (ret == 1) { + OPENSSL_cleanse(aes->key, sizeof(aes->key)); + XMEMCPY(aes->key, key, keySz); + XMEMCPY(aes->iv, iv, sizeof(aes->iv)); + aes->keySz = keySz; + } + } + else if ((ret == 1) && (iv != NULL)) { + if (!aes->initialized) { + ret = 0; + } + else { + rc = wc_AesSetIV(&aes->aes, iv); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesSetIV", rc); + ret = 0; + } + else { + XMEMCPY(aes->iv, iv, sizeof(aes->iv)); + } + } + } + + return ret; +} + +/** Encrypt a complete block for OpenSSL's CMAC key derivation. */ +static int we_cmac_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + int ret = 1; + int rc; + int i; + size_t off; + unsigned char block[WC_AES_BLOCK_SIZE]; + we_CmacCipher *aes; + + aes = (we_CmacCipher *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if ((aes == NULL) || (!aes->initialized) || (out == NULL) || + (in == NULL) || ((len % WC_AES_BLOCK_SIZE) != 0)) { + ret = 0; + } + for (off = 0; (ret == 1) && (off < len); off += WC_AES_BLOCK_SIZE) { + for (i = 0; i < WC_AES_BLOCK_SIZE; i++) + block[i] = in[off + i] ^ aes->iv[i]; +#if defined(WE_AES_DIRECT_RETURNS_VOID) || (defined(HAVE_FIPS) && \ + (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION <= 2))) + wc_AesEncryptDirect(&aes->aes, out + off, block); + rc = 0; +#else + rc = wc_AesEncryptDirect(&aes->aes, out + off, block); +#endif + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_CIPHER, "wc_AesEncryptDirect", rc); + ret = 0; + } + else { + XMEMCPY(aes->iv, out + off, sizeof(aes->iv)); + } + } + OPENSSL_cleanse(block, sizeof(block)); + + return ret; +} + +/** Initialize and safely copy private CMAC cipher state. */ +static int we_cmac_cipher_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, + void *ptr) +{ + int ret = 1; + int rc; + EVP_CIPHER_CTX *dstCtx = NULL; + we_CmacCipher *aes; + we_CmacCipher *dst = NULL; + + (void)arg; + + aes = (we_CmacCipher *)EVP_CIPHER_CTX_get_cipher_data(ctx); + if (aes == NULL) + ret = 0; + + if (ret == 1) { + switch (type) { + case EVP_CTRL_INIT: + XMEMSET(aes, 0, sizeof(*aes)); + break; + + case EVP_CTRL_COPY: + dstCtx = (EVP_CIPHER_CTX *)ptr; + if (dstCtx == NULL) { + ret = 0; + break; + } + dst = (we_CmacCipher *)EVP_CIPHER_CTX_get_cipher_data(dstCtx); + if (dst == NULL) { + ret = 0; + break; + } + XMEMSET(&dst->aes, 0, sizeof(dst->aes)); + dst->initialized = 0; + if (aes->initialized) { + rc = wc_AesInit(&dst->aes, NULL, INVALID_DEVID); + if (rc == 0) { + dst->initialized = 1; + rc = wc_AesSetKey(&dst->aes, dst->key, dst->keySz, + dst->iv, AES_ENCRYPTION); + } + if (rc != 0) { + if (dst->initialized) + wc_AesFree(&dst->aes); + dst->initialized = 0; + ret = 0; + } + } + break; + + default: + ret = 0; + break; + } + } + + return ret; +} +#endif /* WE_HAVE_CMAC */ + /** * Data required to complete an MAC operation. */ @@ -63,6 +266,16 @@ typedef struct we_Mac int size; /** Type of digest to use. */ int type; +#ifdef WE_HAVE_HMAC + /** Context-owned storage for normalized short HMAC keys. */ + byte hmacKey[WC_MAX_BLOCK_SIZE]; +#endif +#ifdef WE_HAVE_CMAC + /** Selected CMAC cipher. */ + int cipherNid; + /** Whether wolfCrypt CMAC state needs to be released. */ + int cmacInitialized; +#endif } we_Mac; /** @@ -78,6 +291,7 @@ static int we_mac_set_key(we_Mac* mac, const unsigned char* newKey, int newKeySz) { int ret = 1; + unsigned char *key = NULL; WOLFENGINE_ENTER(WE_LOG_MAC, "we_mac_set_key"); @@ -93,21 +307,23 @@ static int we_mac_set_key(we_Mac* mac, const unsigned char* newKey, } if (ret == 1) { - /* Dispose of old key. */ - if (mac->key != NULL) { - OPENSSL_clear_free(mac->key, mac->keySz); - } /* We allow the key size to be 0, which OpenSSL also allows. In that * case, we need to allocate at least one byte, which we'll set to a * null terminator. */ - mac->key = (unsigned char *)OPENSSL_malloc(newKeySz + 1); - if (mac->key == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_MAC, "OPENSSL_malloc", mac->key); + key = (unsigned char *)OPENSSL_malloc(newKeySz + 1); + if (key == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_MAC, "OPENSSL_malloc", key); ret = 0; } else { - XMEMCPY(mac->key, newKey, newKeySz); - mac->key[newKeySz] = '\0'; + if (newKeySz > 0) { + XMEMCPY(key, newKey, newKeySz); + } + key[newKeySz] = '\0'; + if (mac->key != NULL) { + OPENSSL_clear_free(mac->key, mac->keySz); + } + mac->key = key; mac->keySz = newKeySz; } } @@ -147,7 +363,11 @@ static int we_mac_get_asn1_key(EVP_PKEY_CTX *ctx, ASN1_OCTET_STRING **pKey) } if (ret == 1) { /* Copy the key into ASN.1 octet string. */ - ASN1_OCTET_STRING_set(key, mac->key, mac->keySz); + if (ASN1_OCTET_STRING_set(key, mac->key, mac->keySz) != 1) { + ASN1_OCTET_STRING_free(key); + key = NULL; + ret = 0; + } } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_mac_get_asn1_key", ret); @@ -272,43 +492,41 @@ static int we_mac_hmac_init(EVP_PKEY_CTX *ctx, we_Mac *mac) int ret; int rc; int blockSize; + const byte *key; + word32 keySz; WOLFENGINE_ENTER(WE_LOG_MAC, "we_mac_hmac_init"); /* Get key into cache. */ ret = we_mac_cache_key(ctx, mac); +#ifdef HAVE_FIPS + if ((ret == 1) && (mac->keySz < HMAC_FIPS_MIN_KEY)) { + WOLFENGINE_ERROR_MSG(WE_LOG_MAC, "HMAC key is below the FIPS minimum"); + ret = 0; + } +#endif if (ret == 1) { /* Set HMAC key into wolfSSL HMAC object. */ WOLFENGINE_MSG(WE_LOG_MAC, "Setting HMAC key"); blockSize = wc_HashGetBlockSize(mac->type); - if (blockSize <= 0) { + if ((blockSize <= 0) || (blockSize > (int)sizeof(mac->hmacKey))) { WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_HashGetBlockSize", blockSize); ret = 0; } } - if (ret == 1 && mac->keySz < blockSize) { - unsigned char *newKey; - /* If the key is smaller than the block size of the underlying hash - * algorithm, we need to pad the key with zeroes to the block size. - * Pad into a fresh buffer so the old key bytes can be wiped. */ - newKey = (unsigned char *)OPENSSL_malloc(blockSize); - if (newKey == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_MAC, "OPENSSL_malloc", newKey); - ret = 0; - } - else { - if (mac->keySz > 0) { - XMEMCPY(newKey, mac->key, mac->keySz); + if (ret == 1) { + key = mac->key; + keySz = (word32)mac->keySz; + if (mac->keySz < blockSize) { + /* Keep short-key compatibility without changing the cached key. */ + XMEMSET(mac->hmacKey, 0, sizeof(mac->hmacKey)); + if (keySz > 0) { + XMEMCPY(mac->hmacKey, key, keySz); } - XMEMSET(newKey + mac->keySz, 0, blockSize - mac->keySz); - OPENSSL_clear_free(mac->key, mac->keySz); - mac->key = newKey; - mac->keySz = blockSize; + key = mac->hmacKey; + keySz = (word32)blockSize; } - } - if (ret == 1) { - rc = wc_HmacSetKey(&mac->state.hmac, mac->type, - (const byte*)mac->key, (word32)mac->keySz); + rc = wc_HmacSetKey(&mac->state.hmac, mac->type, key, keySz); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_HmacSetKey", rc); ret = 0; @@ -332,24 +550,63 @@ static int we_mac_hmac_init(EVP_PKEY_CTX *ctx, we_Mac *mac) */ static int we_mac_cmac_init(EVP_PKEY_CTX *ctx, we_Mac *mac) { - int ret; + int ret = 1; int rc; + EVP_PKEY *pkey; + CMAC_CTX *cmac = NULL; + EVP_CIPHER_CTX *cipherCtx = NULL; + we_CmacCipher *carrier = NULL; WOLFENGINE_ENTER(WE_LOG_MAC, "we_mac_cmac_init"); WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [ctx = %p, mac = %p]", ctx, mac); - /* Get key into cache. */ - ret = we_mac_cache_key(ctx, mac); + if ((ctx == NULL) || (mac == NULL)) { + ret = 0; + } if (ret == 1) { - WOLFENGINE_MSG(WE_LOG_MAC, "Initializing wolfCrypt Cmac structure: %p", - &mac->state.cmac); - /* Initialize wolfSSL CMAC object with key. */ - rc = wc_InitCmac(&mac->state.cmac, (const byte*)mac->key, mac->keySz, - WC_CMAC_AES, NULL); + pkey = EVP_PKEY_CTX_get0_pkey(ctx); + if (pkey == NULL) { + ret = 0; + } + } + if (ret == 1) { + cmac = (CMAC_CTX *)EVP_PKEY_get0(pkey); + if (cmac == NULL) + ret = 0; + } + if (ret == 1) { + cipherCtx = CMAC_CTX_get0_cipher_ctx(cmac); + if ((cipherCtx == NULL) || + (EVP_CIPHER_CTX_cipher(cipherCtx) != we_cmac_ciph)) { + ret = 0; + } + } + if (ret == 1) { + carrier = (we_CmacCipher *)EVP_CIPHER_CTX_get_cipher_data(cipherCtx); + if ((carrier == NULL) || (!carrier->initialized) || + (carrier->keySz <= 0) || + (carrier->keySz > (int)sizeof(carrier->key))) { + ret = 0; + } + } + if (ret == 1) + ret = we_mac_set_key(mac, carrier->key, carrier->keySz); + if (ret == 1) { + if (mac->cmacInitialized) { + we_cmac_free(&mac->state.cmac); + mac->cmacInitialized = 0; + } + rc = wc_InitCmac(&mac->state.cmac, (const byte *)mac->key, + (word32)mac->keySz, WC_CMAC_AES, NULL); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_InitCmac", rc); + we_cmac_free(&mac->state.cmac); ret = 0; } + else { + mac->cmacInitialized = 1; + WOLFENGINE_MSG(WE_LOG_MAC, "CMAC backend: wolfCrypt"); + } } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_mac_cmac_init", ret); @@ -387,14 +644,15 @@ static int we_mac_md_to_hash_type(EVP_MD *md) * Supported operations include: * - EVP_PKEY_CTRL_MD: set digest to use or initialize CMAC operation. * - EVP_PKEY_CTRL_SET_MAC_KEY: set password/key to use. - * - EVP_PKEY_CTRL_CIPHER: set cipher to use (ignored). + * - EVP_PKEY_CTRL_CIPHER: validate and set cipher to use with CMAC. * - EVP_PKEY_CTRL_DIGESTINIT: initialize HMAC's digest. * * @param ctx [in] EVP_PKEY context being used. * @param type [in] Type of operation to perform. * @param num [in] Integer parameter. * @param ptr [in] Pointer parameter. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_mac_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) { @@ -485,7 +743,27 @@ static int we_mac_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) case EVP_PKEY_CTRL_CIPHER: /* ptr [in] EVP_CIPHER object. */ WOLFENGINE_MSG(WE_LOG_MAC, "type: EVP_PKEY_CTRL_CIPHER"); - /* Do nothing, we use internal AES */ + #ifdef WE_HAVE_CMAC + if (mac->algo == WE_CMAC_ALGO) { + if (ptr == NULL) { + ret = 0; + } + else { + int cipherNid = EVP_CIPHER_nid( + (const EVP_CIPHER *)ptr); + + switch (cipherNid) { + case NID_aes_128_cbc: + case NID_aes_192_cbc: + case NID_aes_256_cbc: + mac->cipherNid = cipherNid; + break; + default: + ret = 0; + } + } + } + #endif break; /* Initialize the digest operation. */ @@ -509,7 +787,7 @@ static int we_mac_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); WOLFENGINE_ERROR_MSG(WE_LOG_CIPHER, errBuff); - ret = 0; + ret = -2; } } @@ -522,7 +800,7 @@ static int we_mac_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) /** * Handle control string values. * - * Currently a stub function. + * Supports key, hexkey and cipher controls. * * @param ctx [in] EVP_PKEY context being used. * @param type [in] String with the type of ctrl to do. @@ -532,17 +810,126 @@ static int we_mac_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) static int we_mac_pkey_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { - int ret = 0; - - (void)ctx; - (void)type; - (void)value; + int ret = 1; + we_Mac *mac = NULL; WOLFENGINE_ENTER(WE_LOG_MAC, "we_mac_pkey_ctrl_str"); - WOLFENGINE_ERROR_MSG(WE_LOG_MAC, - "This function is currently a stub, was not used in test cases"); - /* TODO: "key", "hexkey", "cipher" */ + if ((ctx == NULL) || (type == NULL) || (value == NULL)) { + ret = 0; + } + if (ret == 1) { + mac = (we_Mac *)EVP_PKEY_CTX_get_data(ctx); + if (mac == NULL) { + ret = 0; + } + } + if ((ret == 1) && (XSTRCMP(type, "key") == 0)) { + size_t keySz = XSTRLEN(value); + + if ((keySz >= INT_MAX) || ((mac->algo == WE_CMAC_ALGO) && + (mac->size != 0) && (keySz != (size_t)mac->size))) { + ret = 0; + } + else { + ret = EVP_PKEY_CTX_ctrl(ctx, -1, -1, + EVP_PKEY_CTRL_SET_MAC_KEY, (int)keySz, (void *)value); + } + } + else if ((ret == 1) && (XSTRCMP(type, "hexkey") == 0)) { + unsigned char *key = NULL; + size_t allocSz = 0; + size_t i; + size_t keySz = 0; + size_t valueSz = XSTRLEN(value); + int high = -1; + + if ((valueSz == 0) || (valueSz > INT_MAX)) { + ret = 0; + } + if (ret == 1) { + allocSz = (valueSz / 2) + 1; + key = (unsigned char *)OPENSSL_malloc(allocSz); + if (key == NULL) { + ret = 0; + } + } + for (i = 0; (ret == 1) && (i < valueSz); i++) { + int digit; + + if (value[i] == ':') { + if ((high != -1) || (keySz == 0) || (i + 1 == valueSz) || + (value[i + 1] == ':')) { + ret = 0; + } + continue; + } + if ((value[i] >= '0') && (value[i] <= '9')) { + digit = value[i] - '0'; + } + else if ((value[i] >= 'a') && (value[i] <= 'f')) { + digit = value[i] - 'a' + 10; + } + else if ((value[i] >= 'A') && (value[i] <= 'F')) { + digit = value[i] - 'A' + 10; + } + else { + ret = 0; + continue; + } + if (high == -1) { + high = digit; + } + else { + key[keySz++] = (unsigned char)((high << 4) | digit); + high = -1; + } + } + if ((ret == 1) && ((high != -1) || ((mac->algo == WE_CMAC_ALGO) && + (mac->size != 0) && (keySz != (size_t)mac->size)))) { + ret = 0; + } + if (ret == 1) { + ret = EVP_PKEY_CTX_ctrl(ctx, -1, -1, + EVP_PKEY_CTRL_SET_MAC_KEY, (int)keySz, key); + } + OPENSSL_clear_free(key, allocSz); + } + else if ((ret == 1) && (XSTRCMP(type, "cipher") == 0)) { + const EVP_CIPHER *cipher = EVP_get_cipherbyname(value); + + if ((mac->algo != WE_CMAC_ALGO) || (cipher == NULL)) { + ret = 0; + } + else { + int keySz = EVP_CIPHER_key_length(cipher); + + switch (EVP_CIPHER_nid(cipher)) { + case NID_aes_128_cbc: + case NID_aes_192_cbc: + case NID_aes_256_cbc: + if ((mac->key != NULL) && (mac->keySz != keySz)) { + ret = 0; + } + else { + int oldSize = mac->size; + + mac->size = keySz; + ret = EVP_PKEY_CTX_ctrl(ctx, -1, -1, + EVP_PKEY_CTRL_CIPHER, 0, (void *)cipher); + if (ret != 1) { + mac->size = oldSize; + } + } + break; + default: + ret = 0; + } + } + } + else if (ret == 1) { + ret = 0; + } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_mac_pkey_ctrl_str", ret); @@ -585,13 +972,21 @@ static int we_mac_dup(we_Mac *src, we_Mac **dst) mac->size = src->size; mac->type = src->type; mac->keySz = src->keySz; + #ifdef WE_HAVE_CMAC + mac->cipherNid = src->cipherNid; + #endif /* Duplicate the key if set. */ - if (src->keySz >= 0) { + if (src->key != NULL) { ret = we_mac_set_key(mac, src->key, src->keySz); } else { mac->key = NULL; } +#ifdef WE_HAVE_HMAC + if (ret == 1) { + XMEMCPY(mac->hmacKey, src->hmacKey, sizeof(mac->hmacKey)); + } +#endif } if ((ret != 1) && (mac != NULL)) { @@ -651,7 +1046,8 @@ static void we_mac_pkey_cleanup(EVP_PKEY_CTX *ctx) #ifdef WE_HAVE_CMAC case WE_CMAC_ALGO: WOLFENGINE_MSG(WE_LOG_MAC, "MAC algo: WE_CMAC_ALGO"); - /* No free for wolfCrypt CMAC. */ + if (mac->cmacInitialized) + we_cmac_free(&mac->state.cmac); break; #endif default: @@ -663,7 +1059,8 @@ static void we_mac_pkey_cleanup(EVP_PKEY_CTX *ctx) /* Safely dispose of key memory. */ OPENSSL_clear_free(mac->key, mac->keySz); } - /* Dispose of internal MAC object memory. */ + /* Safely dispose of MAC state and internal object memory. */ + OPENSSL_cleanse(mac, sizeof(*mac)); OPENSSL_free(mac); } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_mac_pkey_cleanup", ret); @@ -754,7 +1151,7 @@ static int we_hmac_pkey_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) /* Assign algorithm and key to PKEY. */ if (EVP_PKEY_assign(pkey, EVP_PKEY_HMAC, key) != 1) { WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "EVP_PKEY_assign", 0); - ASN1_OCTET_STRING_free(key); + ASN1_STRING_clear_free((ASN1_STRING*)key); ret = 0; } } @@ -783,7 +1180,7 @@ static void we_hmac_pkey_free(EVP_PKEY *pkey) } if (ret == 1) { /* Dispose of key. */ - ASN1_OCTET_STRING_free(key); + ASN1_STRING_clear_free((ASN1_STRING*)key); } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_hmac_pkey_free", ret); @@ -935,7 +1332,7 @@ static int we_hmac_pkey_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { int ret = 1; we_Mac *mac; - we_Mac *dupl; + we_Mac *dupl = NULL; WOLFENGINE_ENTER(WE_LOG_MAC, "we_hmac_pkey_copy"); WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [dst = %p, src = %p]", dst, src); @@ -967,8 +1364,25 @@ static int we_hmac_pkey_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) } if (ret == 1) { /* Set the internal MAC object against context. */ +#ifdef WOLF_CRYPTO_CB + if (mac->state.hmac.keyRaw == mac->hmacKey) { + dupl->state.hmac.keyRaw = dupl->hmacKey; + } + else if (mac->state.hmac.keyRaw == mac->key) { + dupl->state.hmac.keyRaw = dupl->key; + } + dupl->state.hmac.keyLen = mac->state.hmac.keyLen; +#endif EVP_PKEY_CTX_set_data(dst, dupl); } + else if (dupl != NULL) { + wc_HmacFree(&dupl->state.hmac); + if (dupl->key != NULL) { + OPENSSL_clear_free(dupl->key, dupl->keySz); + } + OPENSSL_cleanse(dupl, sizeof(*dupl)); + OPENSSL_free(dupl); + } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_hmac_pkey_copy", ret); @@ -978,37 +1392,58 @@ static int we_hmac_pkey_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) /** * Initialize for HMAC operation using wolfSSL. * - * @param ctx [in] EVP_PKEY context of operation. + * @param ctx [in] EVP_PKEY context of operation. + * @param hmacInit [in] HMAC initialization function. * @return 1 on success and 0 on failure. */ -static int we_hmac_pkey_init(EVP_PKEY_CTX *ctx) +int we_hmac_pkey_init_ex(EVP_PKEY_CTX *ctx, we_HmacInitCb hmacInit) { int ret = 1, rc; we_Mac *mac = NULL; - WOLFENGINE_ENTER(WE_LOG_MAC, "we_hmac_pkey_init"); + WOLFENGINE_ENTER(WE_LOG_MAC, "we_hmac_pkey_init_ex"); WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [ctx = %p]", ctx); + if (hmacInit == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_MAC, "hmacInit", hmacInit); + ret = 0; + } + /* Initialize the internal MAC object. */ - ret = we_mac_pkey_init(ctx, &mac); if (ret == 1) { + ret = we_mac_pkey_init(ctx, &mac); + } + if (ret == 1) { + /* Set the algorithm before initialization so cleanup is safe when + * initialization fails. */ + mac->algo = WE_HMAC_ALGO; + /* Initialize the wolfCrypt HMAC object. */ - rc = wc_HmacInit(&mac->state.hmac, NULL, INVALID_DEVID); + rc = hmacInit(&mac->state.hmac, NULL, INVALID_DEVID); if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_HmacInit", rc); + WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "hmacInit", rc); ret = 0; } + else { + mac->state.hmac.macType = WC_HASH_TYPE_NONE; + } } - if (ret == 1) { - /* Set the algorithm to HMAC. */ - mac->algo = WE_HMAC_ALGO; + if ((ret == 0) && (mac != NULL)) { + /* OpenSSL does not call the method cleanup when initialization fails. + * Release the partially initialized state here. */ + we_mac_pkey_cleanup(ctx); } - WOLFENGINE_LEAVE(WE_LOG_MAC, "we_hmac_pkey_init", ret); + WOLFENGINE_LEAVE(WE_LOG_MAC, "we_hmac_pkey_init_ex", ret); return ret; } +static int we_hmac_pkey_init(EVP_PKEY_CTX *ctx) +{ + return we_hmac_pkey_init_ex(ctx, wc_HmacInit); +} + /** * Update the HMAC hmac with dataSz bytes from data. If wolfEngine has been * built with WE_ALIGNMENT_SAFETY, this function provides a fix for a potential @@ -1027,6 +1462,11 @@ int we_hmac_update(Hmac* hmac, const void *data, size_t dataSz) { WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [hmac = %p, data = %p, " "dataSz = %zu]", hmac, data, dataSz); + if (dataSz > UINT32_MAX) { + WOLFENGINE_LEAVE(WE_LOG_MAC, "we_hmac_update", 0); + return 0; + } + #ifdef WE_ALIGNMENT_SAFETY const word32 ALIGNMENT_REQ = 8; word32 add = 0; @@ -1036,7 +1476,7 @@ int we_hmac_update(Hmac* hmac, const void *data, size_t dataSz) { hmac->macType == WC_HASH_TYPE_SHA512) { internalBuffLen = hmac->hash.sha512.buffLen; add = dataSz > (WC_SHA512_BLOCK_SIZE - internalBuffLen) ? - (WC_SHA512_BLOCK_SIZE - internalBuffLen) : dataSz; + (WC_SHA512_BLOCK_SIZE - internalBuffLen) : (word32)dataSz; } /* If the conditions below are satisfied, just calling wc_HmacUpdate with * the passed in buffer and length can cause a memory alignment crash on @@ -1054,9 +1494,9 @@ int we_hmac_update(Hmac* hmac, const void *data, size_t dataSz) { } if (ret == 1) { /* Allocate new, aligned buffer. */ - tmp = (byte*)XMALLOC(WC_SHA512_BLOCK_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER); + tmp = (byte*)OPENSSL_malloc(WC_SHA512_BLOCK_SIZE); if (tmp == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_MAC, "XMALLOC", tmp); + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_MAC, "OPENSSL_malloc", tmp); ret = 0; } } @@ -1069,7 +1509,7 @@ int we_hmac_update(Hmac* hmac, const void *data, size_t dataSz) { size_t nextLen = (remaining <= WC_SHA512_BLOCK_SIZE) ? remaining : WC_SHA512_BLOCK_SIZE; XMEMCPY(tmp, nextData, nextLen); - rc = wc_HmacUpdate(hmac, (const byte*)tmp, nextLen); + rc = wc_HmacUpdate(hmac, (const byte*)tmp, (word32)nextLen); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_HmacUpdate", rc); ret = 0; @@ -1081,7 +1521,7 @@ int we_hmac_update(Hmac* hmac, const void *data, size_t dataSz) { } if (tmp != NULL) { - XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER); + OPENSSL_clear_free(tmp, WC_SHA512_BLOCK_SIZE); } } else @@ -1222,7 +1662,8 @@ static int we_hmac_pkey_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, } } - /* Input signature length ignored - set to algorithm output size. */ + /* OpenSSL's TLS PRF passes an uninitialized length, so ignore it like + * OpenSSL's own HMAC method does. */ if (ret == 1) { *sigLen = (size_t)mac->size; } @@ -1287,8 +1728,8 @@ int we_init_hmac_pkey_meth(void) */ static int we_hmac_pkey_asn1_size(const EVP_PKEY *pkey) { - /* Return wolfCrypt's maximum HMAC block size that is the output size. */ - int ret = WC_HMAC_BLOCK_SIZE; + /* Return wolfCrypt's maximum HMAC output size. */ + int ret = WC_MAX_DIGEST_SIZE; WOLFENGINE_ENTER(WE_LOG_MAC, "we_hmac_pkey_asn1_size"); WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [pkey = %p]", pkey); @@ -1345,7 +1786,7 @@ static int we_hmac_pkey_asn1_set_priv_key(EVP_PKEY *pkey, /* Dispose of ASN.1 object on failure. */ if ((ret == 0) && (asn1 != NULL)) { - ASN1_OCTET_STRING_free(asn1); + ASN1_STRING_clear_free((ASN1_STRING*)asn1); } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_hmac_pkey_asn1_set_priv_key", ret); @@ -1366,6 +1807,7 @@ static int we_hmac_pkey_asn1_get_priv_key(const EVP_PKEY *pkey, { int ret = 1; const unsigned char* privTmp; + size_t bufferLen = 0; WOLFENGINE_ENTER(WE_LOG_MAC, "we_hmac_pkey_asn1_get_priv_key"); @@ -1375,14 +1817,17 @@ static int we_hmac_pkey_asn1_get_priv_key(const EVP_PKEY *pkey, } if (ret == 1) { + if (priv != NULL) + bufferLen = *len; privTmp = EVP_PKEY_get0_hmac(pkey, len); if (privTmp == NULL) { ret = 0; } - else { - if (priv != NULL) { - XMEMCPY(priv, privTmp, *len); - } + else if ((priv != NULL) && (bufferLen < *len)) { + ret = 0; + } + else if (priv != NULL) { + XMEMCPY(priv, privTmp, *len); } } @@ -1460,10 +1905,6 @@ int we_init_hmac_pkey_asn1_meth(void) EVP_PKEY_asn1_set_get_priv_key(we_hmac_pkey_asn1_method, we_hmac_pkey_asn1_get_priv_key); #endif - /* Add our created asn1 method to the internal list of available - * methods. */ - /* Known, still-reachable memory leak from openssl internals on 1.0.2 */ - EVP_PKEY_asn1_add0(we_hmac_pkey_asn1_method); } /* No failure after allocation - no need to free on error. */ @@ -1498,7 +1939,12 @@ EVP_PKEY_ASN1_METHOD *we_cmac_we_pkey_asn1_method = NULL; static int we_cmac_pkey_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { int ret = 1; - ASN1_OCTET_STRING *key; + int keySz = 0; + we_Mac *mac = NULL; + CMAC_CTX *cmac = NULL; + EVP_CIPHER_CTX *cipherCtx = NULL; + const EVP_CIPHER *cipher = NULL; + ENGINE *engine = NULL; WOLFENGINE_ENTER(WE_LOG_MAC, "we_cmac_pkey_keygen"); WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [ctx = %p, pkey = %p]", ctx, pkey); @@ -1513,12 +1959,75 @@ static int we_cmac_pkey_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) } if (ret == 1) { - /* Make an ASN.1 octet string from key data. */ - ret = we_mac_get_asn1_key(ctx, &key); + mac = (we_Mac *)EVP_PKEY_CTX_get_data(ctx); + if ((mac == NULL) || (mac->key == NULL)) { + ret = 0; + } } if (ret == 1) { - /* Assign algorithm and key to PKEY. */ - EVP_PKEY_assign(pkey, EVP_PKEY_CMAC, key); + switch (mac->cipherNid) { + case NID_aes_128_cbc: + keySz = AES_128_KEY_SIZE; + break; + case NID_aes_192_cbc: + keySz = AES_192_KEY_SIZE; + break; + case NID_aes_256_cbc: + keySz = AES_256_KEY_SIZE; + break; + case NID_undef: + keySz = mac->keySz; + break; + default: + ret = 0; + } + if ((ret == 1) && ((keySz != AES_128_KEY_SIZE) && + (keySz != AES_192_KEY_SIZE) && + (keySz != AES_256_KEY_SIZE))) { + ret = 0; + } + if ((ret == 1) && (mac->keySz != keySz)) { + ret = 0; + } + } + if (ret == 1) { + cmac = CMAC_CTX_new(); + if (cmac == NULL) { + ret = 0; + } + } + if (ret == 1) { + engine = wolfengine_get_bound_engine(); + if (engine == NULL) + ret = 0; + } + if (ret == 1) { + cipher = ENGINE_get_cipher(engine, NID_cmac); + if ((cipher == NULL) || (cipher != we_cmac_ciph)) + ret = 0; + } + if (ret == 1) { + cipherCtx = CMAC_CTX_get0_cipher_ctx(cmac); + if (cipherCtx == NULL) { + ret = 0; + } + else { + EVP_CIPHER_CTX_set_flags(cipherCtx, + EVP_CIPH_FLAG_NON_FIPS_ALLOW); + } + } + if ((ret == 1) && (CMAC_Init(cmac, mac->key, (size_t)mac->keySz, + cipher, engine) != 1)) { + ret = 0; + } + if ((ret == 1) && + (EVP_PKEY_assign(pkey, EVP_PKEY_CMAC, cmac) != 1)) { + WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "EVP_PKEY_assign", 0); + ret = 0; + } + if (ret == 1) + cmac = NULL; + if (ret == 1) { #if OPENSSL_VERSION_NUMBER >= 0x10101000L /* Set alias to distinguish between OpenSSL and wolfEngine created. */ ret = EVP_PKEY_set_alias_type(pkey, NID_wolfengine_cmac); @@ -1527,58 +2036,34 @@ static int we_cmac_pkey_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) #endif } + CMAC_CTX_free(cmac); + if (engine != NULL) + ENGINE_finish(engine); + WOLFENGINE_LEAVE(WE_LOG_MAC, "we_cmac_pkey_keygen", ret); return ret; } /** - * Free PKEY data that is either of type ASN1_OCTET_STRING or CMAC_CTX. + * Free the CMAC context held by a PKEY. * * @param pkey [in] EVP PKEY being freed. */ static void we_cmac_pkey_free(EVP_PKEY *pkey) { int ret = 1; + CMAC_CTX *cmac; WOLFENGINE_ENTER(WE_LOG_MAC, "we_cmac_pkey_free"); WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [pkey = %p]", pkey); - /* Can be either local alias or CMAC with OpenSSL data. */ -#if OPENSSL_VERSION_NUMBER >= 0x1000212fL - if (EVP_PKEY_id(pkey) == NID_wolfengine_cmac) -#endif - { - ASN1_OCTET_STRING *key; - - WOLFENGINE_MSG(WE_LOG_MAC, "EVP_PKEY_id: NID_wolfengine_cmac"); - - /* Get the key as an ASN.1 octet string. */ - key = (ASN1_OCTET_STRING*)EVP_PKEY_get0(pkey); - if (key != NULL) { - /* Dispose of object. */ - ASN1_OCTET_STRING_free(key); - } - else { - ret = 0; - } + cmac = (CMAC_CTX *)EVP_PKEY_get0(pkey); + if (cmac != NULL) { + CMAC_CTX_free(cmac); } -#if OPENSSL_VERSION_NUMBER >= 0x1000212fL else { - CMAC_CTX *cmac; - - WOLFENGINE_MSG(WE_LOG_MAC, "EVP_PKEY_id: EVP_PKEY_CMAC"); - - /* Get the key as CMAC_CTX. */ - cmac = (CMAC_CTX*)EVP_PKEY_get0(pkey); - if (cmac != NULL) { - /* Dispose of object. */ - CMAC_CTX_free(cmac); - } - else { - ret = 0; - } + ret = 0; } -#endif WOLFENGINE_LEAVE(WE_LOG_MAC, "we_cmac_pkey_free", ret); @@ -1605,7 +2090,7 @@ static int we_cmac_copy(we_Mac* mac, Cmac* dst, Cmac* src) /* Initialize the wolfCrypt CMAC object for AES. */ rc = wc_InitCmac(dst, (const byte*)mac->key, mac->keySz, WC_CMAC_AES, NULL); if (rc != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_InitCmac", ret); + WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_InitCmac", rc); ret = 0; } @@ -1641,7 +2126,7 @@ static int we_cmac_pkey_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { int ret = 1; we_Mac *mac; - we_Mac *dupl; + we_Mac *dupl = NULL; WOLFENGINE_ENTER(WE_LOG_MAC, "we_cmac_pkey_copy"); WOLFENGINE_MSG_VERBOSE(WE_LOG_MAC, "ARGS [dst = %p, src = %p]", dst, src); @@ -1670,11 +2155,21 @@ static int we_cmac_pkey_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) if (ret == 1) { /* Copy wolfSSL CMAC object. */ ret = we_cmac_copy(mac, &dupl->state.cmac, &mac->state.cmac); + if (ret == 1) + dupl->cmacInitialized = 1; } if (ret == 1) { /* Set the internal MAC object against context. */ EVP_PKEY_CTX_set_data(dst, dupl); } + if ((ret == 0) && (dupl != NULL)) { + we_cmac_free(&dupl->state.cmac); + if (dupl->key != NULL) { + OPENSSL_clear_free(dupl->key, dupl->keySz); + } + OPENSSL_cleanse(dupl, sizeof(*dupl)); + OPENSSL_free(dupl); + } WOLFENGINE_LEAVE(WE_LOG_MAC, "we_cmac_pkey_copy", ret); @@ -1708,6 +2203,9 @@ static int we_cmac_pkey_update(EVP_MD_CTX *ctx, const void *data, size_t dataSz) "we_cmac_pkey_update, data:", (void*)data); ret = 0; } + else if (dataSz > UINT32_MAX) { + ret = 0; + } if (ret == 1) { EVP_PKEY_CTX *pkeyCtx; @@ -1729,8 +2227,8 @@ static int we_cmac_pkey_update(EVP_MD_CTX *ctx, const void *data, size_t dataSz) } if ((ret == 1) && (dataSz != 0)) { - /* Update the wolfCrypt CMAC object with more data. */ - rc = wc_CmacUpdate(&mac->state.cmac, (const byte*)data, (word32)dataSz); + rc = wc_CmacUpdate(&mac->state.cmac, (const byte *)data, + (word32)dataSz); if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_CmacUpdate", rc); ret = 0; @@ -1805,15 +2303,17 @@ static int we_cmac_pkey_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, } } - if ((ret == 1) && (sig == NULL)) { - /* Set to full CMAC output size. */ + if (ret == 1) { + if ((sig != NULL) && (*sigLen < WC_CMAC_TAG_MAX_SZ)) + ret = 0; *sigLen = WC_CMAC_TAG_MAX_SZ; } - else if ((ret == 1) && (sig != NULL)) { + if ((ret == 1) && (sig != NULL)) { word32 len = WC_CMAC_TAG_MAX_SZ; /* Calculate MAC output. */ - rc = wc_CmacFinal(&mac->state.cmac, (byte*)sig, &len); + rc = wc_CmacFinal(&mac->state.cmac, (byte *)sig, &len); + mac->cmacInitialized = 0; if (rc != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_CmacFinal", rc); ret = 0; @@ -1878,6 +2378,57 @@ static int we_cmac_pkey_keygen_init(EVP_PKEY_CTX *ctx) } +/** Flags for the private CMAC key-carrier cipher. */ +#define WE_CMAC_CIPHER_FLAGS \ + (EVP_CIPH_FLAG_DEFAULT_ASN1 | \ + EVP_CIPH_CBC_MODE | \ + EVP_CIPH_VARIABLE_LENGTH | \ + EVP_CIPH_ALWAYS_CALL_INIT | \ + EVP_CIPH_CTRL_INIT | \ + EVP_CIPH_CUSTOM_COPY | \ + EVP_CIPH_FLAG_NON_FIPS_ALLOW) + +/** Create the private CMAC key-carrier cipher method. */ +int we_init_cmac_cipher_meth(void) +{ + int ret = 1; + + we_cmac_ciph = EVP_CIPHER_meth_new(NID_cmac, WC_AES_BLOCK_SIZE, + AES_256_KEY_SIZE); + if (we_cmac_ciph == NULL) + ret = 0; + if (ret == 1) + ret = EVP_CIPHER_meth_set_iv_length(we_cmac_ciph, + WC_AES_BLOCK_SIZE); + if (ret == 1) + ret = EVP_CIPHER_meth_set_flags(we_cmac_ciph, + WE_CMAC_CIPHER_FLAGS); + if (ret == 1) + ret = EVP_CIPHER_meth_set_init(we_cmac_ciph, we_cmac_cipher_init); + if (ret == 1) + ret = EVP_CIPHER_meth_set_do_cipher(we_cmac_ciph, we_cmac_cipher); + if (ret == 1) + ret = EVP_CIPHER_meth_set_ctrl(we_cmac_ciph, we_cmac_cipher_ctrl); + if (ret == 1) + ret = EVP_CIPHER_meth_set_impl_ctx_size(we_cmac_ciph, + sizeof(we_CmacCipher)); + if (ret == 1) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + ret = EVP_CIPHER_meth_set_cleanup(we_cmac_ciph, + we_cmac_cipher_cleanup); +#else + we_cmac_ciph->cleanup = we_cmac_cipher_cleanup; +#endif + } + if (ret != 1) { + EVP_CIPHER_meth_free(we_cmac_ciph); + we_cmac_ciph = NULL; + } + + return ret; +} + + /** * Create a new method and assign the functions to use for CMAC. * @@ -1978,16 +2529,6 @@ int we_init_cmac_pkey_asn1_meth(void) ret = 0; } if (ret == 1) { - /* Set with CMAC methods. */ - EVP_PKEY_asn1_set_free(we_cmac_pkey_asn1_method, we_cmac_pkey_free); - EVP_PKEY_asn1_set_public(we_cmac_pkey_asn1_method, 0, 0, 0, 0, - we_cmac_pkey_asn1_size, 0); - /* Add our created asn1 method to the internal list of available - * methods. */ - /* Known, still-reachable memory leak from openssl internals on 1.0.2 */ - EVP_PKEY_asn1_add0(we_cmac_pkey_asn1_method); - EVP_PKEY_asn1_add_alias(EVP_PKEY_CMAC, NID_wolfengine_cmac); - /* Create alternative ASN.1 method object for local NID. * (See comment at top.) */ we_cmac_we_pkey_asn1_method = EVP_PKEY_asn1_new(NID_wolfengine_cmac, 0, @@ -1999,12 +2540,20 @@ int we_init_cmac_pkey_asn1_meth(void) } } if (ret == 1) { - /* Set with same CMAC methods. */ + /* Set with CMAC methods. */ + EVP_PKEY_asn1_set_free(we_cmac_pkey_asn1_method, we_cmac_pkey_free); + EVP_PKEY_asn1_set_public(we_cmac_pkey_asn1_method, 0, 0, 0, 0, + we_cmac_pkey_asn1_size, 0); + /* Set alternative with same CMAC methods. */ EVP_PKEY_asn1_copy(we_cmac_we_pkey_asn1_method, we_cmac_pkey_asn1_method); + /* CMAC key generation uses this callback-free alias to select the + * alternative PKEY method without retaining either engine-owned + * ASN.1 method. */ + EVP_PKEY_asn1_add_alias(EVP_PKEY_CMAC, NID_wolfengine_cmac); } - /* No failure after alias creation - no need to free on error. */ + /* No failure after setup - no need to free on error. */ if ((ret == 0) && (we_cmac_pkey_asn1_method != NULL)) { /* Free the CMAC method object and reset pointer to NULL. */ EVP_PKEY_asn1_free(we_cmac_pkey_asn1_method); diff --git a/src/we_openssl_bc.c b/src/we_openssl_bc.c index e49624bc..77da3939 100644 --- a/src/we_openssl_bc.c +++ b/src/we_openssl_bc.c @@ -54,6 +54,19 @@ int EVP_MD_meth_set_update(EVP_MD *md, int (*update)(EVP_MD_CTX *ctx, return 1; } +int EVP_MD_meth_set_copy(EVP_MD *md, int (*copy)(EVP_MD_CTX *to, + const EVP_MD_CTX *from)) +{ + md->copy = copy; + return 1; +} + +int (*EVP_MD_meth_get_copy(const EVP_MD *md))(EVP_MD_CTX *to, + const EVP_MD_CTX *from) +{ + return md->copy; +} + int EVP_MD_meth_set_final(EVP_MD *md, int (*final)(EVP_MD_CTX *ctx, unsigned char *md)) { @@ -149,6 +162,13 @@ int EVP_CIPHER_meth_set_init(EVP_CIPHER *cipher, return 1; } +int EVP_CIPHER_meth_set_cleanup(EVP_CIPHER *cipher, + int (*cleanup)(EVP_CIPHER_CTX *ctx)) +{ + cipher->cleanup = cleanup; + return 1; +} + int EVP_CIPHER_meth_set_do_cipher(EVP_CIPHER *cipher, int (*do_cipher) (EVP_CIPHER_CTX *ctx, unsigned char *out, @@ -193,23 +213,46 @@ void EVP_CIPHER_meth_free(EVP_CIPHER *cipher) size_t EC_KEY_priv2buf(const EC_KEY *eckey, unsigned char **pbuf) { const BIGNUM *priv_key_bn = NULL; - size_t priv_len = 0; + const EC_GROUP *group = NULL; + BIGNUM *order = NULL; + int priv_len = 0; + int order_len = 0; + size_t ret = 0; unsigned char *priv_key_buf = NULL; priv_key_bn = EC_KEY_get0_private_key(eckey); - priv_len = BN_num_bytes(priv_key_bn); + if (priv_key_bn == NULL) + return 0; + group = EC_KEY_get0_group(eckey); + if (group == NULL) + return 0; - if (priv_len == 0) + order = BN_new(); + if (order == NULL) return 0; + if (EC_GROUP_get_order(group, order, NULL) != 1) + goto end; + + priv_len = BN_num_bytes(priv_key_bn); + order_len = BN_num_bytes(order); + if ((priv_len <= 0) || (order_len <= 0) || (priv_len > order_len)) + goto end; - priv_key_buf = OPENSSL_malloc(priv_len); + priv_key_buf = OPENSSL_zalloc((size_t)order_len); if (priv_key_buf == NULL) - return 0; - - BN_bn2bin(priv_key_bn, priv_key_buf); + goto end; + if (BN_bn2bin(priv_key_bn, + priv_key_buf + order_len - priv_len) != priv_len) { + goto end; + } *pbuf = priv_key_buf; + priv_key_buf = NULL; + ret = (size_t)order_len; - return priv_len; +end: + OPENSSL_clear_free(priv_key_buf, (size_t)order_len); + BN_free(order); + return ret; } void OPENSSL_clear_free(void *str, size_t num) @@ -392,17 +435,17 @@ int RSA_meth_set_keygen(RSA_METHOD *meth, RSA_METHOD *RSA_meth_new(const char *name, int flags) { - RSA_METHOD *meth = OPENSSL_zalloc(sizeof(*meth)); + RSA_METHOD *meth = NULL; + if (name != NULL) { + meth = OPENSSL_zalloc(sizeof(*meth)); + } if (meth != NULL) { meth->flags = flags; - if (name != NULL) { - meth->name = name; - return meth; - } + meth->name = name; } - return NULL; + return meth; } void RSA_meth_free(RSA_METHOD *meth) @@ -518,17 +561,17 @@ int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) DH_METHOD *DH_meth_new(const char *name, int flags) { - DH_METHOD *dhm = OPENSSL_zalloc(sizeof(*dhm)); + DH_METHOD *dhm = NULL; + if (name != NULL) { + dhm = OPENSSL_zalloc(sizeof(*dhm)); + } if (dhm != NULL) { dhm->flags = flags; - if (name != NULL) { - dhm->name = name; - return dhm; - } + dhm->name = name; } - return NULL; + return dhm; } void DH_meth_free(DH_METHOD *dhm) diff --git a/src/we_pbe.c b/src/we_pbe.c index bf56072c..4ae71c3d 100644 --- a/src/we_pbe.c +++ b/src/we_pbe.c @@ -19,11 +19,115 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif + #include #ifdef WE_HAVE_PBE #ifndef NO_PWDBASED +#if defined(_WIN32) +#include +#elif defined(WE_HAVE_DLADDR) +#include +#if defined(WE_HAVE_DL_ITERATE_PHDR) +#include +#include +#endif +#if defined(__APPLE__) +#include +#endif +#endif + +#ifndef WE_NO_DYNAMIC_ENGINE +#if defined(_WIN32) +static HMODULE we_pbe_module = NULL; +#elif defined(WE_HAVE_DLADDR) +static void *we_pbe_module = NULL; +#endif +#endif + +#if defined(WE_HAVE_DL_ITERATE_PHDR) && defined(WE_HAVE_DLADDR) && \ + !defined(WE_NO_DYNAMIC_ENGINE) +static int we_pbe_in_executable(struct dl_phdr_info *info, size_t size, + void *address) +{ + uintptr_t target = (uintptr_t)address; + uintptr_t start; + unsigned int i; + + (void)size; + + /* The first object is the executable, even when its name is nonempty. */ + for (i = 0; i < info->dlpi_phnum; i++) { + if (info->dlpi_phdr[i].p_type == PT_LOAD) { + start = (uintptr_t)info->dlpi_addr + + (uintptr_t)info->dlpi_phdr[i].p_vaddr; + if ((target >= start) && + (target - start < info->dlpi_phdr[i].p_memsz)) { + return 1; + } + } + } + return 2; +} +#endif + +static int we_pin_pbe_module(void) +{ + int ret = 1; + +#ifndef WE_NO_DYNAMIC_ENGINE +#if defined(_WIN32) + if ((we_pbe_module == NULL) && + (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + (LPCSTR)(const void *)&we_pbe_module, + &we_pbe_module) == 0)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PBE, "Failed to pin PBE module"); + ret = 0; + } +#elif defined(WE_HAVE_DLADDR) + if (we_pbe_module == NULL) { + Dl_info info; + +#if defined(WE_HAVE_DL_ITERATE_PHDR) + if (dl_iterate_phdr(we_pbe_in_executable, &we_pbe_module) == 1) { + /* The executable already has process lifetime. */ + ret = 1; + } + else +#endif + if ((dladdr((const void *)&we_pbe_module, &info) == 0) || + (info.dli_fname == NULL)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PBE, "Failed to locate PBE module"); + ret = 0; + } +#if defined(__APPLE__) + else if ((info.dli_fbase != NULL) && + (((const struct mach_header *)info.dli_fbase)->filetype == + MH_EXECUTE)) { + ret = 1; + } +#endif + else { + we_pbe_module = dlopen(info.dli_fname, RTLD_NOW | RTLD_LOCAL); + if (we_pbe_module == NULL) { + WOLFENGINE_ERROR_MSG(WE_LOG_PBE, "Failed to pin PBE module"); + ret = 0; + } + } + } +#else + WOLFENGINE_ERROR_MSG(WE_LOG_PBE, "PBE module pinning is unavailable"); + ret = 0; +#endif +#endif /* !WE_NO_DYNAMIC_ENGINE */ + + return ret; +} + /** * Convert the OpenSSL HMAC NID to a wolfCrypt hash type. * @@ -109,6 +213,9 @@ static int we_pbkdf2_keygen(EVP_CIPHER_CTX *ctx, const char *passwd, int sLen; int hashType; + if (we_pbe_keygen_ready() == 0) + return 0; + /* Cipher already set. */ (void)cipher; /* Digest comes from BER encoded parameters. */ @@ -131,11 +238,19 @@ static int we_pbkdf2_keygen(EVP_CIPHER_CTX *ctx, const char *passwd, #if OPENSSL_VERSION_NUMBER >= 0x10100000L kdf = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBKDF2PARAM), param); #else - const unsigned char *pBuf = param->value.sequence->data; - int pLen = param->value.sequence->length; - kdf = d2i_PBKDF2PARAM(NULL, &pBuf, pLen); + if ((param == NULL) || (param->type != V_ASN1_SEQUENCE) || + (param->value.sequence == NULL)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PBE, "Invalid PBKDF2 parameters"); + ret = 0; + } + else { + const unsigned char *pBuf = param->value.sequence->data; + int pLen = param->value.sequence->length; + + kdf = d2i_PBKDF2PARAM(NULL, &pBuf, pLen); + } #endif /* OPENSSL_VERSION_NUMBER >= 0x10100000L */ - if (kdf == NULL) { + if ((ret == 1) && (kdf == NULL)) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PBE, "ASN1_TYPE_unpack_sequence", kdf); ret = 0; @@ -299,6 +414,9 @@ static int we_pbe_keyivgen(EVP_CIPHER_CTX *ctx, const char *passwd, unsigned char *uniPass = NULL; int uniLen; + if (we_pbe_keygen_ready() == 0) + return 0; + WOLFENGINE_ENTER(WE_LOG_PBE, "we_pbe_keyivgen"); WOLFENGINE_MSG_VERBOSE(WE_LOG_PBE, "ARGS [ctx = %p, passwd = %p, " "passwdLen = %d, param = %p, cipher = %p, md = %p, en_de = %d]", ctx, @@ -429,6 +547,9 @@ static int we_pbes2_keyivgen(EVP_CIPHER_CTX *ctx, const char *passwd, /* Cipher ingored in favour of PBES2 parameters. */ (void)c; + if (we_pbe_keygen_ready() == 0) + return 0; + WOLFENGINE_ENTER(WE_LOG_PBE, "we_pbes2_keyivgen"); WOLFENGINE_MSG_VERBOSE(WE_LOG_PBE, "ARGS [ctx = %p, passwd = %p, " "passwdLen = %d, param = %p, c = %p, md = %p, en_de = %d]", ctx, passwd, @@ -507,25 +628,51 @@ static int we_pbes2_keyivgen(EVP_CIPHER_CTX *ctx, const char *passwd, return ret; } #endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */ + +static int we_pbe_callback_matches(int type, int nid, EVP_PBE_KEYGEN *keygen) +{ + int cipherNid; + int digestNid; + EVP_PBE_KEYGEN *registered = NULL; + + return (EVP_PBE_find(type, nid, &cipherNid, &digestNid, ®istered) == 1) && + (registered == keygen); +} #endif /* !NO_PWDBASED */ /** - * Set the PBE functions to lookup for PBE, PBES2 and PKBDF2. + * Reserve the lifetime of PBE callbacks without registering them. * * @returns 1 on success and 0 on failure. */ +int we_prepare_pbe_keygen(void) +{ +#ifndef NO_PWDBASED + return we_pin_pbe_module(); +#else + return 1; +#endif +} + int we_init_pbe_keygen(void) { #ifndef NO_PWDBASED int ret; - ret = EVP_PBE_alg_add_type(EVP_PBE_TYPE_OUTER, NID_id_pbkdf2, -1, -1, - we_pbkdf2_keygen); - if (ret != 1) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PBE, "EVP_PBE_alg_add_type", ret); + ret = we_prepare_pbe_keygen(); + if ((ret == 1) && !we_pbe_callback_matches(EVP_PBE_TYPE_OUTER, + NID_id_pbkdf2, + we_pbkdf2_keygen)) { + ret = EVP_PBE_alg_add_type(EVP_PBE_TYPE_OUTER, NID_id_pbkdf2, -1, -1, + we_pbkdf2_keygen); + if (ret != 1) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PBE, "EVP_PBE_alg_add_type", ret); + } } #if OPENSSL_VERSION_NUMBER >= 0x10100000L - if (ret == 1) { + if ((ret == 1) && !we_pbe_callback_matches(EVP_PBE_TYPE_KDF, + NID_id_pbkdf2, + we_pbkdf2_keygen)) { /* Let PKCS5_v2_PBE_keyivgen look up the KDF function. */ ret = EVP_PBE_alg_add_type(EVP_PBE_TYPE_KDF, NID_id_pbkdf2, -1, -1, we_pbkdf2_keygen); @@ -534,7 +681,9 @@ int we_init_pbe_keygen(void) } } #else - if (ret == 1) { + if ((ret == 1) && !we_pbe_callback_matches(EVP_PBE_TYPE_OUTER, + NID_pbes2, + we_pbes2_keyivgen)) { /* PKCS5_v2_PBE_keyivgen doesn't look up the KDF function. */ ret = EVP_PBE_alg_add_type(EVP_PBE_TYPE_OUTER, NID_pbes2, -1, -1, we_pbes2_keyivgen); @@ -543,7 +692,9 @@ int we_init_pbe_keygen(void) } } #endif /* OPENSSL_VERSION_NUMBER >= 0x10100000L */ - if (ret == 1) { + if ((ret == 1) && !we_pbe_callback_matches(EVP_PBE_TYPE_OUTER, + NID_pbe_WithSHA1And3_Key_TripleDES_CBC, + we_pbe_keyivgen)) { ret = EVP_PBE_alg_add_type(EVP_PBE_TYPE_OUTER, NID_pbe_WithSHA1And3_Key_TripleDES_CBC, NID_des_ede3_cbc, NID_sha1, we_pbe_keyivgen); @@ -551,7 +702,6 @@ int we_init_pbe_keygen(void) WOLFENGINE_ERROR_FUNC(WE_LOG_PBE, "EVP_PBE_alg_add_type", ret); } } - return ret; #else WOLFENGINE_MSG(WE_LOG_PBE, "wolfCrypt does not support PBKDF"); diff --git a/src/we_random.c b/src/we_random.c index d372c7b5..a74efc35 100644 --- a/src/we_random.c +++ b/src/we_random.c @@ -33,6 +33,24 @@ extern int wc_RNG_DRBG_Reseed(WC_RNG* rng, const byte* seed, word32 seedSz); unsigned char we_seed[WC_SHA256_DIGEST_SIZE] = {0,}; /* Have added to global seed. */ int haveSeed = 0; +#if !defined(WE_SINGLE_THREADED) && defined(WOLFSSL_ATOMIC_OPS) +/* Tickets for serializing access to supplemental seed state. */ +static wolfSSL_Atomic_Int we_seedLockNext = 0; +static wolfSSL_Atomic_Int we_seedLockServing = 0; + +static void we_rand_lock_seed_state(void) +{ + int ticket = wolfSSL_Atomic_Int_FetchAdd(&we_seedLockNext, 1); + + while (wolfSSL_Atomic_Int_FetchAdd(&we_seedLockServing, 0) != ticket) { + } +} + +static void we_rand_unlock_seed_state(void) +{ + wolfSSL_Atomic_Int_FetchAdd(&we_seedLockServing, 1); +} +#endif #endif #ifndef WE_STATIC_WOLFSSL @@ -53,7 +71,7 @@ static int we_rand_mix_seed(unsigned char* buf, int num, int ret = 1; int rc; wc_Sha256 sha256; - unsigned char seedHash[WC_SHA256_DIGEST_SIZE]; + unsigned char seedHash[WC_SHA256_DIGEST_SIZE] = {0,}; unsigned char hash[WC_SHA256_DIGEST_SIZE] = {0,}; int i; int j; @@ -140,6 +158,9 @@ static int we_rand_mix_seed(unsigned char* buf, int num, wc_Sha256Free(&sha256); } + OPENSSL_cleanse(seedHash, sizeof(seedHash)); + OPENSSL_cleanse(hash, sizeof(hash)); + WOLFENGINE_LEAVE(WE_LOG_RNG, "we_rand_mix_seed", ret); return ret; @@ -184,10 +205,24 @@ static int we_rand_seed(const void *buf, int num) ret = 0; } #else + #if !defined(WE_SINGLE_THREADED) && defined(WOLFSSL_ATOMIC_OPS) + we_rand_lock_seed_state(); + #endif /* Mix the seed into the global seed. */ - (void)we_rand_mix_seed(we_seed, sizeof(we_seed), + ret = we_rand_mix_seed(we_seed, sizeof(we_seed), (const unsigned char*)buf, num); - haveSeed = 1; + if (ret == 1) { + haveSeed = 1; + } + else { + OPENSSL_cleanse(we_seed, sizeof(we_seed)); + haveSeed = 0; + WOLFENGINE_ERROR_MSG(WE_LOG_RNG, + "we_rand_mix_seed failed"); + } + #if !defined(WE_SINGLE_THREADED) && defined(WOLFSSL_ATOMIC_OPS) + we_rand_unlock_seed_state(); + #endif #endif #ifndef WE_SINGLE_THREADED wc_UnLockMutex(we_rng_mutex); @@ -203,10 +238,53 @@ static int we_rand_seed(const void *buf, int num) #endif } +#ifndef WE_STATIC_WOLFSSL +/** + * Clear the supplemental seed state. + * + * OpenSSL can invoke the RAND cleanup callback after destroying the engine, + * so supplemental seed state uses synchronization independent of the + * engine-owned RNG mutex when atomic operations are available. + */ +void we_rand_clear_seed(void) +{ +#if !defined(WE_SINGLE_THREADED) && defined(WOLFSSL_ATOMIC_OPS) + we_rand_lock_seed_state(); +#elif !defined(WE_SINGLE_THREADED) + int locked = 0; + int rc; + + if (we_rng_mutex_is_initialized()) { + rc = wc_LockMutex(we_rng_mutex); + if (rc != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_RNG, "wc_LockMutex", rc); + return; + } + else { + locked = 1; + } + } +#endif + + OPENSSL_cleanse(we_seed, sizeof(we_seed)); + haveSeed = 0; + +#if !defined(WE_SINGLE_THREADED) && defined(WOLFSSL_ATOMIC_OPS) + we_rand_unlock_seed_state(); +#elif !defined(WE_SINGLE_THREADED) + if (locked) { + wc_UnLockMutex(we_rng_mutex); + } +#endif +} +#endif + static void we_rand_cleanup(void) { - /* Global random cleanup done in internal.c: we_final_random(). */ WOLFENGINE_ENTER(WE_LOG_RNG, "we_rand_cleanup"); +#ifndef WE_STATIC_WOLFSSL + we_rand_clear_seed(); +#endif WOLFENGINE_LEAVE(WE_LOG_RNG, "we_rand_cleanup", 1); } @@ -227,7 +305,7 @@ static int we_rand_add(const void *buf, int num, double entropy) WOLFENGINE_ENTER(WE_LOG_RNG, "we_rand_add"); WOLFENGINE_MSG_VERBOSE(WE_LOG_RNG, "ARGS [buf = %p, num = %d, " - "entropy = %d]", buf, num, entropy); + "entropy = %f]", buf, num, entropy); /* Call seed implementation - entropy not used. */ #if OPENSSL_VERSION_NUMBER < 0x10100000L @@ -386,6 +464,9 @@ static int we_rand_bytes(unsigned char *buf, int num) ret = 0; } #ifndef WE_STATIC_WOLFSSL + #if !defined(WE_SINGLE_THREADED) && defined(WOLFSSL_ATOMIC_OPS) + we_rand_lock_seed_state(); + #endif /* Mix global seed if RAND_add() or RAND_seed() has been called. */ if (ret == 1 && haveSeed) { ret = we_rand_mix_seed(buf, num, we_seed, sizeof(we_seed)); @@ -394,6 +475,9 @@ static int we_rand_bytes(unsigned char *buf, int num) "global seed failed"); } } + #if !defined(WE_SINGLE_THREADED) && defined(WOLFSSL_ATOMIC_OPS) + we_rand_unlock_seed_state(); + #endif /* Mix in weak entropy. */ if (ret == 1) { ret = we_rand_add_weak_entropy(buf, num); @@ -422,11 +506,12 @@ static int we_rand_bytes(unsigned char *buf, int num) */ static int we_rand_status(void) { + int ret = we_rng_is_initialized(); + WOLFENGINE_ENTER(WE_LOG_RNG, "we_rand_status"); - WOLFENGINE_LEAVE(WE_LOG_RNG, "we_rand_status", 1); + WOLFENGINE_LEAVE(WE_LOG_RNG, "we_rand_status", ret); - /* Always have enough entropy. */ - return 1; + return ret; } /** diff --git a/src/we_rsa.c b/src/we_rsa.c index 2768a56e..21bf7999 100644 --- a/src/we_rsa.c +++ b/src/we_rsa.c @@ -67,6 +67,10 @@ typedef struct we_Rsa int bits; /** Length of salt to use with PSS. */ int saltLen; + /** Owned OAEP label, transferred by the EVP control. */ + unsigned char *oaepLabel; + /** Length of the OAEP label. */ + int oaepLabelLen; /** Indicates private key has been set into wolfSSL structure. */ unsigned int privKeySet:1; /** Indicates public key has been set into wolfSSL structure. */ @@ -75,6 +79,28 @@ typedef struct we_Rsa unsigned int mdSet:1; } we_Rsa; +static unsigned char *we_rsa_oaep_label_alloc(int length) +{ + if (length <= 0) { + return NULL; + } + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + return (unsigned char *)CRYPTO_malloc((size_t)length, __FILE__, __LINE__); +#else + return (unsigned char *)CRYPTO_malloc(length, __FILE__, __LINE__); +#endif +} + +static void we_rsa_oaep_label_free(void *label) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + CRYPTO_free(label, __FILE__, __LINE__); +#else + CRYPTO_free(label); +#endif +} + /** RSA direct method - RSA using wolfSSL for the implementation. */ RSA_METHOD *we_rsa_method = NULL; @@ -194,14 +220,14 @@ static int we_pss_salt_len_to_wc(int saltLen, const EVP_MD *md, RsaKey *key, if (saltLen == RSA_PSS_SALTLEN_DIGEST) { saltLen = RSA_PSS_SALT_LEN_DEFAULT; } - if (saltLen == RSA_PSS_SALTLEN_MAX) { + else if (saltLen == RSA_PSS_SALTLEN_MAX) { #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER saltLen = EVP_MD_size(md); #else saltLen = RSA_PSS_SALT_LEN_DISCOVER; #endif } - if (saltLen == RSA_PSS_SALTLEN_AUTO) { + else if (saltLen == RSA_PSS_SALTLEN_AUTO) { #ifndef WOLFSSL_PSS_LONG_SALT saltLen = EVP_MD_size(md); #else @@ -450,7 +476,7 @@ static int we_rsa_set_public_key(RSA *rsaKey, we_Rsa *engineRsa) /* DER encoded public key with OpenSSL. */ pubDerLen = i2d_RSAPublicKey(rsaKey, &pubDer); - if (pubDerLen == 0) { + if (pubDerLen <= 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "i2d_RSAPublicKey", pubDerLen); ret = 0; } @@ -539,8 +565,8 @@ static int we_rsa_set_public_key_from_ctx(EVP_PKEY_CTX* ctx, we_Rsa* engineRsa) /** * Set the private key in a we_Rsa structure. * - * @param ctx [in] Public key context of operation. - * @param rsa [in] RSA structure to hold private key. + * @param rsaKey [in] OpenSSL RSA private key. + * @param engineRsa [out] wolfEngine RSA object to hold key. * @returns 1 on success and 0 on failure. */ static int we_rsa_set_private_key(RSA *rsaKey, we_Rsa *engineRsa) @@ -557,9 +583,10 @@ static int we_rsa_set_private_key(RSA *rsaKey, we_Rsa *engineRsa) /* DER encoded private key with OpenSSL. */ privDerLen = i2d_RSAPrivateKey(rsaKey, &privDer); - if (privDerLen == 0) { + if (privDerLen <= 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "i2d_RSAPrivateKey", privDerLen); ret = 0; + privDerLen = 0; } if (ret == 1) { @@ -767,7 +794,8 @@ static int we_rsa_pub_enc_int(size_t fromLen, const unsigned char *from, ret = wc_RsaPublicEncrypt_ex(from, (word32)fromLen, to, (word32)toLen, &rsa->key, rng, WC_RSA_OAEP_PAD, we_nid_to_wc_hash_type(EVP_MD_type(rsa->md)), - we_mgf_from_hash(EVP_MD_type(mdMGF1)), NULL, 0); + we_mgf_from_hash(EVP_MD_type(mdMGF1)), rsa->oaepLabel, + (word32)rsa->oaepLabelLen); if (ret < 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_RsaPublicEncrypt_ex", ret); @@ -896,13 +924,12 @@ static int we_rsa_priv_dec_int(size_t fromLen, const unsigned char *from, "toLen = %zu, to = %p, rsa = %p]", fromLen, from, toLen, to, rsa); - #if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) +#if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) ret = wc_LockMutex(we_rng_mutex); if (ret != 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_LockMutex", ret); - ret = -1; + return -1; } - else #endif { switch (rsa->padMode) { @@ -940,7 +967,8 @@ static int we_rsa_priv_dec_int(size_t fromLen, const unsigned char *from, ret = wc_RsaPrivateDecrypt_ex(from, (word32)fromLen, to, (word32)toLen, &rsa->key, WC_RSA_OAEP_PAD, we_nid_to_wc_hash_type(EVP_MD_type(rsa->md)), - we_mgf_from_hash(EVP_MD_type(mdMGF1)), NULL, 0); + we_mgf_from_hash(EVP_MD_type(mdMGF1)), rsa->oaepLabel, + (word32)rsa->oaepLabelLen); PRIVATE_KEY_LOCK(); if (ret < 0) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, @@ -1135,9 +1163,6 @@ static int we_rsa_priv_enc_int(size_t fromLen, const unsigned char *from, /* Convert salt length into wolfCrypt value. */ int wc_saltLen = we_pss_salt_len_to_wc(rsa->saltLen, rsa->md, &rsa->key, 1); - if (wc_saltLen >= 0) { - rsa->saltLen = wc_saltLen; - } /* When MGF1 digest is not specified, use signing digest. */ mdMGF1 = rsa->mdMGF1 != NULL ? rsa->mdMGF1 : rsa->md; PRIVATE_KEY_UNLOCK(); @@ -1157,10 +1182,16 @@ static int we_rsa_priv_enc_int(size_t fromLen, const unsigned char *from, WOLFENGINE_MSG(WE_LOG_PK, "padMode: RSA_X931_PADDING"); paddedSz = wc_RsaEncryptSize(&rsa->key); if (paddedSz <= 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_RsaEncryptSize", ret); + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_RsaEncryptSize", + paddedSz); + ret = -1; + } + else if (toLen < (size_t)paddedSz) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Output buffer too small"); ret = -1; } else { + tLen = (unsigned int)paddedSz; padded = (unsigned char *)OPENSSL_malloc(paddedSz); if (padded == NULL) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "OPENSSL_malloc", @@ -1198,7 +1229,7 @@ static int we_rsa_priv_enc_int(size_t fromLen, const unsigned char *from, ret = -1; } else { - rc = mp_read_unsigned_bin(&toMp, to, (int)toLen); + rc = mp_read_unsigned_bin(&toMp, to, (int)tLen); if (rc != MP_OKAY) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "mp_read_unsigned_bin", rc); @@ -1215,10 +1246,11 @@ static int we_rsa_priv_enc_int(size_t fromLen, const unsigned char *from, ret = -1; } else if (mp_cmp(&toMp, &nMinusTo) == MP_GT) { - rc = mp_to_unsigned_bin(&nMinusTo, to); + rc = mp_to_unsigned_bin_len(&nMinusTo, to, + (int)tLen); if (rc != MP_OKAY) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, - "mp_to_unsigned_bin", rc); + "mp_to_unsigned_bin_len", rc); ret = -1; } } @@ -1309,13 +1341,6 @@ static int we_rsa_priv_enc(int fromLen, const unsigned char *from, /* Store the padding mode (PKEY variant has it set) and private * encrypt. */ engineRsa->padMode = padding; - #if OPENSSL_VERSION_NUMBER >= 0x10101000L - if ((padding == RSA_PKCS1_PADDING) && engineRsa->mdSet && - (EVP_MD_size(engineRsa->md) != fromLen)) { - WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Digest length invalid"); - ret = -1; - } - #endif } if (ret == 1) { /* Output size is always the length of the prime. */ @@ -1347,6 +1372,9 @@ static int we_rsa_pub_dec_int(size_t fromLen, const unsigned char *from, int ret = 1; unsigned int tLen = (unsigned int)toLen; const EVP_MD *mdMGF1; +#if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) + int lockRet; +#endif #ifndef WE_RSA_USE_GLOBAL_RNG WC_RNG *rng = &rsa->rng; #else @@ -1357,6 +1385,7 @@ static int we_rsa_pub_dec_int(size_t fromLen, const unsigned char *from, unsigned char* unpadded = NULL; mp_int toMp; mp_int nMinusTo; + int outputSz; int rc; #endif @@ -1386,8 +1415,9 @@ static int we_rsa_pub_dec_int(size_t fromLen, const unsigned char *from, case RSA_NO_PADDING: WOLFENGINE_MSG(WE_LOG_PK, "padMode: RSA_NO_PADDING"); #if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) - if (wc_LockMutex(we_rng_mutex) != 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_LockMutex", ret); + lockRet = wc_LockMutex(we_rng_mutex); + if (lockRet != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_LockMutex", lockRet); ret = -1; } else @@ -1438,15 +1468,46 @@ static int we_rsa_pub_dec_int(size_t fromLen, const unsigned char *from, #ifdef WE_HAVE_RSA_X931 case RSA_X931_PADDING: WOLFENGINE_MSG(WE_LOG_PK, "padMode: RSA_X931_PADDING"); - PRIVATE_KEY_UNLOCK(); - ret = wc_RsaDirect((byte*)from, (unsigned int)fromLen, to, - &tLen, &rsa->key, RSA_PUBLIC_DECRYPT, rng); - PRIVATE_KEY_LOCK(); - if (ret < 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_RsaDirect", ret); + outputSz = wc_RsaEncryptSize(&rsa->key); + if (outputSz <= 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_RsaEncryptSize", + outputSz); + ret = -1; + } + else if (toLen < (size_t)outputSz) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Output buffer too small"); ret = -1; } else { + tLen = (unsigned int)outputSz; + #if defined(WE_RSA_USE_GLOBAL_RNG) && \ + !defined(WE_SINGLE_THREADED) + lockRet = wc_LockMutex(we_rng_mutex); + if (lockRet != 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_LockMutex", + lockRet); + ret = -1; + } + else + #endif + { + PRIVATE_KEY_UNLOCK(); + ret = wc_RsaDirect((byte*)from, + (unsigned int)fromLen, to, &tLen, &rsa->key, + RSA_PUBLIC_DECRYPT, rng); + PRIVATE_KEY_LOCK(); + if (ret < 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "wc_RsaDirect", + ret); + ret = -1; + } + #if defined(WE_RSA_USE_GLOBAL_RNG) && \ + !defined(WE_SINGLE_THREADED) + wc_UnLockMutex(we_rng_mutex); + #endif + } + } + if (ret != -1) { /* * X9.31 specifies, "If e is odd, then * - If RR = 12 mod 16, then IR = RR ; @@ -1455,19 +1516,19 @@ static int we_rsa_pub_dec_int(size_t fromLen, const unsigned char *from, * step. Taking "to" mod 16 is the same as just checking the * lower 4 bits of "to." */ - if ((to[toLen-1] & 0x0F) != 12) { + if ((to[tLen-1] & 0x0F) != 12) { rc = mp_init_multi(&toMp, &nMinusTo, NULL, NULL, NULL, NULL); if (rc != MP_OKAY) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "mp_init_multi", - ret); + rc); ret = -1; } else { - rc = mp_read_unsigned_bin(&toMp, to, (int)toLen); + rc = mp_read_unsigned_bin(&toMp, to, (int)tLen); if (rc != MP_OKAY) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, - "mp_read_unsigned_bin", ret); + "mp_read_unsigned_bin", rc); ret = -1; } else { @@ -1477,10 +1538,11 @@ static int we_rsa_pub_dec_int(size_t fromLen, const unsigned char *from, ret = -1; } else { - rc = mp_to_unsigned_bin(&nMinusTo, to); + rc = mp_to_unsigned_bin_len(&nMinusTo, to, + (int)tLen); if (rc != MP_OKAY) { WOLFENGINE_ERROR_FUNC(WE_LOG_PK, - "mp_to_unsigned_bin", rc); + "mp_to_unsigned_bin_len", rc); ret = -1; } } @@ -1895,6 +1957,7 @@ static int we_rsa_pkey_init(EVP_PKEY_CTX *ctx) wc_FreeRng(&rsa->rng); #endif wc_FreeRsaKey(&rsa->key); + we_rsa_oaep_label_free(rsa->oaepLabel); OPENSSL_free(rsa); } @@ -1924,6 +1987,7 @@ static void we_rsa_pkey_cleanup(EVP_PKEY_CTX *ctx) wc_FreeRng(&rsa->rng); #endif wc_FreeRsaKey(&rsa->key); + we_rsa_oaep_label_free(rsa->oaepLabel); OPENSSL_free(rsa); } @@ -1983,10 +2047,30 @@ static int we_rsa_pkey_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) rsaDst->pubExp = rsaSrc->pubExp; rsaDst->bits = rsaSrc->bits; rsaDst->saltLen = rsaSrc->saltLen; + if (rsaSrc->oaepLabel != NULL) { + rsaDst->oaepLabel = we_rsa_oaep_label_alloc( + rsaSrc->oaepLabelLen); + if (rsaDst->oaepLabel == NULL) { + WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "CRYPTO_malloc", + rsaDst->oaepLabel); + ret = 0; + } + else { + if (rsaSrc->oaepLabelLen > 0) { + XMEMCPY(rsaDst->oaepLabel, rsaSrc->oaepLabel, + (size_t)rsaSrc->oaepLabelLen); + } + rsaDst->oaepLabelLen = rsaSrc->oaepLabelLen; + } + } /* Don't copy wolfSSL RSA key. * No public key or private key set. */ } + if (ret != 1) { + we_rsa_pkey_cleanup(dst); + } + WOLFENGINE_LEAVE(WE_LOG_PK, "we_rsa_pkey_copy", ret); return ret; @@ -2061,7 +2145,8 @@ static int we_rsa_pkey_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) * @param type [in] Type of operation to perform. * @param num [in] Integer parameter. * @param ptr [in] Pointer parameter. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_rsa_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) { @@ -2203,7 +2288,8 @@ static int we_rsa_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) ret = 0; } if (ret == 1) { - rsa->pubExp = (int)e; + rsa->pubExp = e; + BN_free(bn); } break; case EVP_PKEY_CTRL_RSA_PSS_SALTLEN: @@ -2314,14 +2400,36 @@ static int we_rsa_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) break; case EVP_PKEY_CTRL_RSA_OAEP_LABEL: WOLFENGINE_MSG(WE_LOG_PK, "type: EVP_PKEY_CTRL_RSA_OAEP_LABEL"); - /* Not needed - seed created internally. */ + if (rsa->padMode != RSA_PKCS1_OAEP_PADDING || num < 0) { + ret = 0; + } + else { + unsigned char *label = (unsigned char *)ptr; + + if (label != rsa->oaepLabel) { + we_rsa_oaep_label_free(rsa->oaepLabel); + } + if (label == NULL || num == 0) { + we_rsa_oaep_label_free(label); + rsa->oaepLabel = NULL; + rsa->oaepLabelLen = 0; + } + else { + rsa->oaepLabel = label; + rsa->oaepLabelLen = num; + } + } break; case EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL: WOLFENGINE_MSG(WE_LOG_PK, "type: EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL"); - /* Not needed - seed created internally. */ - *(unsigned char **)ptr = NULL; - ret = 0; + if (rsa->padMode != RSA_PKCS1_OAEP_PADDING || ptr == NULL) { + ret = 0; + } + else { + *(unsigned char **)ptr = rsa->oaepLabel; + ret = rsa->oaepLabelLen; + } break; default: @@ -2329,7 +2437,7 @@ static int we_rsa_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; break; } } @@ -2352,7 +2460,7 @@ static int we_rsa_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) * @param ctx [in] Public key context of operation. * @param type [in] Type of operation to perform. * @param value [in] Control string dependent value. - * @returns 1 on success and 0 on failure. + * @returns 1 on success or a non-positive OpenSSL control error code. */ static int we_rsa_pkey_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) @@ -2496,12 +2604,12 @@ static int we_rsa_pkey_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, rsa->pubExp = e; } } - else { + else if (ret == 1) { /* Unsupported string. */ XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl string: %s", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; } return ret; @@ -2528,8 +2636,16 @@ static int we_der_encode_digest(const EVP_MD *md, const unsigned char *digest, "digestLen = %zu, encodedDigest = %p]", md, digest, digestLen, encodedDigest); + if ((md == NULL) || (digest == NULL) || (encodedDigest == NULL) || + (EVP_MD_size(md) <= 0) || + (digestLen != (size_t)EVP_MD_size(md)) || + (digestLen > MAX_DER_DIGEST_SZ - 20)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Digest length invalid"); + ret = 0; + } + /* Allocate a buffer if not passed in. */ - if (*encodedDigest == NULL) { + if ((ret == 1) && (*encodedDigest == NULL)) { *encodedDigest = (unsigned char *)OPENSSL_malloc(MAX_DER_DIGEST_SZ); if (*encodedDigest == NULL) { WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_PK, "OPENSSL_malloc", @@ -2608,7 +2724,7 @@ static int we_rsa_pkey_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, ret = 0; } - if (rsa->md != NULL && + if ((ret == 1) && (rsa->md != NULL) && we_check_rsa_signing_md(EVP_MD_type(rsa->md)) != 1) { ret = 0; } @@ -2661,13 +2777,11 @@ static int we_rsa_pkey_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, } if ((ret == 1) && (sig != NULL)) { - #if OPENSSL_VERSION_NUMBER >= 0x10101000L if ((rsa->md != NULL) && (rsa->padMode == RSA_PKCS1_PADDING) && ((size_t)EVP_MD_size(rsa->md) != tbsLen)) { WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Digest length invalid"); ret = -1; } - #endif if ((ret == 1) && (rsa->md != NULL) && (rsa->padMode == RSA_PKCS1_PADDING)) { /* In this case, OpenSSL expects a proper PKCS #1 v1.5 @@ -2753,7 +2867,16 @@ static int we_rsa_pkey_verify_recover(EVP_PKEY_CTX *ctx, unsigned char* out, { int ret = 1; int rc; + int keySize; + int mdSize; + int encodedSize; + int prefixSize; we_Rsa *rsa = NULL; + unsigned char *decoded = NULL; + unsigned char *encoded = NULL; + const unsigned char *digest = NULL; + unsigned char emptyDigest[EVP_MAX_MD_SIZE]; + unsigned char encodedDigest[MAX_DER_DIGEST_SZ]; WOLFENGINE_ENTER(WE_LOG_PK, "we_rsa_pkey_verify_recover"); WOLFENGINE_MSG_VERBOSE(WE_LOG_PK, "ARGS [ctx = %p, out = %p, outSz = %p, " @@ -2782,15 +2905,82 @@ static int we_rsa_pkey_verify_recover(EVP_PKEY_CTX *ctx, unsigned char* out, } } else { - /* Unpad and public decrypt. */ - rc = we_rsa_pub_dec_int(inSz, in, *outSz, out, rsa); - if (rc < 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "we_rsa_pub_dec_int", rc); - ret = 0; + /* Digest recovery needs room for the encoded form before it is + * reduced to the caller's digest-sized buffer. */ + if (rsa->md != NULL && (rsa->padMode == RSA_PKCS1_PADDING +#ifdef WE_HAVE_RSA_X931 + || rsa->padMode == RSA_X931_PADDING +#endif + )) { + keySize = wc_RsaEncryptSize(&rsa->key); + if (keySize <= 0) { + ret = 0; + } + else { + decoded = (unsigned char *)OPENSSL_malloc((size_t)keySize); + if (decoded == NULL) { + ret = 0; + } + } } - else { - *outSz = rc; + if (ret == 1) { + rc = we_rsa_pub_dec_int(inSz, in, + decoded != NULL ? (size_t)keySize : *outSz, + decoded != NULL ? decoded : out, rsa); + if (rc < 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "we_rsa_pub_dec_int", rc); + ret = 0; + } } + if (ret == 1 && decoded != NULL) { + mdSize = EVP_MD_size(rsa->md); + if (mdSize <= 0 || mdSize > EVP_MAX_MD_SIZE) { + ret = 0; + } + else if (rsa->padMode == RSA_PKCS1_PADDING) { + XMEMSET(emptyDigest, 0, (size_t)mdSize); + encoded = encodedDigest; + encodedSize = we_der_encode_digest(rsa->md, emptyDigest, + (size_t)mdSize, &encoded); + prefixSize = encodedSize - mdSize; + if (encodedSize <= 0 || prefixSize < 0 || + rc != encodedSize || + XMEMCMP(decoded, encodedDigest, + (size_t)prefixSize) != 0) { + ret = 0; + } + else { + digest = decoded + prefixSize; + rc = mdSize; + } + } +#ifdef WE_HAVE_RSA_X931 + else if (rsa->padMode == RSA_X931_PADDING) { + if (we_rsa_get_x931_hash_code(EVP_MD_type(rsa->md)) == 0 || + rc != mdSize + 1 || + decoded[mdSize] != + we_rsa_get_x931_hash_code(EVP_MD_type(rsa->md))) { + ret = 0; + } + else { + digest = decoded; + rc = mdSize; + } + } +#endif + if (ret == 1) { + if (*outSz < (size_t)rc) { + ret = 0; + } + else { + XMEMCPY(out, digest, (size_t)rc); + } + } + } + if (ret == 1) { + *outSz = (size_t)rc; + } + OPENSSL_free(decoded); } } @@ -2853,12 +3043,19 @@ static int we_rsa_pkey_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, ret = -1; } if (ret == 1) { - rc = we_rsa_pkey_verify_recover(ctx, decryptedSig, &decLen, sig, - sigLen); - if (rc <= 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "we_rsa_pkey_verify_recover", rc); + if (!rsa->pubKeySet) { + ret = we_rsa_set_public_key_from_ctx(ctx, rsa); + } + } + if (ret == 1) { + rc = we_rsa_pub_dec_int(sigLen, sig, decLen, decryptedSig, rsa); + if (rc < 0) { + WOLFENGINE_ERROR_FUNC(WE_LOG_PK, "we_rsa_pub_dec_int", rc); ret = 0; } + else { + decLen = (size_t)rc; + } } if ((ret == 1) && (rsa->padMode == RSA_PKCS1_PSS_PADDING)) { /* Convert salt length into wolfCrypt value. */ @@ -2961,8 +3158,9 @@ static int we_rsa_pkey_verify(EVP_PKEY_CTX *ctx, const unsigned char *sig, * Encrypt data with a public RSA key. * * @param ctx [in] Public key context of operation. - * @param ciphertext [in] Encrypted data. - * @param cipherLen [in] Length of encrypted data. + * @param ciphertext [out] Buffer to hold encrypted data. + * @param cipherLen [in/out] Buffer size on input, encrypted length on + * output. * @param plaintext [in] Data to be encrypted. * @param plainLen [in] Length of data to be encrypted. * @returns 1 on success and 0 on failure. @@ -3052,8 +3250,8 @@ static int we_rsa_pkey_encrypt(EVP_PKEY_CTX *ctx, unsigned char *ciphertext, * Decrypt ciphertext with a private RSA key. * * @param ctx [in] Private key context of operation. - * @param plaintext [in] Buffer to hold decrypted data. - * NULL indicates length of signature requested. + * @param plaintext [out] Buffer receiving decrypted data, or NULL to + * request the required buffer length. * @param plainLen [in/out] Length of decrypted data. * @param ciphertext [in] Data to be decrypted. * @param cipherLen [in] Length of encrypted data. diff --git a/src/we_tls_prf.c b/src/we_tls_prf.c index 1019b53e..867194a6 100644 --- a/src/we_tls_prf.c +++ b/src/we_tls_prf.c @@ -110,9 +110,8 @@ static void we_tls1_prf_cleanup(EVP_PKEY_CTX *ctx) * Derive the key from the secret and label/seed. * * @param ctx [in] PKEY context. - * @param key [in] Calculated key data. - * @param keySz [in,out] On in, size of key data to calculate in bytes. - * On out, size of key data in bytes. + * @param key [out] Calculated key data. + * @param keySz [in] Size of key data to calculate in bytes. * @returns 1 on success and 0 on failure. */ static int we_tls1_prf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, @@ -140,6 +139,10 @@ static int we_tls1_prf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, WOLFENGINE_ERROR_MSG(WE_LOG_PK, "No secret from app."); ret = 0; } + if ((ret == 1) && (*keySz > UINT32_MAX)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Output size too large"); + ret = 0; + } if ((ret == 1) && (tls1Prf->mdType == NID_md5_sha1)) { /* Calculate key. * Label is included in seed so pass in buffer and 0 length for label. @@ -155,7 +158,8 @@ static int we_tls1_prf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, ret = 0; } } - else if (ret == 1) { + else if ((ret == 1) && ((tls1Prf->mdType == NID_sha256) || + (tls1Prf->mdType == NID_sha384))) { PRIVATE_KEY_UNLOCK(); rc = wc_PRF_TLS(key, (word32)*keySz, tls1Prf->secret, (word32)(tls1Prf->secretSz), (byte*)"", 0, @@ -168,6 +172,10 @@ static int we_tls1_prf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, ret = 0; } } + else if (ret == 1) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Unsupported digest"); + ret = 0; + } WOLFENGINE_LEAVE(WE_LOG_PK, "we_tls1_prf_derive", ret); @@ -186,12 +194,14 @@ static int we_tls1_prf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, * @param type [in] Type of operation to perform. * @param num [in] Integer argument. * @param ptr [in] Pointer argument. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_tls1_prf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) { we_Tls1_Prf *tls1Prf; int ret = 1; + int mdType; char errBuff[WOLFENGINE_MAX_LOG_WIDTH]; WOLFENGINE_ENTER(WE_LOG_PK, "we_tls1_prf_ctrl"); @@ -206,7 +216,15 @@ static int we_tls1_prf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) case EVP_PKEY_CTRL_TLS_MD: WOLFENGINE_MSG(WE_LOG_PK, "type: EVP_PKEY_CTRL_TLS_MD"); /* ptr: EVP md object. */ - tls1Prf->mdType = EVP_MD_type(ptr); + mdType = EVP_MD_type(ptr); + if ((mdType != NID_md5_sha1) && (mdType != NID_sha256) && + (mdType != NID_sha384)) { + WOLFENGINE_ERROR_MSG(WE_LOG_PK, "Unsupported digest"); + ret = 0; + } + else { + tls1Prf->mdType = mdType; + } break; case EVP_PKEY_CTRL_TLS_SECRET: @@ -223,6 +241,8 @@ static int we_tls1_prf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) OPENSSL_clear_free(tls1Prf->secret, tls1Prf->secretSz); } if (ret == 1) { + tls1Prf->secret = NULL; + tls1Prf->secretSz = 0; /* Clear label/seed as this is a new operation. */ OPENSSL_cleanse(tls1Prf->seed, tls1Prf->seedSz); tls1Prf->seedSz = 0; @@ -265,7 +285,7 @@ static int we_tls1_prf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %d", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; break; } @@ -287,7 +307,8 @@ static int we_tls1_prf_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr) * @param ctx [in] PKEY context. * @param type [in] Type of operation to perform. * @param value [in] Pointer argument. - * @returns 1 on success and 0 on failure. + * @returns 1 or a queried value on success, 0 on failure, + * or -2 if the control is unsupported. */ static int we_tls1_prf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) @@ -304,7 +325,6 @@ static int we_tls1_prf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, ret = 0; } else if (XSTRNCMP(type, "md", 3) == 0) { - we_Tls1_Prf *tls1Prf = (we_Tls1_Prf *)EVP_PKEY_CTX_get_data(ctx); const EVP_MD *md = EVP_get_digestbyname(value); /* Cannot get here without initialization succeeding. */ if (md == NULL) { @@ -312,7 +332,7 @@ static int we_tls1_prf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, ret = 0; } else { - tls1Prf->mdType = EVP_MD_type(md); + ret = we_tls1_prf_ctrl(ctx, EVP_PKEY_CTRL_TLS_MD, 0, (void *)md); } } else if (XSTRNCMP(type, "secret", 7) == 0) { @@ -331,7 +351,7 @@ static int we_tls1_prf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, /* Unsupported type. */ XSNPRINTF(errBuff, sizeof(errBuff), "Unsupported ctrl type %s", type); WOLFENGINE_ERROR_MSG(WE_LOG_PK, errBuff); - ret = 0; + ret = -2; } WOLFENGINE_LEAVE(WE_LOG_PK, "we_tls1_prf_ctrl_str", ret); diff --git a/src/we_wolfengine.c b/src/we_wolfengine.c index fbb5c24d..d653e8d1 100644 --- a/src/we_wolfengine.c +++ b/src/we_wolfengine.c @@ -43,23 +43,17 @@ static ENGINE *engine_wolfengine(void) int rc; ENGINE *ret; - WOLFENGINE_ENTER(WE_LOG_ENGINE, "engine_wolfengine"); - /* Known, still-reachable memory leak from openssl internals on 1.0.2 */ ret = ENGINE_new(); if (ret == NULL) { - WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_ENGINE, "ENGINE_new", ret); return NULL; } rc = wolfengine_bind(ret, wolfengine_id); if (rc == 0) { - WOLFENGINE_ERROR_FUNC(WE_LOG_ENGINE, "wolfengine_bind", rc); ENGINE_free(ret); return NULL; } - WOLFENGINE_LEAVE(WE_LOG_ENGINE, "engine_wolfengine", 1); - return ret; } @@ -68,18 +62,18 @@ static ENGINE *engine_wolfengine(void) */ void ENGINE_load_wolfengine(void) { - ENGINE *toadd = engine_wolfengine(); - - WOLFENGINE_ENTER(WE_LOG_ENGINE, "ENGINE_load_wolfengine"); + ENGINE *toadd; + if (we_engine_bind_available() == 0) { + return; + } + toadd = engine_wolfengine(); if (!toadd) return; ENGINE_add(toadd); ENGINE_free(toadd); /* Known, still-reachable memory leak from openssl internals on 1.0.2 */ ERR_clear_error(); - - WOLFENGINE_LEAVE(WE_LOG_ENGINE, "ENGINE_load_wolfengine", 1); } #ifndef WE_NO_DYNAMIC_ENGINE diff --git a/test-openssl-version.sh b/test-openssl-version.sh index b25ad68c..319dc975 100755 --- a/test-openssl-version.sh +++ b/test-openssl-version.sh @@ -135,6 +135,23 @@ do_config() { if [ "$VERBOSE" = "yes" ]; then cat $TMP_FILE fi + + echo -n " dh_alloc.test ... " + LD_LIBRARY_PATH=$OPENSSL_DIR ./test/dh_alloc.test >$TMP_FILE 2>&1 + DH_ALLOC_RESULT=$? + case $DH_ALLOC_RESULT in + 0) echo "PASS" ;; + 77) echo "SKIP" ;; + *) + cat $TMP_FILE + echo "DH allocation test failed for wolfSSL engine" + do_cleanup + exit 1 + ;; + esac + if [ "$VERBOSE" = "yes" ]; then + cat $TMP_FILE + fi } while [ $# -gt 0 ] diff --git a/test/engine_bind.test b/test/engine_bind.test new file mode 100755 index 00000000..82f140a9 --- /dev/null +++ b/test/engine_bind.test @@ -0,0 +1,3 @@ +#!/bin/sh + +exec ./test/unit.test --bind-lifecycle diff --git a/test/include.am b/test/include.am index 4ab850c9..abe96daf 100644 --- a/test/include.am +++ b/test/include.am @@ -4,11 +4,53 @@ TEST_EXTENSIONS=.test TESTS += $(check_PROGRAMS) +TESTS += test/rsa_oaep_allocator.sh +dist_noinst_SCRIPTS += test/rsa_oaep_allocator.sh + +check_PROGRAMS += test/cmac_cleanup.test test/cmac_cleanup_inline.test \ + test/cmac_cleanup_buffered.test +test_cmac_cleanup_test_SOURCES = test/test_cmac_compat.c +test_cmac_cleanup_inline_test_SOURCES = test/test_cmac_compat.c +test_cmac_cleanup_inline_test_CPPFLAGS = $(AM_CPPFLAGS) -DWE_TEST_CMAC_INLINE +test_cmac_cleanup_buffered_test_SOURCES = test/test_cmac_compat.c +test_cmac_cleanup_buffered_test_CPPFLAGS = $(AM_CPPFLAGS) -DWE_TEST_CMAC_BUFFERED check_PROGRAMS += test/unit.test noinst_PROGRAMS += test/unit.test DISTCLEANFILES += test/.libs/unit.test +check_PROGRAMS += test/pbe_lifetime.test +noinst_PROGRAMS += test/pbe_lifetime.test +DISTCLEANFILES += test/.libs/pbe_lifetime.test + +test_pbe_lifetime_test_SOURCES = test/test_pbe_lifetime.c +test_pbe_lifetime_test_LDADD = $(OPENSSL_LIBS) + +check_PROGRAMS += test/engine_lifetime.test +noinst_PROGRAMS += test/engine_lifetime.test +DISTCLEANFILES += test/.libs/engine_lifetime.test + +test_engine_lifetime_test_SOURCES = test/test_engine_lifetime.c +test_engine_lifetime_test_LDADD = $(OPENSSL_LIBS) + +check_PROGRAMS += test/engine_pbe_init.test +noinst_PROGRAMS += test/engine_pbe_init.test +DISTCLEANFILES += test/.libs/engine_pbe_init.test + +test_engine_pbe_init_test_SOURCES = test/test_engine_pbe_init.c +test_engine_pbe_init_test_LDADD = libwolfengine.la + +if BUILD_STATIC_TESTS +check_PROGRAMS += test/pbe_static.test +noinst_PROGRAMS += test/pbe_static.test +DISTCLEANFILES += test/.libs/pbe_static.test + +test_pbe_static_test_SOURCES = test/test_pbe_lifetime.c +test_pbe_static_test_CPPFLAGS = $(AM_CPPFLAGS) -DWE_PBE_STATIC_LINK +test_pbe_static_test_LDFLAGS = $(AM_LDFLAGS) -static +test_pbe_static_test_LDADD = libwolfengine.la +endif + test_unit_test_SOURCES = \ test/test_aestag.c \ test/test_cipher.c \ @@ -19,6 +61,7 @@ test_unit_test_SOURCES = \ test/test_hkdf.c \ test/test_hmac.c \ test/test_logging.c \ + test/test_openssl_bc.c \ test/test_pbe.c \ test/test_pkey.c \ test/test_rand.c \ @@ -27,3 +70,10 @@ test_unit_test_SOURCES = \ test/unit.c test_unit_test_LDADD = libwolfengine.la noinst_HEADERS += test/unit.h + +check_PROGRAMS += test/dh_alloc.test +noinst_PROGRAMS += test/dh_alloc.test +DISTCLEANFILES += test/.libs/dh_alloc.test + +test_dh_alloc_test_SOURCES = test/test_dh_alloc.c +test_dh_alloc_test_LDADD = libwolfengine.la diff --git a/test/rsa_oaep_allocator.sh b/test/rsa_oaep_allocator.sh new file mode 100755 index 00000000..d33afdcc --- /dev/null +++ b/test/rsa_oaep_allocator.sh @@ -0,0 +1,12 @@ +#!/bin/sh + +set -eu + +source_file="${srcdir:-.}/src/we_rsa.c" + +grep -q 'CRYPTO_malloc(' "$source_file" +grep -q 'CRYPTO_free(label' "$source_file" + +if grep -Eq 'OPENSSL_free\((rsa->oaepLabel|label)\)' "$source_file"; then + exit 1 +fi diff --git a/test/test_aestag.c b/test/test_aestag.c index d223cc2c..2e496414 100644 --- a/test/test_aestag.c +++ b/test/test_aestag.c @@ -21,12 +21,16 @@ #include "unit.h" +#include +#include + #ifndef EVP_CCM_TLS_FIXED_IV_LEN #define EVP_CCM_TLS_FIXED_IV_LEN EVP_GCM_TLS_FIXED_IV_LEN #endif #ifndef EVP_CCM_TLS_TAG_LEN #define EVP_CCM_TLS_TAG_LEN EVP_GCM_TLS_TAG_LEN #endif +#define CCM_TAG_DEFAULT_LEN 12 #if defined(WE_HAVE_AESGCM) || defined(WE_HAVE_AESCCM) @@ -91,8 +95,8 @@ static int test_aes_tag_enc(ENGINE *e, const EVP_CIPHER *cipher, err = EVP_EncryptUpdate(ctx, NULL, &encLen, aad + 1, (int)strlen((char *)aad) - 1) != 1; } - if (err == 0 && len > 0) { - /* Update with msg, if len > 0 (not GMAC) */ + if (err == 0 && (len > 0 || ccm)) { + /* CCM authenticates empty messages during the payload update. */ err = EVP_EncryptUpdate(ctx, enc, &encLen, msg, len) != 1; if (encLen != len) { err = 1; @@ -165,9 +169,11 @@ static int test_aes_tag_dec(ENGINE *e, const EVP_CIPHER *cipher, err = 1; } } - if (err == 0 && len > 0) { - /* Not used in GMAC test (len == 0) */ + if (err == 0 && (len > 0 || ccm)) { err = EVP_DecryptUpdate(ctx, dec, &decLen, enc, len) != 1; + if (err == 0 && ccm && len == 0) { + err = decLen != 0; + } } else { /* Reset decLen, represented AAD length above */ decLen = 0; @@ -176,7 +182,7 @@ static int test_aes_tag_dec(ENGINE *e, const EVP_CIPHER *cipher, /* Bug in older versions has tag_set cleared and causes failure. */ if (err == 0) { #else - if (err == 0 && (!ccm || len == 0)) { + if (err == 0 && !ccm) { #endif err = EVP_DecryptFinal_ex(ctx, dec + decLen, &decLen) != 1; } @@ -493,6 +499,10 @@ static int test_aes_tag_tls_dec(ENGINE *e, const EVP_CIPHER *cipher, PRINT_BUFFER("Decrypted", msg + EVP_GCM_TLS_EXPLICIT_IV_LEN, dLen); (void)dLen; } + if ((err == 0) && (e != NULL)) { + PRINT_MSG("TLS decrypt requires a fresh record header"); + err = EVP_Cipher(ctx, msg, msg, len) >= 0; + } EVP_CIPHER_CTX_free(ctx); @@ -1173,18 +1183,448 @@ int test_aes128_gcm_iv_gen_bounds(ENGINE *e, void *data) #endif /* HAVE_FIPS || HAVE_FIPS_VERSION */ } +int test_aes_gcm_ctx_copy_rejected(ENGINE *e, void *data) +{ + int err = 0; + int len; + int finalLen; + EVP_CIPHER_CTX *src = NULL; + EVP_CIPHER_CTX *dst = NULL; + unsigned char key[16] = {0}; + unsigned char iv[12] = {0}; + unsigned char aad[4] = {1, 2, 3, 4}; + unsigned char msg[4] = {5, 6, 7, 8}; + unsigned char enc[sizeof(msg)]; + unsigned char tag[16]; + + (void)data; + + err = (src = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = (dst = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_EncryptInit_ex(src, EVP_aes_128_gcm(), e, key, iv) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(src, NULL, &len, aad, sizeof(aad)) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_copy(dst, src) == 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(src, enc, &len, msg, sizeof(msg)) != 1; + } + if (err == 0) { + err = EVP_EncryptFinal_ex(src, enc + len, &finalLen) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(src, EVP_CTRL_AEAD_GET_TAG, + sizeof(tag), tag) != 1; + } + + EVP_CIPHER_CTX_free(dst); + EVP_CIPHER_CTX_free(src); + + return err; +} + +int test_aes_gcm_cleanup_empty_ctx(ENGINE *e, void *data) +{ + int err = 0; + EVP_CIPHER_CTX *active = NULL; + EVP_CIPHER_CTX *empty = NULL; + const EVP_CIPHER *cipher = NULL; + int (*cleanup)(EVP_CIPHER_CTX *) = NULL; + unsigned char key[16] = {0}; + unsigned char iv[12] = {0}; + + (void)data; + + err = (active = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = (empty = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_EncryptInit_ex(active, EVP_aes_128_gcm(), e, key, iv) != 1; + } + if (err == 0) { + cipher = EVP_CIPHER_CTX_cipher(active); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + cleanup = EVP_CIPHER_meth_get_cleanup(cipher); +#else + cleanup = cipher->cleanup; +#endif + err = (cleanup == NULL) || (cleanup(empty) != 1); + } + + EVP_CIPHER_CTX_free(empty); + EVP_CIPHER_CTX_free(active); + return err; +} + +int test_aes_gcm_aad_length_bounds(ENGINE *e, void *data) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + int err = 0; + int len; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = NULL; + int (*doCipher)(EVP_CIPHER_CTX *, unsigned char *, + const unsigned char *, size_t) = NULL; + unsigned char key[16] = {0}; + unsigned char iv[12] = {0}; + unsigned char aad = 0; + + (void)data; + + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), e, key, iv) != 1; + } + if (err == 0) { + cipher = EVP_CIPHER_CTX_cipher(ctx); + doCipher = EVP_CIPHER_meth_get_do_cipher(cipher); + err = doCipher == NULL; + } + if (err == 0) { + size_t oversized = (size_t)INT_MAX + 1U; + + err = doCipher(ctx, NULL, &aad, oversized) >= 0; + } + if ((err == 0) && (sizeof(size_t) > sizeof(unsigned int))) { + size_t oversized = (size_t)UINT_MAX + 2U; + + err = doCipher(ctx, NULL, &aad, oversized) >= 0; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, NULL, &len, &aad, sizeof(aad)) != 1; + } + + EVP_CIPHER_CTX_free(ctx); + + return err; +#else + (void)e; + (void)data; + return 0; +#endif +} + +int test_aes_gcm_auth_error_queue(ENGINE *e, void *data) +{ + int err = 0; + int i; + int len = 0; + int finalLen; + int ret; + int flags; + int line; + unsigned long code; + unsigned long expectedError; + const char *file; + const char *detail; + EVP_CIPHER_CTX *ctx = NULL; + unsigned char key[16] = {0}; + unsigned char iv[12] = {0}; + unsigned char aad[] = "AAD"; + unsigned char msg[] = "Test pattern"; + unsigned char enc[sizeof(msg)]; + unsigned char dec[sizeof(msg)]; + unsigned char tag[16]; + unsigned char tlsAad[EVP_AEAD_TLS1_AAD_LEN] = {0}; + unsigned char record[EVP_GCM_TLS_EXPLICIT_IV_LEN + sizeof(msg) + + EVP_GCM_TLS_TAG_LEN] = {0}; + unsigned char recordCopy[sizeof(record)]; + + (void)data; + + err = test_aes_tag_enc(NULL, EVP_aes_128_gcm(), key, iv, sizeof(iv), + aad, msg, sizeof(msg), enc, tag, 0, 0); + if (err == 0) { + tag[0] ^= 1; + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, + sizeof(tag), tag) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, dec, &len, enc, sizeof(enc)) != 1; + } + if (err == 0) { + ERR_clear_error(); + ret = EVP_DecryptFinal_ex(ctx, dec + len, &finalLen); + err = 1; + if (ret <= 0) { + while ((code = ERR_get_error_line_data(&file, &line, &detail, + &flags)) != 0) { + if ((ERR_GET_LIB(code) == ERR_LIB_USER) && + ((flags & ERR_TXT_STRING) != 0) && + (strstr(detail, "wolfEngine AES-GCM") != NULL)) { + err = 0; + break; + } + } + } + } + + EVP_CIPHER_CTX_free(ctx); + ctx = NULL; + if (err == 0) { + tlsAad[8] = 23; + tlsAad[9] = 3; + tlsAad[10] = 3; + tlsAad[12] = sizeof(record) - EVP_GCM_TLS_TAG_LEN; + XMEMCPY(record + EVP_GCM_TLS_EXPLICIT_IV_LEN, msg, sizeof(msg)); + err = test_aes_tag_tls_enc(NULL, EVP_aes_128_gcm(), key, iv, + EVP_GCM_TLS_FIXED_IV_LEN, tlsAad, record, + sizeof(record), 0); + } + if (err == 0) { + record[sizeof(record) - 1] ^= 1; + tlsAad[12] = sizeof(record); + } + for (i = 0; (err == 0) && (i < 4); i++) { + XMEMCPY(recordCopy, record, sizeof(record)); + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), + (i & 1) ? e : NULL, key, NULL) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IV_FIXED, + EVP_GCM_TLS_FIXED_IV_LEN, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(tlsAad), tlsAad) != + EVP_GCM_TLS_TAG_LEN; + } + if (err == 0) { + PRINT_MSG("TLS GCM authentication failure preserves error state"); + ERR_clear_error(); + if (i >= 2) { + ERR_put_error(ERR_LIB_USER, 0, 101, __FILE__, __LINE__); + } + expectedError = ERR_peek_error(); + ret = EVP_Cipher(ctx, recordCopy, recordCopy, sizeof(recordCopy)); + code = ERR_get_error(); + err = (ret >= 0) || (code != expectedError) || + (ERR_peek_error() != 0); + } + EVP_CIPHER_CTX_free(ctx); + ctx = NULL; + } + + EVP_CIPHER_CTX_free(ctx); + ERR_clear_error(); + return err; +} + +int test_aes_gcm_ctrl_output_buffers(ENGINE *e, void *data) +{ + int err = 0; + EVP_CIPHER_CTX *ctx = NULL; + unsigned char key[16] = {0}; + unsigned char iv[12] = {0}; + unsigned char aad[] = "AAD"; + unsigned char msg[] = "Test pattern"; + unsigned char enc[sizeof(msg)]; + unsigned char expectedEnc[sizeof(msg)]; + unsigned char tag[16] = {0}; + unsigned char expectedTag[16] = {0}; +#if !defined(HAVE_FIPS) && !defined(HAVE_FIPS_VERSION) + unsigned char generated[8] = {0}; +#endif + + (void)data; + iv[11] = 1; + + err = test_aes_tag_enc(NULL, EVP_aes_128_gcm(), key, iv, sizeof(iv), + aad, msg, sizeof(msg), expectedEnc, expectedTag, + 0, 0); + if (err == 0) { + err = test_aes_tag_enc(e, EVP_aes_128_gcm(), key, iv, sizeof(iv), + aad, msg, sizeof(msg), enc, tag, 0, 0); + } + if (err == 0) { + err = memcmp(enc, expectedEnc, sizeof(enc)) != 0; + } + if (err == 0) { + err = memcmp(tag, expectedTag, sizeof(tag)) != 0; + } + +#if !defined(HAVE_FIPS) && !defined(HAVE_FIPS_VERSION) + if (err == 0) { + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IV_FIXED, + -1, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_IV_GEN, + sizeof(generated), generated) != 1; + } + if (err == 0) { + err = memcmp(generated, iv + sizeof(iv) - sizeof(generated), + sizeof(generated)) != 0; + } +#endif + + EVP_CIPHER_CTX_free(ctx); + return err; +} + #endif /* WE_HAVE_AESGCM */ /******************************************************************************/ #ifdef WE_HAVE_AESCCM +static int test_aes_ccm_default_tag_encrypt(ENGINE *e, unsigned char *enc, + unsigned char *tag) +{ + int err = 0; + int encLen = 0; + unsigned char key[16]; + unsigned char iv[13]; + unsigned char msg[] = "Test pattern"; + EVP_CIPHER_CTX *ctx = NULL; + + XMEMSET(key, 0, sizeof(key)); + XMEMSET(iv, 0, sizeof(iv)); + + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, EVP_aes_128_ccm(), e, NULL, NULL) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, + sizeof(iv), NULL) != 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, NULL, &encLen, NULL, sizeof(msg)) != 1; + } + if ((err == 0) && (e != NULL)) { + encLen = -1; + err = EVP_EncryptUpdate(ctx, enc, &encLen, msg, 0) != 1; + } + if ((err == 0) && (e != NULL)) { + err = encLen != 0; + } + if ((err == 0) && (e != NULL)) { + err = EVP_EncryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if ((err == 0) && (e != NULL)) { + err = EVP_EncryptUpdate(ctx, NULL, &encLen, NULL, sizeof(msg)) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, enc, &encLen, msg, sizeof(msg)) != 1; + } + if (err == 0) { + err = encLen != (int)sizeof(msg); + } + if (err == 0) { + err = EVP_EncryptFinal_ex(ctx, enc + encLen, &encLen) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + CCM_TAG_DEFAULT_LEN, tag) != 1; + } + + EVP_CIPHER_CTX_free(ctx); + return err; +} + +static int test_aes_ccm_default_tag(ENGINE *e) +{ + int err = 0; + unsigned char enc[sizeof("Test pattern")]; + unsigned char encOSSL[sizeof("Test pattern")]; + unsigned char tag[CCM_TAG_DEFAULT_LEN]; + unsigned char tagOSSL[CCM_TAG_DEFAULT_LEN]; + + err = test_aes_ccm_default_tag_encrypt(NULL, encOSSL, tagOSSL); + if (err == 0) { + err = test_aes_ccm_default_tag_encrypt(e, enc, tag); + } + if (err == 0) { + err = XMEMCMP(enc, encOSSL, sizeof(enc)) != 0; + } + if (err == 0) { + err = XMEMCMP(tag, tagOSSL, sizeof(tag)) != 0; + } + + return err; +} + +static int test_aes_ccm_empty(ENGINE *e, const EVP_CIPHER *cipher) +{ + int err; + unsigned char key[32] = {0}; + unsigned char iv[13] = {0}; + unsigned char aad[] = "AAD"; + unsigned char msg[1] = {0}; + unsigned char enc[1] = {0}; + unsigned char dec[1] = {0}; + unsigned char tag[16]; + unsigned char expectedTag[sizeof(tag)]; + + PRINT_MSG("CCM authenticates empty messages with AAD"); + err = test_aes_tag_enc(NULL, cipher, key, iv, sizeof(iv), aad, msg, 0, + enc, expectedTag, 1, 0); + if (err == 0) { + err = test_aes_tag_dec(NULL, cipher, key, iv, sizeof(iv), aad, msg, 0, + enc, expectedTag, dec, 1, 0); + } + if (err == 0) { + expectedTag[0] ^= 1; + err = test_aes_tag_dec(NULL, cipher, key, iv, sizeof(iv), aad, msg, 0, + enc, expectedTag, dec, 1, 0) == 0; + } + if (err == 0) { + err = test_aes_tag_dec(e, cipher, key, iv, sizeof(iv), aad, msg, 0, + enc, expectedTag, dec, 1, 0) == 0; + } + if (err == 0) { + expectedTag[0] ^= 1; + err = test_aes_tag_dec(e, cipher, key, iv, sizeof(iv), aad, msg, 0, + enc, expectedTag, dec, 1, 0); + } + if (err == 0) { + err = test_aes_tag_enc(e, cipher, key, iv, sizeof(iv), aad, msg, 0, + enc, tag, 1, 0); + } + if (err == 0) { + err = XMEMCMP(tag, expectedTag, sizeof(tag)) != 0; + } + + return err; +} + int test_aes128_ccm(ENGINE *e, void *data) { int err = 0; /* test with default length field (L) */ err = test_aes_tag(e, data, EVP_aes_128_ccm(), 16, 13, 1, 0); + if (err == 0) { + err = test_aes_ccm_default_tag(e); + } + if (err == 0) { + err = test_aes_ccm_empty(e, EVP_aes_128_ccm()); + } #if OPENSSL_VERSION_NUMBER < 0x30000000L /* test with modified length field (L) of 7 */ @@ -1204,6 +1644,9 @@ int test_aes192_ccm(ENGINE *e, void *data) /* test with default length field (L) */ err = test_aes_tag(e, data, EVP_aes_192_ccm(), 24, 13, 1, 0); + if (err == 0) { + err = test_aes_ccm_empty(e, EVP_aes_192_ccm()); + } #if OPENSSL_VERSION_NUMBER < 0x30000000L /* test with modified length field (L) of 7 */ @@ -1223,6 +1666,9 @@ int test_aes256_ccm(ENGINE *e, void *data) /* test with default length field (L) */ err = test_aes_tag(e, data, EVP_aes_256_ccm(), 32, 13, 1, 0); + if (err == 0) { + err = test_aes_ccm_empty(e, EVP_aes_256_ccm()); + } #if OPENSSL_VERSION_NUMBER < 0x30000000L /* test with modified length field (L) of 7 */ diff --git a/test/test_cipher.c b/test/test_cipher.c index 34436b21..ec67e747 100644 --- a/test/test_cipher.c +++ b/test/test_cipher.c @@ -20,6 +20,7 @@ */ #include "unit.h" +#include #if defined(WE_HAVE_DES3CBC) || defined(WE_HAVE_AESCBC) @@ -332,6 +333,151 @@ static int test_stream_enc_dec(ENGINE *e, void *data, const EVP_CIPHER *cipher, #ifdef WE_HAVE_DES3CBC +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) +static int des3DecryptErrorLogged; + +static void test_des3_cbc_log_cb(const int logLevel, const int component, + const char *const logMessage) +{ + if ((logLevel == WE_LOG_ERROR) && (component == WE_LOG_CIPHER) && + (strstr(logMessage, "wc_Des3_CbcDecrypt") != NULL)) { + des3DecryptErrorLogged = 1; + } +} +#endif + + +static int test_des3_cbc_copy(ENGINE *e) +{ + const int offsets[] = { 0, 1, 7, 8, 9, 17, 33 }; + unsigned char key[24] = { 1 }; + unsigned char nextKey[24] = { 2 }; + unsigned char iv[8] = { 4 }; + unsigned char in[64] = { 3 }; + unsigned char out[80]; + unsigned char expected[80]; + EVP_CIPHER_CTX *src = NULL, *copy = NULL; + EVP_CIPHER_CTX *ref = NULL, *copyRef = NULL; + int err = 0, enc, order, stage, i, outLen, expectedLen; + + PRINT_MSG("Copy DES3-CBC with buffered and complete blocks"); + for (enc = 0; err == 0 && enc < 2; enc++) { + for (order = 0; err == 0 && order < 2; order++) { + for (i = 0; err == 0 && i < (int)(sizeof(offsets) / + sizeof(offsets[0])); i++) { + src = EVP_CIPHER_CTX_new(); + copy = EVP_CIPHER_CTX_new(); + ref = EVP_CIPHER_CTX_new(); + copyRef = EVP_CIPHER_CTX_new(); + if (src == NULL || copy == NULL || ref == NULL || + copyRef == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_CipherInit_ex(src, EVP_des_ede3_cbc(), e, key, iv, + enc) != 1 || + EVP_CipherInit_ex(copy, EVP_des_ede3_cbc(), e, nextKey, + iv, enc) != 1 || + EVP_CipherInit_ex(ref, EVP_des_ede3_cbc(), NULL, key, + iv, enc) != 1 || + EVP_CIPHER_CTX_set_padding(src, 0) != 1 || + EVP_CIPHER_CTX_set_padding(ref, 0) != 1; + } + if (err == 0) { + err = EVP_CipherUpdate(src, out, &outLen, in, + offsets[i]) != 1 || + EVP_CipherUpdate(ref, expected, &expectedLen, in, + offsets[i]) != 1; + } + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0 || + EVP_CIPHER_CTX_copy(copy, src) != 1 || + EVP_CIPHER_CTX_copy(copyRef, ref) != 1; + } + if (err == 0) { + err = EVP_CipherInit_ex(src, NULL, NULL, nextKey, iv, + enc) != 1 || + EVP_CipherInit_ex(ref, NULL, NULL, nextKey, iv, + enc) != 1; + } + if (order == 0) { + EVP_CIPHER_CTX_free(src); + src = NULL; + } + if (err == 0) { + err = EVP_CipherUpdate(copy, out, &outLen, + in + offsets[i], + sizeof(in) - offsets[i]) != 1 || + EVP_CipherUpdate(copyRef, expected, &expectedLen, + in + offsets[i], + sizeof(in) - offsets[i]) != 1; + } + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0; + } + if (err == 0) { + err = EVP_CipherFinal_ex(copy, out, &outLen) != 1 || + EVP_CipherFinal_ex(copyRef, expected, + &expectedLen) != 1; + } + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0; + } + EVP_CIPHER_CTX_free(copy); + copy = NULL; + if (err == 0 && order == 1) { + err = EVP_CipherUpdate(src, out, &outLen, in, + sizeof(in)) != 1 || + EVP_CipherUpdate(ref, expected, &expectedLen, in, + sizeof(in)) != 1; + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0; + } + } + EVP_CIPHER_CTX_free(src); + EVP_CIPHER_CTX_free(ref); + EVP_CIPHER_CTX_free(copyRef); + src = ref = copyRef = NULL; + } + } + } + PRINT_MSG("Copy DES3-CBC before setting the key"); + for (stage = 0; err == 0 && stage < 2; stage++) { + src = EVP_CIPHER_CTX_new(); + copy = EVP_CIPHER_CTX_new(); + ref = EVP_CIPHER_CTX_new(); + if (src == NULL || copy == NULL || ref == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_CipherInit_ex(src, EVP_des_ede3_cbc(), e, NULL, + stage ? iv : NULL, 1) != 1 || + EVP_CIPHER_CTX_copy(copy, src) != 1 || + EVP_CipherInit_ex(copy, NULL, NULL, key, + stage ? NULL : iv, 1) != 1 || + EVP_CipherInit_ex(ref, EVP_des_ede3_cbc(), NULL, key, iv, + 1) != 1; + } + if (err == 0) { + err = EVP_CipherUpdate(copy, out, &outLen, in, sizeof(in)) != 1 || + EVP_CipherUpdate(ref, expected, &expectedLen, in, + sizeof(in)) != 1; + } + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0; + } + EVP_CIPHER_CTX_free(src); + EVP_CIPHER_CTX_free(copy); + EVP_CIPHER_CTX_free(ref); + src = copy = ref = NULL; + } + return err; +} int test_des3_cbc(ENGINE *e, void *data) { @@ -349,6 +495,206 @@ int test_des3_cbc_stream(ENGINE *e, void *data) err = test_stream_enc_dec(e, data, EVP_des_ede3_cbc(), 24, 8, 1, 1); if (err == 0) err = test_stream_enc_dec(e, data, EVP_des_ede3_cbc(), 24, 8, 7, 1); + if (err == 0) + err = test_des3_cbc_copy(e); + + return err; +} + +/******************************************************************************/ + +int test_des3_cbc_iv_bounds(ENGINE *e, void *data) +{ + int err = 0; + EVP_CIPHER_CTX *ctx = NULL; + unsigned char key[24] = { 0 }; + unsigned char iv[8] = { 0 }; + unsigned char in[8] = { 0 }; + unsigned char out[8]; + unsigned char *ctxIv; + int outLen; + + (void)data; + + ctx = EVP_CIPHER_CTX_new(); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, EVP_des_ede3_cbc(), e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_set_padding(ctx, 0) != 1; + } + if (err == 0) { + ctxIv = EVP_CIPHER_CTX_iv_noconst(ctx); + XMEMSET(ctxIv + sizeof(iv), 0xa5, EVP_MAX_IV_LENGTH - sizeof(iv)); + err = EVP_EncryptUpdate(ctx, out, &outLen, in, sizeof(in)) != 1; + } + if (err == 0) { + err = outLen != (int)sizeof(out); + } + if (err == 0) { + size_t i; + + for (i = sizeof(iv); i < EVP_MAX_IV_LENGTH; i++) { + if (ctxIv[i] != 0xa5) { + err = 1; + break; + } + } + } + + EVP_CIPHER_CTX_free(ctx); + + return err; +} + +/******************************************************************************/ + +int test_des3_cbc_decrypt_error_log(ENGINE *e, void *data) +{ +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) + int err = 0; + int initialDebug = 0; + EVP_CIPHER_CTX *ctx = NULL; + unsigned char key[24] = { 0 }; + unsigned char iv[8] = { 0 }; + unsigned char in[8] = { 0 }; + int outLen; + + if (data == NULL) { + err = 1; + } + else { + initialDebug = *(int *)data; + } + + if (err == 0) { + ctx = EVP_CIPHER_CTX_new(); + if (ctx == NULL) { + err = 1; + } + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, EVP_des_ede3_cbc(), e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_set_padding(ctx, 0) != 1; + } + if (err == 0) { + err = wolfEngine_SetLoggingCb(test_des3_cbc_log_cb) != 0; + } + if (err == 0) { + err = wolfEngine_Debugging_ON() != 0; + } + if (err == 0) { + des3DecryptErrorLogged = 0; + err = EVP_DecryptUpdate(ctx, NULL, &outLen, in, sizeof(in)) == 1; + } + if (err == 0) { + err = des3DecryptErrorLogged == 0; + } + + (void)wolfEngine_SetLoggingCb(NULL); + if (!initialDebug) { + wolfEngine_Debugging_OFF(); + } + EVP_CIPHER_CTX_free(ctx); + + return err; +#else + (void)e; + (void)data; + return 0; +#endif +} + +/******************************************************************************/ + +int test_des3_cbc_rekey_cleanup(ENGINE *e, void *data) +{ + int err = 0; + const EVP_CIPHER *cipher; + EVP_CIPHER_CTX *ctx = NULL; + EVP_CIPHER_CTX *ref = NULL; + EVP_CIPHER_CTX *copyCtx = NULL; + int (*cleanup)(EVP_CIPHER_CTX *) = NULL; + unsigned char key[24] = { 0 }; + unsigned char nextKey[24] = { 2 }; + unsigned char iv[8] = { 0 }; + unsigned char in[8] = { 0 }; + unsigned char out[8]; + unsigned char expected[8]; + int outLen; + int expectedLen; + + (void)data; + + cipher = ENGINE_get_cipher(e, NID_des_ede3_cbc); + if (cipher == NULL) { + err = 1; + } + if (err == 0) { + err = (EVP_CIPHER_flags(cipher) & EVP_CIPH_CTRL_INIT) == 0; + } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (err == 0) { + cleanup = EVP_CIPHER_meth_get_cleanup(cipher); + } +#else + if (err == 0) { + cleanup = cipher->cleanup; + } +#endif + if (err == 0) { + err = cleanup == NULL; + } + if (err == 0) { + ctx = EVP_CIPHER_CTX_new(); + ref = EVP_CIPHER_CTX_new(); + copyCtx = EVP_CIPHER_CTX_new(); + if ((ctx == NULL) || (ref == NULL) || (copyCtx == NULL)) { + err = 1; + } + } + if (err == 0) { + err = cleanup(copyCtx) != 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, EVP_des_ede3_cbc(), e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_copy(copyCtx, ctx) != 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, NULL, NULL, nextKey, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_set_padding(ctx, 0) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, out, &outLen, in, sizeof(in)) != 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ref, EVP_des_ede3_cbc(), NULL, nextKey, iv) != + 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_set_padding(ref, 0) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ref, expected, &expectedLen, in, sizeof(in)) != + 1; + } + if (err == 0) { + err = (outLen != expectedLen) || + (XMEMCMP(out, expected, sizeof(out)) != 0); + } + + EVP_CIPHER_CTX_free(copyCtx); + EVP_CIPHER_CTX_free(ref); + EVP_CIPHER_CTX_free(ctx); return err; } @@ -357,11 +703,86 @@ int test_des3_cbc_stream(ENGINE *e, void *data) /******************************************************************************/ +#if defined(WE_HAVE_AESCBC) || defined(WE_HAVE_AESECB) +static int test_aes_block_lifecycle(ENGINE *e, const EVP_CIPHER *cipher, + const unsigned char *iv) +{ + int err = 0; + EVP_CIPHER_CTX *ctx = NULL; + EVP_CIPHER_CTX *copyCtx = NULL; + unsigned char key[32] = { 0 }; + unsigned char input[32] = { 0 }; + unsigned char output[16]; + unsigned char copyOutput[16]; + int outputLen = 0; + int copyOutputLen = 0; + + ctx = EVP_CIPHER_CTX_new(); + err = ctx == NULL; + if (err == 0) { + err = EVP_CipherInit_ex(ctx, cipher, e, key, iv, 1) != 1; + } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (err == 0) { + err = EVP_CIPHER_meth_get_cleanup(EVP_CIPHER_CTX_cipher(ctx)) == NULL; + } +#else + if (err == 0) { + err = EVP_CIPHER_CTX_cipher(ctx)->cleanup == NULL; + } +#endif + if (err == 0) { + err = EVP_CipherInit_ex(ctx, NULL, e, key, iv, -1) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_set_padding(ctx, 0) != 1; + } + if (err == 0) { + err = EVP_CipherUpdate(ctx, output, &outputLen, input, + sizeof(output)) != 1; + } + if (err == 0) { + copyCtx = EVP_CIPHER_CTX_new(); + err = copyCtx == NULL; + } + if (err == 0) { + err = EVP_CIPHER_CTX_copy(copyCtx, ctx) != 1; + } + if (err == 0) { + err = EVP_CipherUpdate(ctx, output, &outputLen, + input + sizeof(output), sizeof(output)) != 1; + } + if (err == 0) { + err = EVP_CipherUpdate(copyCtx, copyOutput, ©OutputLen, + input + sizeof(output), + sizeof(copyOutput)) != 1; + } + if (err == 0) { + err = (outputLen != copyOutputLen) || + (memcmp(output, copyOutput, outputLen) != 0); + } + + EVP_CIPHER_CTX_free(copyCtx); + EVP_CIPHER_CTX_free(ctx); + + return err; +} +#endif + +/******************************************************************************/ + #ifdef WE_HAVE_AESECB int test_aes128_ecb(ENGINE *e, void *data) { - return test_cipher_enc_dec(e, data, EVP_aes_128_ecb(), 16, 16); + int err; + + err = test_cipher_enc_dec(e, data, EVP_aes_128_ecb(), 16, 16); + if (err == 0) { + err = test_aes_block_lifecycle(e, EVP_aes_128_ecb(), NULL); + } + + return err; } /******************************************************************************/ @@ -390,7 +811,6 @@ int test_aes128_ecb_stream(ENGINE *e, void *data) return err; } - /******************************************************************************/ int test_aes192_ecb_stream(ENGINE *e, void *data) @@ -425,7 +845,56 @@ int test_aes256_ecb_stream(ENGINE *e, void *data) int test_aes128_cbc(ENGINE *e, void *data) { - return test_cipher_enc_dec(e, data, EVP_aes_128_cbc(), 16, 16); + int err; + + err = test_cipher_enc_dec(e, data, EVP_aes_128_cbc(), 16, 16); + + if (err == 0) { + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher; + int (*doCipher)(EVP_CIPHER_CTX *, unsigned char *, + const unsigned char *, size_t); + unsigned char key[16] = { 0 }; + unsigned char iv[16] = { 0 }; + unsigned char in[16] = { 0 }; + + ctx = EVP_CIPHER_CTX_new(); + err = ctx == NULL; + if (err == 0) { + err = EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), e, key, iv, 1) + != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_iv_length(ctx) != (int)sizeof(iv); + } + if (err == 0) { + cipher = EVP_CIPHER_CTX_cipher(ctx); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + doCipher = EVP_CIPHER_meth_get_do_cipher(cipher); +#else + doCipher = cipher->do_cipher; +#endif + err = doCipher == NULL; + } + if (err == 0) { + err = doCipher(ctx, NULL, in, sizeof(in)) != 0; + } + if (err == 0) { + err = EVP_CipherInit_ex(ctx, NULL, e, key, iv, 0) != 1; + } + if (err == 0) { + err = doCipher(ctx, NULL, in, sizeof(in)) != 0; + } + EVP_CIPHER_CTX_free(ctx); + } + + if (err == 0) { + unsigned char iv[16] = { 0 }; + + err = test_aes_block_lifecycle(e, EVP_aes_128_cbc(), iv); + } + + return err; } /******************************************************************************/ @@ -483,8 +952,7 @@ int test_aes256_cbc_stream(ENGINE *e, void *data) /******************************************************************************/ -#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ - !defined(HAVE_FIPS) && !defined(HAVE_FIPS_VERSION) +#if !defined(HAVE_FIPS) && !defined(HAVE_FIPS_VERSION) int test_aes128_cbc_hmac_tls_short(ENGINE *e, void *data) { int err = 0; @@ -492,7 +960,8 @@ int test_aes128_cbc_hmac_tls_short(ENGINE *e, void *data) int decLen = 0; EVP_CIPHER_CTX *encCtx = NULL; EVP_CIPHER_CTX *ctx = NULL; - const EVP_CIPHER *cipher = EVP_aes_128_cbc_hmac_sha256(); + const EVP_CIPHER *cipher = ENGINE_get_cipher(e, + NID_aes_128_cbc_hmac_sha256); unsigned char key[16]; unsigned char macKey[SHA256_DIGEST_LENGTH]; unsigned char iv[16]; @@ -503,12 +972,8 @@ int test_aes128_cbc_hmac_tls_short(ENGINE *e, void *data) (void)data; - /* OpenSSL only provides the stitched AES-CBC-HMAC-SHA256 cipher on - * platforms where it has a hand-written assembly implementation (e.g. - * AES-NI x86_64); elsewhere EVP_aes_128_cbc_hmac_sha256() returns NULL, - * so there is nothing to exercise. */ if (cipher == NULL) { - return 0; + return 1; } XMEMSET(key, 0, sizeof(key)); @@ -570,23 +1035,1155 @@ int test_aes128_cbc_hmac_tls_short(ENGINE *e, void *data) return err; } -#else -int test_aes128_cbc_hmac_tls_short(ENGINE *e, void *data) + +static int test_cbc_hmac_plain_reuse(EVP_CIPHER_CTX *ctx, + unsigned char *key, unsigned char *iv) +{ + int err; + unsigned char msg[AES_BLOCK_SIZE] = {1, 2, 3, 4}; + unsigned char enc[sizeof(msg)]; + unsigned char out[sizeof(msg)]; + + PRINT_MSG("CBC-HMAC consumes TLS framing once per record"); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, msg, + sizeof(msg), enc, 0); + if (err == 0) { + err = EVP_Cipher(ctx, out, enc, sizeof(enc)) != (int)sizeof(msg); + } + if (err == 0) { + err = XMEMCMP(out, msg, sizeof(msg)) != 0; + } + + return err; +} + +int test_aes128_cbc_hmac_tls_lengths(ENGINE *e, void *data) +{ + int err = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher(e, + NID_aes_128_cbc_hmac_sha256); + int (*doCipher)(EVP_CIPHER_CTX *, unsigned char *, + const unsigned char *, size_t) = NULL; + unsigned char key[16] = {0}; + unsigned char macKey[SHA256_DIGEST_LENGTH] = {0}; + unsigned char iv[16] = {0}; + unsigned char record[64] = {0}; + unsigned char out[64] = {0}; + unsigned char aad[EVP_AEAD_TLS1_AAD_LEN] = {0}; + + (void)data; + + if (cipher == NULL) { + return 1; + } + aad[9] = (unsigned char)(TLS1_2_VERSION >> 8); + aad[10] = (unsigned char)TLS1_2_VERSION; + + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + doCipher = EVP_CIPHER_meth_get_do_cipher(EVP_CIPHER_CTX_cipher(ctx)); +#else + doCipher = EVP_CIPHER_CTX_cipher(ctx)->do_cipher; +#endif + err = doCipher == NULL; + } + if (err == 0) { + err = doCipher(ctx, out, record, 0) >= 0; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + err = doCipher(ctx, out, record, 17) >= 0; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + err = doCipher(ctx, out, record, (size_t)INT_MAX + 1U) >= 0; + } + if (err == 0) { + err = test_cbc_hmac_plain_reuse(ctx, key, iv); + } + + EVP_CIPHER_CTX_free(ctx); + return err; +} + +int test_aes128_cbc_hmac_no_tls_mac(ENGINE *e, void *data) +{ + int err = 0; + int len = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher(e, + NID_aes_128_cbc_hmac_sha256); + unsigned char key[16] = {0}; + unsigned char macKey[SHA256_DIGEST_LENGTH] = {0}; + unsigned char iv[16] = {0}; + unsigned char msg[16] = {1, 2, 3, 4}; + unsigned char enc[sizeof(msg)] = {0}; + unsigned char out[sizeof(msg) + SHA256_DIGEST_LENGTH] = {0}; + + (void)data; + + if (cipher == NULL) { + return 1; + } + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, msg, + sizeof(msg), enc, 0); + if (err == 0) { + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + len = EVP_Cipher(ctx, out, enc, sizeof(enc)); + err = len != sizeof(msg); + } + if (err == 0) { + err = XMEMCMP(out, msg, sizeof(msg)) != 0; + } + + EVP_CIPHER_CTX_free(ctx); + return err; +} + +int test_aes128_cbc_hmac_tls_extended_padding(ENGINE *e, void *data) +{ + int err = 0; + int len = 0; + unsigned int macLen = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher(e, + NID_aes_128_cbc_hmac_sha256); + unsigned char key[16] = {0}; + unsigned char macKey[SHA256_DIGEST_LENGTH] = {0}; + unsigned char iv[16] = {0}; + unsigned char msg[16] = {1, 2, 3, 4}; + unsigned char aad[EVP_AEAD_TLS1_AAD_LEN] = {0}; + unsigned char hmacInput[EVP_AEAD_TLS1_AAD_LEN + sizeof(msg)] = {0}; + unsigned char mac[SHA256_DIGEST_LENGTH] = {0}; + unsigned char plain[sizeof(msg) + SHA256_DIGEST_LENGTH + 32] = {0}; + unsigned char record[sizeof(iv) + sizeof(plain)] = {0}; + unsigned char out[sizeof(record)] = {0}; + + (void)data; + + if (cipher == NULL) { + return 1; + } + aad[9] = (unsigned char)(TLS1_2_VERSION >> 8); + aad[10] = (unsigned char)TLS1_2_VERSION; + XMEMCPY(hmacInput, aad, sizeof(aad)); + hmacInput[sizeof(aad) - 1] = sizeof(msg); + XMEMCPY(hmacInput + sizeof(aad), msg, sizeof(msg)); + err = HMAC(EVP_sha256(), macKey, sizeof(macKey), hmacInput, + sizeof(hmacInput), mac, &macLen) == NULL; + if (err == 0) { + err = macLen != sizeof(mac); + } + if (err == 0) { + XMEMCPY(plain, msg, sizeof(msg)); + XMEMCPY(plain + sizeof(msg), mac, sizeof(mac)); + XMEMSET(plain + sizeof(msg) + sizeof(mac), 31, 32); + XMEMCPY(record, iv, sizeof(iv)); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(plain), record + sizeof(iv), 0); + } + + aad[sizeof(aad) - 1] = sizeof(record); + if (err == 0) { + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + len = EVP_Cipher(ctx, out, record, sizeof(record)); + err = len != sizeof(msg); + } + if (err == 0) { + err = XMEMCMP(out + sizeof(iv), msg, sizeof(msg)) != 0; + } + if (err == 0) { + err = test_cbc_hmac_plain_reuse(ctx, key, + record + sizeof(record) - sizeof(iv)); + } + + EVP_CIPHER_CTX_free(ctx); + return err; +} + +int test_aes128_cbc_hmac_tls_retry_after_bad_padding(ENGINE *e, void *data) +{ + int err = 0; + int len; + unsigned int macLen = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher(e, + NID_aes_128_cbc_hmac_sha256); + int (*doCipher)(EVP_CIPHER_CTX *, unsigned char *, + const unsigned char *, size_t) = NULL; + unsigned char key[16] = {0}; + unsigned char macKey[SHA256_DIGEST_LENGTH] = {0}; + unsigned char iv[16] = {0}; + unsigned char msg[16] = {1, 2, 3, 4}; + unsigned char aad[EVP_AEAD_TLS1_AAD_LEN] = {0}; + unsigned char hmacInput[EVP_AEAD_TLS1_AAD_LEN + sizeof(msg)] = {0}; + unsigned char mac[SHA256_DIGEST_LENGTH] = {0}; + unsigned char plain[sizeof(msg) + SHA256_DIGEST_LENGTH + 16] = {0}; + unsigned char validRecord[sizeof(iv) + sizeof(plain)] = {0}; + unsigned char badRecord[sizeof(validRecord)] = {0}; + unsigned char badMacRecord[sizeof(validRecord)] = {0}; + unsigned char out[sizeof(validRecord)] = {0}; + + (void)data; + + if (cipher == NULL) { + return 1; + } + aad[9] = (unsigned char)(TLS1_2_VERSION >> 8); + aad[10] = (unsigned char)TLS1_2_VERSION; + XMEMCPY(hmacInput, aad, sizeof(aad)); + hmacInput[sizeof(aad) - 1] = sizeof(msg); + XMEMCPY(hmacInput + sizeof(aad), msg, sizeof(msg)); + err = HMAC(EVP_sha256(), macKey, sizeof(macKey), hmacInput, + sizeof(hmacInput), mac, &macLen) == NULL; + if (err == 0) { + err = macLen != sizeof(mac); + } + if (err == 0) { + XMEMCPY(plain, msg, sizeof(msg)); + XMEMCPY(plain + sizeof(msg), mac, sizeof(mac)); + XMEMSET(plain + sizeof(msg) + sizeof(mac), 15, 16); + XMEMCPY(validRecord, iv, sizeof(iv)); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(plain), validRecord + sizeof(iv), 0); + } + if (err == 0) { + plain[sizeof(msg)] ^= 1; + XMEMCPY(badMacRecord, iv, sizeof(iv)); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(plain), badMacRecord + sizeof(iv), 0); + plain[sizeof(msg)] ^= 1; + } + if (err == 0) { + plain[sizeof(plain) - 2] ^= 1; + XMEMCPY(badRecord, iv, sizeof(iv)); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(plain), badRecord + sizeof(iv), 0); + } + + aad[sizeof(aad) - 1] = sizeof(validRecord); + if (err == 0) { + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + doCipher = EVP_CIPHER_meth_get_do_cipher(EVP_CIPHER_CTX_cipher(ctx)); +#else + doCipher = EVP_CIPHER_CTX_cipher(ctx)->do_cipher; +#endif + err = doCipher == NULL; + } + if (err == 0) { + err = doCipher(ctx, out, badRecord, sizeof(badRecord)) >= 0; + } + if (err == 0) { + err = test_cbc_hmac_plain_reuse(ctx, key, + badRecord + sizeof(badRecord) - sizeof(iv)); + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + err = doCipher(ctx, out, badMacRecord, sizeof(badMacRecord)) >= 0; + } + if (err == 0) { + err = test_cbc_hmac_plain_reuse(ctx, key, + badMacRecord + sizeof(badMacRecord) - sizeof(iv)); + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + len = doCipher(ctx, out, validRecord, sizeof(validRecord)); + err = len != sizeof(msg); + } + if (err == 0) { + err = XMEMCMP(out + sizeof(iv), msg, sizeof(msg)) != 0; + } + + EVP_CIPHER_CTX_free(ctx); + return err; +} + +int test_aes128_cbc_hmac_tls_padding_range(ENGINE *e, void *data) +{ + int err = 0; + int len; + int n; + int msgLen; + unsigned int macLen; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher(e, + NID_aes_128_cbc_hmac_sha256); + const int pads[] = {0, 15, 31, 47, 63, 127, 191, 255}; + unsigned char key[16] = {0}; + unsigned char macKey[SHA256_DIGEST_LENGTH] = {1, 2, 3, 4}; + unsigned char iv[16] = {0}; + unsigned char msg[271] = {1, 2, 3, 4}; + unsigned char aad[EVP_AEAD_TLS1_AAD_LEN] = {0}; + unsigned char hmacInput[EVP_AEAD_TLS1_AAD_LEN + sizeof(msg)] = {0}; + unsigned char mac[SHA256_DIGEST_LENGTH] = {0}; + unsigned char plain[sizeof(msg) + SHA256_DIGEST_LENGTH + 1] = {0}; + unsigned char record[sizeof(iv) + sizeof(plain)] = {0}; + unsigned char out[sizeof(record)] = {0}; + + (void)data; + + if (cipher == NULL) { + return 1; + } + aad[9] = (unsigned char)(TLS1_2_VERSION >> 8); + aad[10] = (unsigned char)TLS1_2_VERSION; + aad[sizeof(aad) - 2] = (unsigned char)(sizeof(record) >> 8); + aad[sizeof(aad) - 1] = (unsigned char)sizeof(record); + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + for (n = 0; (err == 0) && (n < (int)(sizeof(pads) / sizeof(pads[0]))); + n++) { + msgLen = (int)sizeof(msg) - pads[n]; + XMEMSET(hmacInput, 0, sizeof(hmacInput)); + XMEMCPY(hmacInput, aad, sizeof(aad)); + hmacInput[sizeof(aad) - 2] = (unsigned char)(msgLen >> 8); + hmacInput[sizeof(aad) - 1] = (unsigned char)msgLen; + XMEMCPY(hmacInput + sizeof(aad), msg, msgLen); + err = HMAC(EVP_sha256(), macKey, sizeof(macKey), hmacInput, + sizeof(aad) + msgLen, mac, &macLen) == NULL; + if (err == 0) { + err = macLen != sizeof(mac); + } + if (err == 0) { + XMEMCPY(plain, msg, msgLen); + XMEMCPY(plain + msgLen, mac, sizeof(mac)); + XMEMSET(plain + msgLen + sizeof(mac), pads[n], pads[n] + 1); + XMEMCPY(record, iv, sizeof(iv)); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(plain), record + sizeof(iv), 0); + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + len = EVP_Cipher(ctx, out, record, sizeof(record)); + err = len != msgLen; + } + if (err == 0) { + err = XMEMCMP(out + sizeof(iv), msg, msgLen) != 0; + } + } + + /* A short record cannot contain the largest claimed padding. */ + if (err == 0) { + XMEMSET(plain, 0, sizeof(iv) * 3); + plain[sizeof(iv) * 3 - 1] = 255; + XMEMCPY(record, iv, sizeof(iv)); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(iv) * 3, record + sizeof(iv), 0); + } + if (err == 0) { + aad[sizeof(aad) - 2] = 0; + aad[sizeof(aad) - 1] = sizeof(iv) * 4; + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + len = EVP_Cipher(ctx, out, record, sizeof(iv) * 4); + err = len >= 0; + } + + /* TLS 1.0 carries no explicit IV in the record. */ + if (err == 0) { + EVP_CIPHER_CTX_free(ctx); + ctx = NULL; + aad[9] = (unsigned char)(TLS1_VERSION >> 8); + aad[10] = (unsigned char)TLS1_VERSION; + aad[sizeof(aad) - 1] = sizeof(iv) * 5; + XMEMSET(hmacInput, 0, sizeof(hmacInput)); + XMEMCPY(hmacInput, aad, sizeof(aad)); + hmacInput[sizeof(aad) - 1] = sizeof(iv); + XMEMCPY(hmacInput + sizeof(aad), msg, sizeof(iv)); + err = HMAC(EVP_sha256(), macKey, sizeof(macKey), hmacInput, + sizeof(aad) + sizeof(iv), mac, &macLen) == NULL; + } + if (err == 0) { + err = macLen != sizeof(mac); + } + if (err == 0) { + XMEMCPY(plain, msg, sizeof(iv)); + XMEMCPY(plain + sizeof(iv), mac, sizeof(mac)); + XMEMSET(plain + sizeof(iv) + sizeof(mac), 31, 32); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(iv) * 5, record, 0); + } + if (err == 0) { + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + len = EVP_Cipher(ctx, out, record, sizeof(iv) * 5); + err = len != sizeof(iv); + } + if (err == 0) { + err = XMEMCMP(out, msg, sizeof(iv)) != 0; + } + if (err == 0) { + err = test_cbc_hmac_plain_reuse(ctx, key, record + sizeof(iv) * 4); + } + if (err == 0) { + plain[sizeof(iv) * 5 - 1] = 255; + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(iv) * 5, record, 0); + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad) != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + len = EVP_Cipher(ctx, out, record, sizeof(iv) * 5); + err = len >= 0; + } + + EVP_CIPHER_CTX_free(ctx); + return err; +} +#else +int test_aes128_cbc_hmac_tls_short(ENGINE *e, void *data) +{ + (void)e; + (void)data; + return 0; +} + +int test_aes128_cbc_hmac_tls_lengths(ENGINE *e, void *data) +{ + (void)e; + (void)data; + return 0; +} + +int test_aes128_cbc_hmac_no_tls_mac(ENGINE *e, void *data) +{ + (void)e; + (void)data; + return 0; +} + +int test_aes128_cbc_hmac_tls_extended_padding(ENGINE *e, void *data) +{ + (void)e; + (void)data; + return 0; +} + +int test_aes128_cbc_hmac_tls_retry_after_bad_padding(ENGINE *e, void *data) +{ + (void)e; + (void)data; + return 0; +} + +int test_aes128_cbc_hmac_tls_padding_range(ENGINE *e, void *data) +{ + (void)e; + (void)data; + return 0; +} +#endif + +/******************************************************************************/ + +int test_aes128_cbc_hmac_staged_init(ENGINE *e, void *data) +{ + int err = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher( + e, NID_aes_128_cbc_hmac_sha256); + unsigned char key[16]; + unsigned char iv[16]; + unsigned char plain[16] = {1, 2, 3, 4}; + unsigned char first[16]; + unsigned char repeated[16]; + + (void)data; + + XMEMSET(key, 0, sizeof(key)); + XMEMSET(iv, 0, sizeof(iv)); + + err = (cipher == NULL) || + ((EVP_CIPHER_flags(cipher) & EVP_CIPH_CTRL_INIT) == 0); + if (err == 0) + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, cipher, e, NULL, NULL) != 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_Cipher(ctx, first, plain, sizeof(plain)) != sizeof(plain); + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, NULL, e, NULL, NULL) != 1; + } + if (err == 0) { + err = EVP_Cipher(ctx, repeated, plain, sizeof(plain)) != sizeof(plain); + } + if (err == 0) { + err = XMEMCMP(first, repeated, sizeof(first)) != 0; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, NULL, e, NULL, NULL) != 0; + } + + EVP_CIPHER_CTX_free(ctx); + + return err; +} + +/******************************************************************************/ + +int test_aes128_cbc_hmac_plain_encrypt(ENGINE *e, void *data) +{ + int err = 0; + int len; + EVP_CIPHER_CTX *usedCtx = NULL; + EVP_CIPHER_CTX *cleanCtx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher( + e, NID_aes_128_cbc_hmac_sha256); + unsigned char key[16]; + unsigned char macKey[SHA256_DIGEST_LENGTH]; + unsigned char iv[16]; + unsigned char aadUsed[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char aadClean[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char in[64]; + unsigned char usedOut[64]; + unsigned char cleanOut[64]; + + (void)data; + + XMEMSET(key, 0, sizeof(key)); + XMEMSET(macKey, 0, sizeof(macKey)); + XMEMSET(iv, 0, sizeof(iv)); + XMEMSET(aadUsed, 0, sizeof(aadUsed)); + XMEMSET(in, 0, sizeof(in)); + + aadUsed[9] = (unsigned char)(TLS1_VERSION >> 8); + aadUsed[10] = (unsigned char)TLS1_VERSION; + aadUsed[12] = 16; + XMEMCPY(aadClean, aadUsed, sizeof(aadClean)); + + err = (usedCtx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) + err = (cleanCtx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(usedCtx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(usedCtx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) + err = EVP_Cipher(usedCtx, usedOut, in, 16) != 16; + if (err == 0) + err = EVP_EncryptInit_ex(usedCtx, NULL, e, key, iv) != 1; + if (err == 0) { + err = EVP_EncryptInit_ex(cleanCtx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(cleanCtx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + len = EVP_CIPHER_CTX_ctrl(usedCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aadUsed), aadUsed); + err = len != 48; + } + if (err == 0) { + err = EVP_EncryptInit_ex(usedCtx, NULL, e, NULL, NULL) != 1; + } + if (err == 0) { + len = EVP_CIPHER_CTX_ctrl(usedCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aadUsed), aadUsed); + err = len != 48; + } + if (err == 0) { + len = EVP_CIPHER_CTX_ctrl(cleanCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aadClean), aadClean); + err = len != 48; + } + if (err == 0) + err = EVP_Cipher(usedCtx, usedOut, in, sizeof(in)) != (int)sizeof(in); + if (err == 0) { + err = EVP_Cipher(cleanCtx, cleanOut, in, sizeof(in)) != + (int)sizeof(in); + } + if (err == 0) + err = XMEMCMP(usedOut, cleanOut, sizeof(usedOut)) != 0; + + EVP_CIPHER_CTX_free(usedCtx); + EVP_CIPHER_CTX_free(cleanCtx); + + return err; +} + +/******************************************************************************/ + +int test_aes128_cbc_hmac_tls_bad_length_reset(ENGINE *e, void *data) +{ + int err = 0; + int len; + EVP_CIPHER_CTX *usedCtx = NULL; + EVP_CIPHER_CTX *cleanCtx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher( + e, NID_aes_128_cbc_hmac_sha256); + unsigned char key[16]; + unsigned char macKey[SHA256_DIGEST_LENGTH]; + unsigned char iv[16]; + unsigned char aad[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char in[64]; + unsigned char usedOut[64]; + unsigned char cleanOut[64]; + + (void)data; + + XMEMSET(key, 0, sizeof(key)); + XMEMSET(macKey, 0, sizeof(macKey)); + XMEMSET(iv, 0, sizeof(iv)); + XMEMSET(in, 0, sizeof(in)); + + err = (usedCtx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = (cleanCtx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_EncryptInit_ex(usedCtx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(usedCtx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(cleanCtx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(cleanCtx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + XMEMSET(aad, 0, sizeof(aad)); + aad[9] = (unsigned char)(TLS1_VERSION >> 8); + aad[10] = (unsigned char)TLS1_VERSION; + aad[12] = 16; + len = EVP_CIPHER_CTX_ctrl(usedCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad); + err = len != 48; + } + if (err == 0) { + err = EVP_Cipher(usedCtx, usedOut, in, 48) >= 0; + } + if (err == 0) { + XMEMSET(aad, 0, sizeof(aad)); + aad[9] = (unsigned char)(TLS1_VERSION >> 8); + aad[10] = (unsigned char)TLS1_VERSION; + aad[12] = 16; + len = EVP_CIPHER_CTX_ctrl(usedCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad); + err = len != 48; + } + if (err == 0) { + XMEMSET(aad, 0, sizeof(aad)); + aad[9] = (unsigned char)(TLS1_VERSION >> 8); + aad[10] = (unsigned char)TLS1_VERSION; + aad[12] = 16; + len = EVP_CIPHER_CTX_ctrl(cleanCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad), aad); + err = len != 48; + } + if (err == 0) { + err = EVP_Cipher(usedCtx, usedOut, in, sizeof(in)) != (int)sizeof(in); + } + if (err == 0) { + err = EVP_Cipher(cleanCtx, cleanOut, in, sizeof(in)) != + (int)sizeof(in); + } + if (err == 0) { + err = XMEMCMP(usedOut, cleanOut, sizeof(usedOut)) != 0; + } + + EVP_CIPHER_CTX_free(usedCtx); + EVP_CIPHER_CTX_free(cleanCtx); + + return err; +} + +/******************************************************************************/ + +int test_aes128_cbc_hmac_encrypt_error(ENGINE *e, void *data) +{ + int err = 0; + int outLen = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher( + e, NID_aes_128_cbc_hmac_sha256); + unsigned char in[16]; + unsigned char out[16]; + + (void)data; + + XMEMSET(in, 0, sizeof(in)); + + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, cipher, e, NULL, NULL) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, out, &outLen, in, sizeof(in)) != 0; + } + + EVP_CIPHER_CTX_free(ctx); + + return err; +} + +/******************************************************************************/ + +int test_aes128_cbc_hmac_ctrl_error(ENGINE *e, void *data) +{ + int err = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher( + e, NID_aes_128_cbc_hmac_sha256); + unsigned char aad[EVP_AEAD_TLS1_AAD_LEN]; + + (void)data; + + XMEMSET(aad, 0, sizeof(aad)); + + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, cipher, e, NULL, NULL) != 1; + } + if (err == 0) { + ERR_clear_error(); + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(aad) - 1, aad) != 0; + } + if (err == 0) + err = ERR_peek_last_error() != 0; + + EVP_CIPHER_CTX_free(ctx); + + return err; +} + +/******************************************************************************/ + +int test_aes128_cbc_hmac_tls_empty(ENGINE *e, void *data) +{ + int err = 0; + int len; + int engineLen = 0; + int finalLen = 0; + int i; + EVP_CIPHER_CTX *engineCtx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher( + e, NID_aes_128_cbc_hmac_sha256); + unsigned int macLen = 0; + unsigned char key[16]; + unsigned char macKey[SHA256_DIGEST_LENGTH]; + unsigned char iv[16]; + unsigned char engineAAD[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char rejectedAAD[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char plain[48]; + unsigned char in[48]; + unsigned char expected[48]; + unsigned char engineOut[80]; + + (void)data; + + XMEMSET(key, 0, sizeof(key)); + XMEMSET(macKey, 0, sizeof(macKey)); + XMEMSET(iv, 0, sizeof(iv)); + XMEMSET(engineAAD, 0, sizeof(engineAAD)); + XMEMSET(plain, 0, sizeof(plain)); + XMEMSET(in, 0, sizeof(in)); + XMEMSET(engineOut, 0xa5, sizeof(engineOut)); + + engineAAD[9] = (unsigned char)(TLS1_VERSION >> 8); + engineAAD[10] = (unsigned char)TLS1_VERSION; + + if (err == 0) { + err = HMAC(EVP_sha256(), macKey, sizeof(macKey), engineAAD, + sizeof(engineAAD), plain, &macLen) == NULL; + } + if (err == 0) + err = macLen != SHA256_DIGEST_LENGTH; + if (err == 0) { + XMEMSET(plain + macLen, 15, sizeof(plain) - macLen); + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, plain, + sizeof(plain), expected, 0); + } + if (err == 0) + err = (engineCtx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(engineCtx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(engineCtx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + len = EVP_CIPHER_CTX_ctrl(engineCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(engineAAD), engineAAD); + err = len != (int)sizeof(in); + } + if (err == 0) { + XMEMCPY(rejectedAAD, engineAAD, sizeof(rejectedAAD)); + rejectedAAD[9] = (unsigned char)(TLS1_1_VERSION >> 8); + rejectedAAD[10] = (unsigned char)TLS1_1_VERSION; + err = EVP_CIPHER_CTX_ctrl(engineCtx, EVP_CTRL_AEAD_TLS1_AAD, + sizeof(rejectedAAD), rejectedAAD) != 0; + } + if (err == 0) { + err = EVP_Cipher(engineCtx, engineOut, in, 0) >= 0; + } + if (err == 0) { + err = EVP_Cipher(engineCtx, engineOut, in, AES_BLOCK_SIZE) >= 0; + } + if (err == 0) { + err = EVP_Cipher(engineCtx, engineOut, in, + 2 * AES_BLOCK_SIZE) >= 0; + } + for (i = 0; (err == 0) && (i < (int)sizeof(engineOut)); i++) { + err = engineOut[i] != 0xa5; + } + if (err == 0) { + err = EVP_EncryptUpdate(engineCtx, engineOut, &engineLen, in, + sizeof(in)) != 1; + } + if (err == 0) + err = engineLen != (int)sizeof(expected); + if (err == 0) + err = XMEMCMP(expected, engineOut, sizeof(expected)) != 0; + if (err == 0) { + err = EVP_EncryptFinal_ex(engineCtx, engineOut + engineLen, + &finalLen) != 1; + } + if (err == 0) + err = finalLen != 0; + for (i = engineLen; (err == 0) && (i < (int)sizeof(engineOut)); i++) { + err = engineOut[i] != 0xa5; + } + + EVP_CIPHER_CTX_free(engineCtx); + + return err; +} + +/******************************************************************************/ + +int test_aes128_cbc_hmac_reinit_state(ENGINE *e, void *data) +{ + int err = 0; + int len; + unsigned int macLen = 0; + EVP_CIPHER_CTX *ctx = NULL; + const EVP_CIPHER *cipher = ENGINE_get_cipher( + e, NID_aes_128_cbc_hmac_sha256); + unsigned char key[16]; + unsigned char macKey[SHA256_DIGEST_LENGTH]; + unsigned char iv[16]; + unsigned char aad[EVP_AEAD_TLS1_AAD_LEN]; + unsigned char in[16]; + unsigned char enc[16]; + unsigned char mac[SHA256_DIGEST_LENGTH]; + unsigned char out[sizeof(in) + sizeof(mac)]; + + (void)data; + + XMEMSET(key, 0, sizeof(key)); + XMEMSET(macKey, 0, sizeof(macKey)); + XMEMSET(iv, 0, sizeof(iv)); + XMEMSET(aad, 0, sizeof(aad)); + XMEMSET(in, 0, sizeof(in)); + XMEMSET(out, 0, sizeof(out)); + + err = test_cipher_enc(NULL, EVP_aes_128_cbc(), key, iv, in, sizeof(in), + enc, 0); + if (err == 0) { + err = HMAC(EVP_sha256(), macKey, sizeof(macKey), in, sizeof(in), mac, + &macLen) == NULL; + } + if (err == 0) + err = macLen != sizeof(mac); + + aad[9] = (unsigned char)(TLS1_1_VERSION >> 8); + aad[10] = (unsigned char)TLS1_1_VERSION; + aad[12] = sizeof(in); + + if (err == 0) + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, + sizeof(macKey), macKey) != 1; + } + if (err == 0) { + len = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, sizeof(aad), + aad); + err = len != SHA256_DIGEST_LENGTH; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + XMEMCPY(out + sizeof(in), mac, sizeof(mac)); + err = EVP_Cipher(ctx, out, enc, sizeof(enc)) != (int)sizeof(in); + } + if (err == 0) + err = XMEMCMP(out, in, sizeof(in)) != 0; + + EVP_CIPHER_CTX_free(ctx); + + return err; +} + +/******************************************************************************/ + +int test_aes128_cbc_hmac_cleanup(ENGINE *e, void *data) { - /* Stitched AES-CBC-HMAC is not a FIPS-validated cipher, so this path is - * not exercised under FIPS. */ - (void)e; + int err = 0; + EVP_CIPHER_CTX *ctx = NULL; + EVP_CIPHER_CTX *copyCtx = NULL; + const EVP_CIPHER *cipher; + unsigned char key[16]; + unsigned char iv[16]; + (void)data; - return 0; -} + + cipher = ENGINE_get_cipher(e, NID_aes_128_cbc_hmac_sha256); + err = cipher == NULL; + if (err == 0) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + err = EVP_CIPHER_meth_get_cleanup(cipher) == NULL; +#else + err = cipher->cleanup == NULL; #endif + } + + XMEMSET(key, 0, sizeof(key)); + XMEMSET(iv, 0, sizeof(iv)); + + if (err == 0) + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) + err = (copyCtx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) + err = EVP_CIPHER_CTX_copy(copyCtx, ctx) != 0; + EVP_CIPHER_CTX_free(copyCtx); + EVP_CIPHER_CTX_free(ctx); + + return err; +} #endif /* WE_HAVE_AESCBC */ /******************************************************************************/ #ifdef WE_HAVE_AESCTR +static int test_aes_ctr_copy(ENGINE *e, const EVP_CIPHER *cipher) +{ + const int offsets[] = { 0, 1, 15, 16, 17, 33 }; + unsigned char key[32] = { 1 }; + unsigned char nextKey[32] = { 2 }; + unsigned char iv[16]; + unsigned char in[64] = { 3 }; + unsigned char out[80]; + unsigned char expected[80]; + EVP_CIPHER_CTX *src = NULL, *copy = NULL; + EVP_CIPHER_CTX *ref = NULL, *copyRef = NULL; + int err = 0, enc, order, stage, i, outLen, expectedLen; + + XMEMSET(iv, 0xff, sizeof(iv)); + PRINT_MSG("Copy AES-CTR at block and partial-block positions"); + for (enc = 0; err == 0 && enc < 2; enc++) { + for (order = 0; err == 0 && order < 2; order++) { + for (i = 0; err == 0 && i < (int)(sizeof(offsets) / + sizeof(offsets[0])); i++) { + src = EVP_CIPHER_CTX_new(); + copy = EVP_CIPHER_CTX_new(); + ref = EVP_CIPHER_CTX_new(); + copyRef = EVP_CIPHER_CTX_new(); + if (src == NULL || copy == NULL || ref == NULL || + copyRef == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_CipherInit_ex(src, cipher, e, key, iv, enc) != 1 || + EVP_CipherInit_ex(copy, cipher, e, nextKey, iv, + enc) != 1 || + EVP_CipherInit_ex(ref, cipher, NULL, key, iv, enc) != 1; + } + if (err == 0) { + err = EVP_CipherUpdate(src, out, &outLen, in, + offsets[i]) != 1 || + EVP_CipherUpdate(ref, expected, &expectedLen, in, + offsets[i]) != 1; + } + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0 || + EVP_CIPHER_CTX_copy(copy, src) != 1 || + EVP_CIPHER_CTX_copy(copyRef, ref) != 1; + } + if (err == 0) { + err = EVP_CipherInit_ex(src, NULL, NULL, nextKey, iv, + enc) != 1 || + EVP_CipherInit_ex(ref, NULL, NULL, nextKey, iv, + enc) != 1; + } + if (order == 0) { + EVP_CIPHER_CTX_free(src); + src = NULL; + } + if (err == 0) { + err = EVP_CipherUpdate(copy, out, &outLen, in, + sizeof(in)) != 1 || + EVP_CipherUpdate(copyRef, expected, &expectedLen, in, + sizeof(in)) != 1; + } + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0; + } + EVP_CIPHER_CTX_free(copy); + copy = NULL; + if (err == 0 && order == 1) { + err = EVP_CipherUpdate(src, out, &outLen, in, + sizeof(in)) != 1 || + EVP_CipherUpdate(ref, expected, &expectedLen, in, + sizeof(in)) != 1; + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0; + } + } + EVP_CIPHER_CTX_free(src); + EVP_CIPHER_CTX_free(ref); + EVP_CIPHER_CTX_free(copyRef); + src = ref = copyRef = NULL; + } + } + } + PRINT_MSG("Copy AES-CTR before setting the key"); + for (stage = 0; err == 0 && stage < 2; stage++) { + src = EVP_CIPHER_CTX_new(); + copy = EVP_CIPHER_CTX_new(); + ref = EVP_CIPHER_CTX_new(); + if (src == NULL || copy == NULL || ref == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_CipherInit_ex(src, cipher, e, NULL, + stage ? iv : NULL, 1) != 1 || + EVP_CIPHER_CTX_copy(copy, src) != 1 || + EVP_CipherInit_ex(copy, NULL, NULL, key, + stage ? NULL : iv, 1) != 1 || + EVP_CipherInit_ex(ref, cipher, NULL, key, iv, 1) != 1; + } + if (err == 0) { + err = EVP_CipherUpdate(copy, out, &outLen, in, sizeof(in)) != 1 || + EVP_CipherUpdate(ref, expected, &expectedLen, in, + sizeof(in)) != 1; + } + if (err == 0) { + err = outLen != expectedLen || + XMEMCMP(out, expected, outLen) != 0; + } + EVP_CIPHER_CTX_free(src); + EVP_CIPHER_CTX_free(copy); + EVP_CIPHER_CTX_free(ref); + src = copy = ref = NULL; + } + return err; +} + int test_aes128_ctr_stream(ENGINE *e, void *data) { int err; @@ -594,6 +2191,8 @@ int test_aes128_ctr_stream(ENGINE *e, void *data) err = test_stream_enc_dec(e, data, EVP_aes_128_ctr(), 16, 16, 16, 0); if (err == 0) err = test_stream_enc_dec(e, data, EVP_aes_128_ctr(), 16, 16, 1, 0); + if (err == 0) + err = test_aes_ctr_copy(e, EVP_aes_128_ctr()); return err; } @@ -607,6 +2206,8 @@ int test_aes192_ctr_stream(ENGINE *e, void *data) err = test_stream_enc_dec(e, data, EVP_aes_192_ctr(), 24, 16, 15, 0); if (err == 0) err = test_stream_enc_dec(e, data, EVP_aes_128_ctr(), 16, 16, 2, 0); + if (err == 0) + err = test_aes_ctr_copy(e, EVP_aes_192_ctr()); return err; } @@ -620,6 +2221,8 @@ int test_aes256_ctr_stream(ENGINE *e, void *data) err = test_stream_enc_dec(e, data, EVP_aes_256_ctr(), 32, 16, 14, 0); if (err == 0) err = test_stream_enc_dec(e, data, EVP_aes_256_ctr(), 32, 16, 3, 0); + if (err == 0) + err = test_aes_ctr_copy(e, EVP_aes_256_ctr()); return err; } @@ -774,6 +2377,11 @@ int test_aes_ctr_leftover_data_regression(ENGINE *e, void *data) int test_aes_ctr_iv_init_regression(ENGINE *e, void *data) { int err = 0; + int outLen; +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + const EVP_CIPHER* cipher; + EVP_CIPHER_CTX* copyCtx = NULL; +#endif unsigned char iv[AES_BLOCK_SIZE]; unsigned char key[16]; EVP_CIPHER_CTX* encCtx = NULL; @@ -812,9 +2420,35 @@ int test_aes_ctr_iv_init_regression(ENGINE *e, void *data) if (err == 0) { err = EVP_CipherInit_ex(decCtx, EVP_aes_128_ctr(), e, NULL, iv, 0) != 1; } + if (err == 0) { + err = EVP_CIPHER_CTX_iv_length(decCtx) != (int)sizeof(iv); + } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (err == 0) { + cipher = EVP_CIPHER_CTX_cipher(decCtx); + err = (cipher == NULL) || + (EVP_CIPHER_meth_get_cleanup(cipher) == NULL); + } +#endif if (err == 0) { err = EVP_CipherInit_ex(decCtx, NULL, e, key, NULL, -1) != 1; } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (err == 0) { + err = (copyCtx = EVP_CIPHER_CTX_new()) == NULL; + } + if (err == 0) { + err = EVP_CIPHER_CTX_copy(copyCtx, decCtx) != 1; + } + if (err == 0) { + ERR_clear_error(); + } +#endif + + if (err == 0) { + outLen = EVP_Cipher(decCtx, decText, decText, 0); + err = outLen != 0; + } /* Encrypt. */ if (err == 0) { @@ -835,9 +2469,338 @@ int test_aes_ctr_iv_init_regression(ENGINE *e, void *data) EVP_CIPHER_CTX_free(encCtx); if (decCtx != NULL) EVP_CIPHER_CTX_free(decCtx); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (copyCtx != NULL) + EVP_CIPHER_CTX_free(copyCtx); +#endif return err; } #endif /* WE_HAVE_AESCTR */ +#ifdef WE_HAVE_AESCCM + +static int test_ccm_keyed_roundtrip(ENGINE *e, const EVP_CIPHER *cipher) +{ + int err = 0; + int len = 0; + int finalLen = 0; + int lengthRet = 1; + const unsigned char msg[] = "Test pattern"; + static const unsigned char aad[] = { 0x01, 0x02, 0x03, 0x04, 0x05 }; + unsigned char key[32] = {0}; + unsigned char iv[13] = {0}; + unsigned char enc[sizeof(msg)]; + unsigned char dec[sizeof(msg)]; + unsigned char tag[16]; + unsigned char nextTag[sizeof(tag)]; + EVP_CIPHER_CTX *ctx = NULL; + EVP_CIPHER_CTX *copy = NULL; + +#if OPENSSL_VERSION_NUMBER < 0x1010103fL + /* Native OpenSSL before 1.1.1c needs a tag for length setup. */ + lengthRet = e != NULL; +#endif + + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, cipher, e, NULL, NULL) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, + sizeof(iv), NULL) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, + sizeof(tag), NULL) != 1; + } + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if ((err == 0) && (e != NULL)) { + err = (copy = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + PRINT_MSG("CCM engine contexts reject copying"); + err = EVP_CIPHER_CTX_copy(copy, ctx) != 0; + } + } + if (err == 0) { + PRINT_MSG("CCM encryption tags require a completed operation"); + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + sizeof(tag), tag) != 0; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, NULL, &len, NULL, sizeof(msg)) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, NULL, &len, aad, sizeof(aad)) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, enc, &len, msg, sizeof(msg)) != 1; + } + if (err == 0) { + err = len != (int)sizeof(msg); + } + if (err == 0) { + err = EVP_EncryptFinal_ex(ctx, enc + len, &finalLen) != 1; + } + if (err == 0) { + err = finalLen != 0; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + sizeof(tag), tag) != 1; + } + if (err == 0) { + unsigned char unused[sizeof(tag)]; + + PRINT_MSG("CCM encryption tags are exported once per operation"); + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + sizeof(unused), unused) != 0; + } + if (err == 0) { + PRINT_MSG("Reinitialize CCM for a keyed decrypt roundtrip"); + err = EVP_DecryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, NULL, &len, NULL, sizeof(enc)) != lengthRet; + } + if (err == 0) { + PRINT_MSG("CCM decryption requires an authentication tag"); + err = EVP_DecryptUpdate(ctx, dec, &len, enc, sizeof(enc)) != 0; + } + if (err == 0) { + err = EVP_DecryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, + sizeof(tag), tag) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, NULL, &len, NULL, sizeof(enc)) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, NULL, &len, aad, sizeof(aad)) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, dec, &len, enc, sizeof(enc)) != 1; + } + if (err == 0) { + err = (len != (int)sizeof(msg)) || + (XMEMCMP(dec, msg, sizeof(msg)) != 0); + } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L + /* Older OpenSSL clears CCM tag state before finalization. */ + if (err == 0) { + err = EVP_DecryptFinal_ex(ctx, dec + len, &finalLen) != 1; + } + if (err == 0) { + err = finalLen != 0; + } +#endif + if (err == 0) { + PRINT_MSG("CCM decrypt contexts do not export encryption tags"); + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + sizeof(tag), tag) != 0; + } + + if (err == 0) { + PRINT_MSG("Reinitialize CCM for keyed encryption"); + err = EVP_EncryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, NULL, &len, NULL, sizeof(msg)) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, NULL, &len, aad, sizeof(aad)) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, dec, &len, msg, sizeof(msg)) != 1; + } + if (err == 0) { + err = (len != (int)sizeof(msg)) || + (XMEMCMP(dec, enc, sizeof(enc)) != 0); + } + if (err == 0) { + err = EVP_EncryptFinal_ex(ctx, dec + len, &finalLen) != 1; + } + if (err == 0) { + err = finalLen != 0; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + sizeof(nextTag), nextTag) != 1; + } + if (err == 0) { + err = XMEMCMP(nextTag, tag, sizeof(tag)) != 0; + } + + EVP_CIPHER_CTX_free(ctx); + EVP_CIPHER_CTX_free(copy); + return err; +} + +int test_aes_ccm_keyed_reinit(ENGINE *e, void *data) +{ + int err; + + (void)data; + + err = test_ccm_keyed_roundtrip(NULL, EVP_aes_128_ccm()); + if (err == 0) + err = test_ccm_keyed_roundtrip(e, EVP_aes_128_ccm()); + if (err == 0) + err = test_ccm_keyed_roundtrip(NULL, EVP_aes_192_ccm()); + if (err == 0) + err = test_ccm_keyed_roundtrip(e, EVP_aes_192_ccm()); + if (err == 0) + err = test_ccm_keyed_roundtrip(NULL, EVP_aes_256_ccm()); + if (err == 0) + err = test_ccm_keyed_roundtrip(e, EVP_aes_256_ccm()); + + return err; +} + +#endif /* WE_HAVE_AESCCM */ + +#ifdef WE_HAVE_AESGCM + +static int test_gcm_keyed_roundtrip(ENGINE *e, const EVP_CIPHER *cipher) +{ + int err; + int len = 0; + int finalLen = 0; + const unsigned char msg[] = "Test pattern"; + static const unsigned char aad[] = { 0x01, 0x02, 0x03, 0x04, 0x05 }; + unsigned char badAad[sizeof(aad)]; + unsigned char key[32] = {0}; + unsigned char iv[12] = {0}; + unsigned char enc[sizeof(msg)]; + unsigned char dec[sizeof(msg)]; + unsigned char tag[16]; + unsigned char nextTag[sizeof(tag)]; + EVP_CIPHER_CTX *ctx = NULL; + + XMEMCPY(badAad, aad, sizeof(aad)); + badAad[0] ^= 0x80; + + err = (ctx = EVP_CIPHER_CTX_new()) == NULL; + if (err == 0) { + err = EVP_EncryptInit_ex(ctx, cipher, e, key, iv) != 1; + } + if (err == 0) { + PRINT_MSG("GCM appends AAD through a NULL output buffer"); + err = EVP_EncryptUpdate(ctx, NULL, &len, aad, sizeof(aad)) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, enc, &len, msg, sizeof(msg)) != 1; + } + if (err == 0) { + err = len != (int)sizeof(msg); + } + if (err == 0) { + err = EVP_EncryptFinal_ex(ctx, enc + len, &finalLen) != 1; + } + if (err == 0) { + err = finalLen != 0; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + sizeof(tag), tag) != 1; + } + + if (err == 0) { + PRINT_MSG("Reinitialize GCM for a keyed decrypt roundtrip"); + err = EVP_DecryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, + sizeof(tag), tag) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, NULL, &len, aad, sizeof(aad)) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, dec, &len, enc, sizeof(enc)) != 1; + } + /* The engine releases GCM plaintext only once the tag verifies. */ + if (err == 0) { + err = EVP_DecryptFinal_ex(ctx, dec + len, &finalLen) != 1; + } + if (err == 0) { + err = (len + finalLen != (int)sizeof(msg)) || + (XMEMCMP(dec, msg, sizeof(msg)) != 0); + } + + if (err == 0) { + PRINT_MSG("GCM decryption authenticates the appended AAD"); + err = EVP_DecryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, + sizeof(tag), tag) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, NULL, &len, badAad, sizeof(badAad)) != 1; + } + if (err == 0) { + err = EVP_DecryptUpdate(ctx, dec, &len, enc, sizeof(enc)) != 1; + } + if (err == 0) { + err = EVP_DecryptFinal_ex(ctx, dec + len, &finalLen) > 0; + } + + if (err == 0) { + PRINT_MSG("Reinitialize GCM for keyed encryption"); + err = EVP_EncryptInit_ex(ctx, NULL, e, key, iv) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, NULL, &len, aad, sizeof(aad)) != 1; + } + if (err == 0) { + err = EVP_EncryptUpdate(ctx, dec, &len, msg, sizeof(msg)) != 1; + } + /* The engine's one-shot GCM writes buffered output at finalization. */ + if (err == 0) { + err = EVP_EncryptFinal_ex(ctx, dec + len, &finalLen) != 1; + } + if (err == 0) { + err = (len + finalLen != (int)sizeof(msg)) || + (XMEMCMP(dec, enc, sizeof(enc)) != 0); + } + if (err == 0) { + err = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, + sizeof(nextTag), nextTag) != 1; + } + if (err == 0) { + err = XMEMCMP(nextTag, tag, sizeof(tag)) != 0; + } + + EVP_CIPHER_CTX_free(ctx); + return err; +} + +int test_aes_gcm_keyed_reinit(ENGINE *e, void *data) +{ + int err; + + (void)data; + + err = test_gcm_keyed_roundtrip(NULL, EVP_aes_128_gcm()); + if (err == 0) + err = test_gcm_keyed_roundtrip(e, EVP_aes_128_gcm()); + if (err == 0) + err = test_gcm_keyed_roundtrip(NULL, EVP_aes_192_gcm()); + if (err == 0) + err = test_gcm_keyed_roundtrip(e, EVP_aes_192_gcm()); + if (err == 0) + err = test_gcm_keyed_roundtrip(NULL, EVP_aes_256_gcm()); + if (err == 0) + err = test_gcm_keyed_roundtrip(e, EVP_aes_256_gcm()); + + return err; +} + +#endif /* WE_HAVE_AESGCM */ + diff --git a/test/test_cmac.c b/test/test_cmac.c index 587eb9ce..76326089 100644 --- a/test/test_cmac.c +++ b/test/test_cmac.c @@ -20,14 +20,81 @@ */ #include "unit.h" +#include #undef AES_BLOCK_SIZE #ifndef WOLFENGINE_USER_SETTINGS #include #endif #include +#include +#include #ifdef WE_HAVE_CMAC +#ifdef WOLFENGINE_DEBUG +static char cmacLog[WOLFENGINE_MAX_LOG_WIDTH]; +#ifndef TEST_MULTITHREADED +static int cmacWolfCryptBackend; +#endif + +static void test_cmac_logging_cb(const int level, const int component, + const char *const message) +{ + (void)component; + + if ((level == WE_LOG_ERROR) && (XSTRSTR(message, "wc_InitCmac") != NULL)) { + XSTRNCPY(cmacLog, message, sizeof(cmacLog) - 1); + cmacLog[sizeof(cmacLog) - 1] = '\0'; + } + #ifndef TEST_MULTITHREADED + if ((level == WE_LOG_INFO) && + (XSTRCMP(message, "CMAC backend: wolfCrypt") == 0)) { + cmacWolfCryptBackend = 1; + } + #endif +} +#endif + +static int test_cmac_ctrl_str(ENGINE *e) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if ((err == 0) && (e != NULL)) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "cipher", "aes-128-ecb") > 0; + } + if ((err == 0) && (e != NULL)) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "cipher", "aes-256-cbc") != 1; + } + if ((err == 0) && (e != NULL)) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "hexkey", + "000102030405060708090a0b0c0d0e0f") > 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "cipher", "aes-128-cbc") != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "hexkey", + "000102030405060708090a0b0c0d0e0f") != 1; + } + if (err == 0) { + err = EVP_PKEY_keygen(ctx, &pkey) != 1; + } + + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(ctx); + + return err; +} + static int test_cmac_generation(ENGINE *e, const EVP_CIPHER *c, unsigned char *key, int keySz, unsigned char *msg, int len, unsigned char *out, int *outLen) @@ -132,6 +199,135 @@ static int test_cmac_create_helper(ENGINE *e, unsigned char *in, return ret; } +static int test_cmac_bad_cipher(ENGINE *e) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_CIPHER, 0, (void *)EVP_aes_128_ecb()) > 0; + } + + EVP_PKEY_CTX_free(ctx); + + return err; +} + +static int test_cmac_cleanup(ENGINE *e) +{ +#if !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) + int err = 0; + unsigned char key[16] = { 0 }; + unsigned char msg[16] = { 1 }; + EVP_MD_CTX *ctx = NULL; + EVP_PKEY_CTX *pctx = NULL; + EVP_PKEY_CTX *signCtx = NULL; + EVP_PKEY *pkey = NULL; + void *mac = NULL; + + ctx = EVP_MD_CTX_new(); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + err = pctx == NULL; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(pctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_CIPHER, 0, (void *)EVP_aes_128_cbc()) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), key) != 1; + } + if (err == 0) { + err = EVP_PKEY_keygen(pctx, &pkey) != 1; + } + if (err == 0) { + err = EVP_DigestSignInit(ctx, &signCtx, NULL, e, pkey) != 1; + } + if (err == 0) { + err = EVP_DigestSignUpdate(ctx, msg, sizeof(msg)) != 1; + } + if (err == 0) { + mac = EVP_PKEY_CTX_get_data(signCtx); + err = mac == NULL; + } + if (err == 0) { + test_openssl_mem_expect_clear(mac); + } + + EVP_MD_CTX_free(ctx); + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(pctx); + + if (err == 0) { + err = test_openssl_mem_clear_result() != 1; + } + + return err; +#else + (void)e; + return 0; +#endif +} + +static int test_cmac_failed_copy_cleanup(ENGINE *e) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) + int err = 0; + unsigned char key = 1; + size_t allocations; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY_CTX *copy = NULL; + + if (!test_openssl_mem_has_source()) { + PRINT_MSG("Skipping allocation-callsite check without source filenames"); + return 0; + } + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), &key) != 1; + } + if (err == 0) { + allocations = test_openssl_mem_active(); + test_openssl_mem_expect_next_clear(sizeof(key) + 1); + copy = EVP_PKEY_CTX_dup(ctx); + err = (copy != NULL) || + (test_openssl_mem_active() != allocations) || + (test_openssl_mem_clear_result() != 1); + } + + EVP_PKEY_CTX_free(copy); + EVP_PKEY_CTX_free(ctx); + + return err; +#else + (void)e; + return 0; +#endif +} + int test_cmac_create(ENGINE *e, void *data) { int ret = 0; @@ -156,8 +352,25 @@ int test_cmac_create(ENGINE *e, void *data) PRINT_MSG("Testing with 256 bit KEY"); keySz = 32; - ret = test_cmac_create_helper(e, in, inSz, key, keySz, - EVP_aes_256_cbc(), flags); +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) + cmacWolfCryptBackend = 0; + ret = wolfEngine_SetLoggingCb(test_cmac_logging_cb) != 0; + ret |= wolfEngine_SetLogLevel(WE_LOG_INFO) != 0; + ret |= wolfEngine_SetLogComponents(WE_LOG_MAC) != 0; + ret |= wolfEngine_Debugging_ON() != 0; +#endif + if (ret == 0) { + ret = test_cmac_create_helper(e, in, inSz, key, keySz, + EVP_aes_256_cbc(), flags); + } +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) + wolfEngine_Debugging_OFF(); + wolfEngine_SetLoggingCb(NULL); + wolfEngine_SetLogLevel(WE_LOG_LEVEL_DEFAULT); + wolfEngine_SetLogComponents(WE_LOG_COMPONENTS_DEFAULT); + if ((ret == 0) && (!cmacWolfCryptBackend)) + ret = -1; +#endif if (ret == 0) { PRINT_MSG("Testing with 128 bit KEY"); @@ -172,10 +385,388 @@ int test_cmac_create(ENGINE *e, void *data) ret = test_cmac_create_helper(e, in, inSz, key, keySz, EVP_aes_192_cbc(), flags); } + if (ret == 0) { + ret = test_cmac_bad_cipher(e); + } + if (ret == 0) { + ret = test_cmac_cleanup(e); + } + if (ret == 0) { + ret = test_cmac_failed_copy_cleanup(e); + } + if (ret == 0) { + PRINT_MSG("Testing string key and cipher controls"); + ret = test_cmac_ctrl_str(NULL); + } + if (ret == 0) { + ret = test_cmac_ctrl_str(e); + } + + return ret; +} + +int test_cmac_output_size(ENGINE *e, void *data) +{ + int ret = 0; + int i; + unsigned char key[16] = { 0 }; + unsigned char msg[] = "Test message"; + unsigned char mac[WC_CMAC_TAG_MAX_SZ]; + size_t macLen = 1; + EVP_MD_CTX *ctx = NULL; + EVP_PKEY_CTX *pctx = NULL; + EVP_PKEY *pkey = NULL; + + (void)data; + XMEMSET(mac, 0xa5, sizeof(mac)); + + ctx = EVP_MD_CTX_new(); + if (ctx == NULL) + ret = -1; + if (ret == 0) { + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (pctx == NULL) + ret = -1; + } + if (ret == 0) + ret = EVP_PKEY_keygen_init(pctx) != 1; + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_CIPHER, 0, (void*)EVP_aes_128_cbc()) != 1; + } + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), key) != 1; + } + if (ret == 0) + ret = EVP_PKEY_keygen(pctx, &pkey) != 1; + if (ret == 0) + ret = EVP_DigestSignInit(ctx, NULL, NULL, e, pkey) != 1; + if (ret == 0) + ret = EVP_DigestSignUpdate(ctx, msg, sizeof(msg)) != 1; + if (ret == 0) { + if (EVP_DigestSignFinal(ctx, mac, &macLen) == 1) + ret = -1; + } + if ((ret == 0) && (macLen != WC_CMAC_TAG_MAX_SZ)) + ret = -1; + for (i = 0; (ret == 0) && (i < (int)sizeof(mac)); i++) { + if (mac[i] != 0xa5) + ret = -1; + } + + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(pctx); + EVP_MD_CTX_free(ctx); + + return ret; +} + +int test_cmac_update_size(ENGINE *e, void *data) +{ + int ret = 0; + unsigned char key[16] = { 0 }; + unsigned char msg = 0; + EVP_MD_CTX *ctx = NULL; + EVP_PKEY_CTX *pctx = NULL; + EVP_PKEY *pkey = NULL; + + (void)data; + ctx = EVP_MD_CTX_new(); + if (ctx == NULL) + ret = -1; + if (ret == 0) { + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (pctx == NULL) + ret = -1; + } + if (ret == 0) + ret = EVP_PKEY_keygen_init(pctx) != 1; + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_CIPHER, 0, (void*)EVP_aes_128_cbc()) != 1; + } + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), key) != 1; + } + if (ret == 0) + ret = EVP_PKEY_keygen(pctx, &pkey) != 1; + if (ret == 0) + ret = EVP_DigestSignInit(ctx, NULL, NULL, e, pkey) != 1; + if (ret == 0) { + if (sizeof(size_t) > sizeof(word32)) { + size_t updateLen = UINT32_MAX; + + updateLen++; + if (EVP_DigestSignUpdate(ctx, &msg, updateLen) == 1) + ret = -1; + } + } + + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(pctx); + EVP_MD_CTX_free(ctx); + + return ret; +} + +int test_cmac_copy_error(ENGINE *e, void *data) +{ + int ret = 0; +#ifdef WOLFENGINE_DEBUG + unsigned char key = 0; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY_CTX *copy = NULL; + + (void)data; + XMEMSET(cmacLog, 0, sizeof(cmacLog)); + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (ctx == NULL) + ret = -1; + if (ret == 0) + ret = EVP_PKEY_keygen_init(ctx) != 1; + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), &key) != 1; + } + if (ret == 0) { + ret = wolfEngine_SetLoggingCb(test_cmac_logging_cb) != 0; + ret |= wolfEngine_SetLogLevel(WE_LOG_ERROR) != 0; + ret |= wolfEngine_SetLogComponents(WE_LOG_MAC) != 0; + ret |= wolfEngine_Debugging_ON() != 0; + } + if (ret == 0) { + copy = EVP_PKEY_CTX_dup(ctx); + if (copy != NULL) + ret = -1; + } + wolfEngine_Debugging_OFF(); + wolfEngine_SetLoggingCb(NULL); + wolfEngine_SetLogLevel(WE_LOG_LEVEL_DEFAULT); + wolfEngine_SetLogComponents(WE_LOG_COMPONENTS_DEFAULT); + + if ((ret == 0) && (XSTRSTR(cmacLog, "ret = -") == NULL)) + ret = -1; + + EVP_PKEY_CTX_free(copy); + EVP_PKEY_CTX_free(ctx); +#else + (void)e; + (void)data; +#endif + + return ret; +} + +int test_cmac_copy(ENGINE *e, void *data) +{ + int ret = 0; + unsigned char key[16] = { 0 }; + unsigned char prefix[] = "shared prefix"; + unsigned char suffix[] = "original"; + unsigned char msg[] = "shared prefixoriginal"; + unsigned char prefixMac[WC_CMAC_TAG_MAX_SZ]; + unsigned char fullMac[WC_CMAC_TAG_MAX_SZ]; + unsigned char expPrefix[WC_CMAC_TAG_MAX_SZ]; + unsigned char expFull[WC_CMAC_TAG_MAX_SZ]; + size_t prefixMacSz = sizeof(prefixMac); + size_t fullMacSz = sizeof(fullMac); + int expPrefixSz = sizeof(expPrefix); + int expFullSz = sizeof(expFull); + EVP_PKEY_CTX *pctx = NULL; + EVP_PKEY *pkey = NULL; + EVP_MD_CTX *ctx = NULL; + + (void)data; + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (pctx == NULL) + ret = -1; + if (ret == 0) + ret = EVP_PKEY_keygen_init(pctx) != 1; + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_CIPHER, 0, (void*)EVP_aes_128_cbc()) != 1; + } + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), key) != 1; + } + if (ret == 0) + ret = EVP_PKEY_keygen(pctx, &pkey) != 1; + if (ret == 0) { + ctx = EVP_MD_CTX_new(); + if (ctx == NULL) + ret = -1; + } + if (ret == 0) + ret = EVP_DigestSignInit(ctx, NULL, NULL, e, pkey) != 1; + if (ret == 0) { + ret = EVP_DigestSignUpdate(ctx, prefix, sizeof(prefix) - 1) != 1; + } + if (ret == 0) + ret = EVP_DigestSignFinal(ctx, prefixMac, &prefixMacSz) != 1; + if (ret == 0) + ret = EVP_DigestSignUpdate(ctx, suffix, sizeof(suffix) - 1) != 1; + if (ret == 0) + ret = EVP_DigestSignFinal(ctx, fullMac, &fullMacSz) != 1; + if (ret == 0) { + ret = test_cmac_generation(NULL, EVP_aes_128_cbc(), key, sizeof(key), + prefix, sizeof(prefix) - 1, expPrefix, &expPrefixSz); + } + if (ret == 0) { + ret = test_cmac_generation(NULL, EVP_aes_128_cbc(), key, sizeof(key), + msg, sizeof(msg) - 1, expFull, &expFullSz); + } + if ((ret == 0) && ((prefixMacSz != (size_t)expPrefixSz) || + (XMEMCMP(prefixMac, expPrefix, prefixMacSz) != 0))) { + ret = -1; + } + if ((ret == 0) && ((fullMacSz != (size_t)expFullSz) || + (XMEMCMP(fullMac, expFull, fullMacSz) != 0))) { + ret = -1; + } + + EVP_MD_CTX_free(ctx); + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(pctx); + + return ret; +} + +int test_cmac_keygen_reuse(ENGINE *e, void *data) +{ + int ret = 0; + unsigned char key[16] = { 0 }; + unsigned char oldKey[16] = { 1 }; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + CMAC_CTX *cmac = NULL; + EVP_CIPHER_CTX *cipherCtx = NULL; + + (void)data; + pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, oldKey, sizeof(oldKey)); + if (pkey == NULL) + ret = -1; + if (ret == 0) { + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_CMAC, e); + if (ctx == NULL) + ret = -1; + } + if (ret == 0) + ret = EVP_PKEY_keygen_init(ctx) != 1; + if (ret == 0) { + ret = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), key) != 1; + } + if (ret == 0) + ret = EVP_PKEY_keygen(ctx, &pkey) != 1; + if ((ret == 0) && (EVP_PKEY_base_id(pkey) != EVP_PKEY_CMAC)) + ret = -1; + if ((ret == 0) && (e != NULL)) { + cmac = (CMAC_CTX *)EVP_PKEY_get0(pkey); + if (cmac != NULL) + cipherCtx = CMAC_CTX_get0_cipher_ctx(cmac); + if ((cipherCtx == NULL) || + (EVP_CIPHER_CTX_nid(cipherCtx) != NID_cmac)) { + ret = -1; + } + } + + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(ctx); + + return ret; +} + +int test_cmac_unregistered_engine(ENGINE *e, void *data) +{ + int ret = 0; + int removed = 0; + unsigned char key[16] = { 0 }; + unsigned char msg[] = "Test message"; + unsigned char mac[WC_CMAC_TAG_MAX_SZ]; + int macSz = sizeof(mac); + + (void)data; + if (ENGINE_remove(e) != 1) + ret = -1; + else + removed = 1; + if (ret == 0) { + ret = test_cmac_generation(e, EVP_aes_128_cbc(), key, sizeof(key), + msg, sizeof(msg), mac, &macSz); + } + if ((removed == 1) && (ENGINE_add(e) != 1)) + ret = -1; + + return ret; +} + +int test_cmac_asn1_registry(ENGINE *e, void *data) +{ + int ret = 0; + int i; + int count; + const int *nids = NULL; + EVP_PKEY_ASN1_METHOD *method = NULL; + ENGINE_PKEY_ASN1_METHS_PTR methods; + + (void)data; + methods = ENGINE_get_pkey_asn1_meths(e); + if (methods == NULL) + ret = -1; + if (ret == 0) { + count = methods(e, NULL, &nids, 0); + if ((count <= 0) || (nids == NULL)) + ret = -1; + } + for (i = 0; (ret == 0) && (i < count); i++) { + if ((methods(e, &method, NULL, nids[i]) != 1) || (method == NULL)) + ret = -1; + } return ret; } #endif /* WE_HAVE_CMAC */ +#if defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC) +int test_mac_asn1_ownership(ENGINE *e, void *data) +{ + int ret = 0; + int i; + int count; + const int *nids = NULL; + const EVP_PKEY_ASN1_METHOD *globalMethod; + EVP_PKEY_ASN1_METHOD *engineMethod = NULL; + ENGINE_PKEY_ASN1_METHS_PTR methods; + + (void)data; + methods = ENGINE_get_pkey_asn1_meths(e); + if (methods == NULL) + ret = -1; + if (ret == 0) { + count = methods(e, NULL, &nids, 0); + if ((count <= 0) || (nids == NULL)) + ret = -1; + } + for (i = 0; (ret == 0) && (i < count); i++) { + if ((methods(e, &engineMethod, NULL, nids[i]) != 1) || + (engineMethod == NULL)) { + ret = -1; + } + if (ret == 0) { + globalMethod = EVP_PKEY_asn1_find(NULL, nids[i]); + if (globalMethod == engineMethod) + ret = -1; + } + } + + return ret; +} + +#endif /* WE_HAVE_HMAC || WE_HAVE_CMAC */ + diff --git a/test/test_cmac_compat.c b/test/test_cmac_compat.c new file mode 100644 index 00000000..a1fd59b6 --- /dev/null +++ b/test/test_cmac_compat.c @@ -0,0 +1,119 @@ +/* Exercise cleanup ownership independently of the installed backend layout. */ +#include +#include +#include + +/* Each build models one backend layout, independent of engine flags. */ +#undef HAVE_FIPS +#undef HAVE_FIPS_VERSION +#undef WE_NO_CMAC_FREE +#undef WE_CMAC_HAS_BUFFERED_STATE +#if defined(WE_TEST_CMAC_INLINE) || defined(WE_TEST_CMAC_BUFFERED) +#define WE_NO_CMAC_FREE +#endif +#ifdef WE_TEST_CMAC_BUFFERED +#define WE_CMAC_HAS_BUFFERED_STATE +#endif + +typedef struct Cmac { + unsigned int aes; +#if !defined(WE_TEST_CMAC_INLINE) + unsigned char *msg; + size_t len; +#endif +} Cmac; + +static int aesFreed; +static int bufferFreed; +static int bufferCleared = 1; + +static void test_cleanse(void *ptr, size_t len) +{ + volatile unsigned char *p = (volatile unsigned char *)ptr; + + while (len-- != 0) + *p++ = 0; +} + +#define OPENSSL_cleanse test_cleanse + +static void wc_AesFree(unsigned int *aes) +{ + if (*aes == 1) + aesFreed++; + *aes = 0; +} + +#if !defined(WE_TEST_CMAC_INLINE) +static void test_free(void *ptr, void *heap, int type) +{ + const unsigned char *p = (const unsigned char *)ptr; + size_t i; + + if ((heap != NULL) || (type != 1)) + bufferCleared = 0; + for (i = 0; i < 16; i++) { + if (p[i] != 0) + bufferCleared = 0; + } + bufferFreed++; + free(ptr); +} + +#define DYNAMIC_TYPE_TMP_BUFFER 1 +#define XFREE(ptr, heap, type) test_free((ptr), (heap), (type)) +#endif + +#if !defined(WE_NO_CMAC_FREE) +static int wc_CmacFree(Cmac *cmac) +{ + OPENSSL_cleanse(cmac->msg, cmac->len); + XFREE(cmac->msg, NULL, DYNAMIC_TYPE_TMP_BUFFER); + wc_AesFree(&cmac->aes); + OPENSSL_cleanse(cmac, sizeof(*cmac)); + return 0; +} +#endif + +#include "../src/we_cmac_compat.h" + +int main(void) +{ + Cmac cmac; + const unsigned char *p = (const unsigned char *)&cmac; + size_t i; + int err = 0; +#if !defined(WE_TEST_CMAC_INLINE) + unsigned char *buffer; + + (void)&test_free; + buffer = (unsigned char *)malloc(16); + if (buffer == NULL) + return 1; + memset(buffer, 0xa5, 16); +#endif + + memset(&cmac, 0, sizeof(cmac)); + cmac.aes = 1; +#if !defined(WE_TEST_CMAC_INLINE) + cmac.msg = buffer; + cmac.len = 16; +#endif + we_cmac_free(&cmac); + err = aesFreed != 1; + for (i = 0; i < sizeof(cmac); i++) { + if (p[i] != 0) + err = 1; + } +#if !defined(WE_TEST_CMAC_INLINE) + if ((bufferFreed != 1) || !bufferCleared) + err = 1; + if (bufferFreed == 0) + free(buffer); +#else + if ((bufferFreed != 0) || !bufferCleared) + err = 1; +#endif + printf("CMAC cleanup ownership: %s\n", err ? "FAIL" : "PASS"); + return err; +} diff --git a/test/test_dh.c b/test/test_dh.c index 8b44931d..60c98acd 100644 --- a/test/test_dh.c +++ b/test/test_dh.c @@ -23,6 +23,10 @@ #ifdef WE_HAVE_DH +#ifndef WE_DH_EX_DATA_IDX +#define WE_DH_EX_DATA_IDX 0 +#endif + /* dh1024 p */ static const unsigned char dh_p[] = { @@ -45,6 +49,76 @@ static const unsigned char dh_g[] = 0x02, }; +#if defined(WE_DH_USE_GLOBAL_RNG) && defined(WE_HAVE_EVP_PKEY) && \ + !defined(WE_SINGLE_THREADED) && !defined(TEST_MULTITHREADED) && \ + !defined(_WIN32) +extern wolfSSL_Mutex* we_rng_mutex; + +static int test_dh_failed_rng_lock(ENGINE* e) +{ + int err = 0; + int attrInit = 0; + int mutexInit = 0; + int mutexLocked = 0; + int rc; + pthread_mutexattr_t attr; + wolfSSL_Mutex mutex; + wolfSSL_Mutex* savedMutex = we_rng_mutex; + EVP_PKEY_CTX* ctx = NULL; + EVP_PKEY* params = NULL; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, e); + err = ctx == NULL; + if (err == 0) + err = EVP_PKEY_paramgen_init(ctx) != 1; + + if (err == 0) { + rc = pthread_mutexattr_init(&attr); + err = rc != 0; + attrInit = rc == 0; + } + if (err == 0) { + rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); + err = rc != 0; + } + if (err == 0) { + rc = pthread_mutex_init(&mutex, &attr); + err = rc != 0; + mutexInit = rc == 0; + } + if (err == 0) { + rc = pthread_mutex_lock(&mutex); + err = rc != 0; + mutexLocked = rc == 0; + } + if (err == 0) { + we_rng_mutex = &mutex; + rc = EVP_PKEY_paramgen(ctx, ¶ms); + we_rng_mutex = savedMutex; + err = rc != 0; + } + if (err == 0) { + rc = pthread_mutex_trylock(&mutex); + if (rc == 0) { + pthread_mutex_unlock(&mutex); + mutexLocked = 0; + err = 1; + } + } + if (mutexInit) { + if (mutexLocked) + pthread_mutex_unlock(&mutex); + pthread_mutex_destroy(&mutex); + } + if (attrInit) + pthread_mutexattr_destroy(&attr); + EVP_PKEY_free(params); + EVP_PKEY_CTX_free(ctx); + + return err; +} +#endif + static int test_dh_keygen(DH *dhOpenSSL, DH *dhWolfEngine) { int err = 0; @@ -103,15 +177,155 @@ static int test_dh_keygen(DH *dhOpenSSL, DH *dhWolfEngine) return err; } +static int test_dh_parameter_refresh(ENGINE *e) +{ + int err; + DH *dhWithQ = NULL; + DH *dhWithoutQ = NULL; + const DH_METHOD *method = ENGINE_get_DH(e); + BIGNUM *p = NULL; + BIGNUM *q = NULL; + BIGNUM *g = NULL; + BIGNUM *priv = NULL; + BIGNUM *peerPub = NULL; + void *withQData = NULL; + void *withoutQData = NULL; + unsigned char secret[sizeof(dh_p)]; + unsigned char privateKey[64]; + int i; + + for (i = 0; i < (int)sizeof(privateKey); i++) + privateKey[i] = (unsigned char)(i + 1); + + err = method == NULL; + if (err == 0) { + dhWithQ = DH_new(); + dhWithoutQ = DH_new(); + err = (dhWithQ == NULL) || (dhWithoutQ == NULL); + } + if (err == 0) { + err = (DH_set_method(dhWithQ, method) != 1) || + (DH_set_method(dhWithoutQ, method) != 1); + } + if (err == 0) { + p = BN_bin2bn(dh_p, sizeof(dh_p), NULL); + q = BN_dup(p); + g = BN_new(); + err = (p == NULL) || (q == NULL) || (g == NULL); + } + if (err == 0) { + err = (BN_sub_word(q, 1) != 1) || (BN_rshift1(q, q) != 1) || + (BN_set_word(g, 4) != 1); + } + if (err == 0) { + err = DH_set0_pqg(dhWithQ, p, q, g) != 1; + if (err == 0) { + p = NULL; + q = NULL; + g = NULL; + } + } + if (err == 0) { + priv = BN_bin2bn(privateKey, sizeof(privateKey), NULL); + err = priv == NULL; + } + if (err == 0) { + err = DH_set0_key(dhWithQ, NULL, priv) != 1; + if (err == 0) + priv = NULL; + } + if (err == 0) + err = DH_generate_key(dhWithQ) != 1; + + if (err == 0) { + p = BN_bin2bn(dh_p, sizeof(dh_p), NULL); + g = BN_bin2bn(dh_g, sizeof(dh_g), NULL); + err = (p == NULL) || (g == NULL); + } + if (err == 0) { + peerPub = BN_new(); + err = (peerPub == NULL) || (BN_set_word(peerPub, 2) != 1); + } + if (err == 0) { + err = DH_set0_pqg(dhWithoutQ, p, NULL, g) != 1; + if (err == 0) { + p = NULL; + g = NULL; + } + } + if (err == 0) + err = DH_generate_key(dhWithoutQ) != 1; + + if (err == 0) { + withQData = DH_get_ex_data(dhWithQ, WE_DH_EX_DATA_IDX); + withoutQData = DH_get_ex_data(dhWithoutQ, WE_DH_EX_DATA_IDX); + err = (withQData == NULL) || (withoutQData == NULL); + } + if (err == 0) { + err = DH_set_ex_data(dhWithQ, WE_DH_EX_DATA_IDX, withoutQData) != 1; + } + if (err == 0) { + if (DH_set_ex_data(dhWithoutQ, WE_DH_EX_DATA_IDX, withQData) != 1) { + (void)DH_set_ex_data(dhWithQ, WE_DH_EX_DATA_IDX, withQData); + err = 1; + } + } + if (err == 0) { + PRINT_MSG("Clear cached q when refreshing q-less DH parameters"); + err = DH_compute_key(secret, peerPub, dhWithoutQ) <= 0; + } + + BN_free(peerPub); + BN_clear_free(priv); + BN_free(g); + BN_free(q); + BN_free(p); + DH_free(dhWithoutQ); + DH_free(dhWithQ); + + return err; +} + +#ifndef HAVE_FIPS +static int test_dh_paramgen_cb(int event, int iteration, BN_GENCB *cb) +{ +#if OPENSSL_VERSION_NUMBER < 0x10100000L + int *count = (int *)cb->arg; +#else + int *count = (int *)BN_GENCB_get_arg(cb); +#endif + + (void)event; + (void)iteration; + (*count)++; + + return 1; +} +#endif + int test_dh_pgen(ENGINE *e, void *data) { int err; - DH *dhWolfEngine; DH *dhOpenSSL = NULL; + DH *dhWolfEngine; const DH_METHOD *method = NULL; +#ifndef HAVE_FIPS const BIGNUM *p = NULL; const BIGNUM *q = NULL; const BIGNUM *g = NULL; + const BIGNUM *oldP = NULL; + const BIGNUM *oldQ = NULL; + const BIGNUM *oldG = NULL; + BIGNUM *copyP = NULL; + BIGNUM *copyQ = NULL; + BIGNUM *copyG = NULL; + BIGNUM *existingQ = NULL; + BN_GENCB *cb = NULL; +#if OPENSSL_VERSION_NUMBER < 0x10100000L + BN_GENCB cbData; +#endif + int callbackCount = 0; +#endif (void)data; @@ -126,26 +340,116 @@ int test_dh_pgen(ENGINE *e, void *data) if (err == 0) { DH_set_method(dhWolfEngine, method); } +#if defined(WE_DH_USE_GLOBAL_RNG) && defined(WE_HAVE_EVP_PKEY) && \ + !defined(WE_SINGLE_THREADED) && !defined(TEST_MULTITHREADED) && \ + !defined(_WIN32) if (err == 0) { - /* Generator and callback (last param) ignored by wolfEngine. */ - err = DH_generate_parameters_ex(dhWolfEngine, 1024, DH_GENERATOR_5, - NULL) != 1; + PRINT_MSG("Keep RNG mutex ownership when locking fails"); + err = test_dh_failed_rng_lock(e); + } +#endif + if (err == 0) { + PRINT_MSG("Reject unsupported DH parameter generators"); + err = DH_generate_parameters_ex(dhWolfEngine, 1024, 1, NULL) > 0; + } + if (err == 0) { + PRINT_MSG("Reject unsupported DH prime lengths before generation"); + err = DH_generate_parameters_ex(dhWolfEngine, 512, DH_GENERATOR_2, + NULL) > 0; + } + if (err == 0) { + PRINT_MSG("Check rejected DH parameter generation left no prime"); + err = DH_get0_p(dhWolfEngine) != NULL; + } +#ifdef HAVE_FIPS + if (err == 0) { + PRINT_MSG("Reject legacy DH parameter generation in FIPS mode"); + err = DH_generate_parameters_ex(dhWolfEngine, 1024, DH_GENERATOR_2, + NULL) > 0; + } +#else + if (err == 0) { +#if OPENSSL_VERSION_NUMBER < 0x10100000L + cb = &cbData; +#else + cb = BN_GENCB_new(); + err = cb == NULL; +#endif + } + if (err == 0) { + BN_GENCB_set(cb, test_dh_paramgen_cb, &callbackCount); + PRINT_MSG("Honor the requested DH generator"); + err = DH_generate_parameters_ex(dhWolfEngine, 1024, DH_GENERATOR_2, + cb) != 1; + } + if (err == 0) { + PRINT_MSG("Forward the DH parameter generation callback"); + err = callbackCount == 0; } - if (err == 0) { DH_get0_pqg(dhWolfEngine, &p, &q, &g); - + PRINT_MSG("Check generated DH parameters"); + err = (p == NULL) || (g == NULL) || + (BN_get_word(g) != DH_GENERATOR_2); + } + if (err == 0) { dhOpenSSL = DH_new(); - err = (dhOpenSSL == NULL); + err = dhOpenSSL == NULL; } if (err == 0) { - err = DH_set0_pqg(dhOpenSSL, BN_dup(p), BN_dup(q), BN_dup(g)) != 1; + PRINT_MSG("Copy generated DH parameters"); + copyP = BN_dup(p); + if (q != NULL) + copyQ = BN_dup(q); + copyG = BN_dup(g); + err = (copyP == NULL) || ((q != NULL) && (copyQ == NULL)) || + (copyG == NULL); + } + if (err == 0) { + err = DH_set0_pqg(dhOpenSSL, copyP, copyQ, copyG) != 1; + if (err == 0) { + copyP = NULL; + copyQ = NULL; + copyG = NULL; + } } - if (err == 0) { + PRINT_MSG("Use generated DH parameters"); err = test_dh_keygen(dhOpenSSL, dhWolfEngine); } + if (err == 0) { + existingQ = BN_new(); + err = (existingQ == NULL) || (BN_set_word(existingQ, 23) != 1); + } + if (err == 0) { + err = DH_set0_pqg(dhWolfEngine, NULL, existingQ, NULL) != 1; + if (err == 0) + existingQ = NULL; + } + if (err == 0) { + DH_get0_pqg(dhWolfEngine, &oldP, &oldQ, &oldG); + PRINT_MSG("Reject replacing DH parameters that contain q"); + err = DH_generate_parameters_ex(dhWolfEngine, 1024, DH_GENERATOR_2, + NULL) > 0; + } + if (err == 0) { + DH_get0_pqg(dhWolfEngine, &p, &q, &g); + err = (p != oldP) || (q != oldQ) || (g != oldG); + } +#endif + if (err == 0) { + err = test_dh_parameter_refresh(e); + } +#ifndef HAVE_FIPS +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + BN_GENCB_free(cb); +#endif + BN_free(existingQ); + BN_free(copyG); + BN_free(copyQ); + BN_free(copyP); +#endif DH_free(dhOpenSSL); DH_free(dhWolfEngine); @@ -330,6 +634,109 @@ int test_dh_priv_key_length(ENGINE *e, void *data) #ifdef WE_HAVE_EVP_PKEY +static int test_dh_pkey_nonzero_padding(ENGINE *e, EVP_PKEY *params, + int useStringControl) +{ + static const unsigned char privateKey[] = { + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x00, 0x64 + }; + int err; + DH *ourDh = NULL; + DH *peerDh = NULL; + BIGNUM *priv = NULL; + BIGNUM *pub = NULL; + EVP_PKEY *ourKey = NULL; + EVP_PKEY *peerKey = NULL; + EVP_PKEY_CTX *ctx = NULL; + unsigned char *secret = NULL; + size_t secretLen = 0; + DH *paramsDh = (DH *)EVP_PKEY_get0_DH(params); + + err = paramsDh == NULL; + if (err == 0) { + ourDh = DHparams_dup(paramsDh); + peerDh = DHparams_dup(paramsDh); + err = (ourDh == NULL) || (peerDh == NULL); + } + if (err == 0) { + priv = BN_bin2bn(privateKey, sizeof(privateKey), NULL); + pub = BN_new(); + err = (priv == NULL) || (pub == NULL); + } + if (err == 0) { + err = BN_set_word(pub, 2) != 1; + } + if (err == 0) { + err = DH_set0_key(ourDh, NULL, priv) != 1; + if (err == 0) + priv = NULL; + } + if (err == 0) { + err = DH_set0_key(peerDh, pub, NULL) != 1; + if (err == 0) + pub = NULL; + } + if (err == 0) { + ourKey = EVP_PKEY_new(); + peerKey = EVP_PKEY_new(); + err = (ourKey == NULL) || (peerKey == NULL); + } + if (err == 0) { + err = EVP_PKEY_assign_DH(ourKey, ourDh) != 1; + if (err == 0) + ourDh = NULL; + } + if (err == 0) { + err = EVP_PKEY_assign_DH(peerKey, peerDh) != 1; + if (err == 0) + peerDh = NULL; + } + if (err == 0) { + ctx = EVP_PKEY_CTX_new(ourKey, e); + err = ctx == NULL; + } + if (err == 0) + err = EVP_PKEY_derive_init(ctx) <= 0; + if (err == 0) + err = EVP_PKEY_derive_set_peer(ctx, peerKey) <= 0; + if ((err == 0) && useStringControl) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "dh_pad", "2") <= 0; + } + else if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_DERIVE, + EVP_PKEY_CTRL_DH_PAD, 2, NULL) <= 0; + } + if (err == 0) { + secretLen = (size_t)EVP_PKEY_size(ourKey); + secret = (unsigned char *)OPENSSL_malloc(secretLen); + err = secret == NULL; + } + if (err == 0) + err = EVP_PKEY_derive(ctx, secret, &secretLen) <= 0; + if (err == 0) + err = secretLen != (size_t)EVP_PKEY_size(ourKey); + if (err == 0) + err = secret[0] != 0; + + OPENSSL_free(secret); + EVP_PKEY_CTX_free(ctx); + EVP_PKEY_free(peerKey); + EVP_PKEY_free(ourKey); + BN_free(pub); + BN_clear_free(priv); + DH_free(peerDh); + DH_free(ourDh); + + return err; +} + static int test_dh_pkey_keygen(ENGINE *e, EVP_PKEY *params) { int err; @@ -340,6 +747,11 @@ static int test_dh_pkey_keygen(ENGINE *e, EVP_PKEY *params) size_t secretLenOpenSSL = 0; unsigned char *secretWolfEngine = NULL; size_t secretLenWolfEngine = 0; + unsigned char *paddedSecret = NULL; + unsigned char *shortSecret = NULL; + size_t paddedSecretLen = 0; + size_t shortSecretLen = 0; + size_t expectedSecretLen = 0; ctx = EVP_PKEY_CTX_new(params, e); err = ctx == NULL; @@ -420,6 +832,48 @@ static int test_dh_pkey_keygen(ENGINE *e, EVP_PKEY *params) err = memcmp(secretOpenSSL, secretWolfEngine, secretLenOpenSSL) != 0; } + if (err == 0) { + PRINT_MSG("Pad DH secret to the modulus size"); + EVP_PKEY_CTX_free(ctx); + ctx = EVP_PKEY_CTX_new(keyWolfEngine, e); + err = ctx == NULL; + } + if (err == 0) { + err = EVP_PKEY_derive_init(ctx) <= 0; + } + if (err == 0) { + err = EVP_PKEY_derive_set_peer(ctx, keyOpenSSL) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_DERIVE, + EVP_PKEY_CTRL_DH_PAD, 1, NULL) <= 0; + } + if (err == 0) { + expectedSecretLen = (size_t)EVP_PKEY_size(keyWolfEngine); + paddedSecretLen = expectedSecretLen + 8; + paddedSecret = (unsigned char*)OPENSSL_malloc(paddedSecretLen); + err = paddedSecret == NULL; + } + if (err == 0) { + err = EVP_PKEY_derive(ctx, paddedSecret, &paddedSecretLen) <= 0; + } + if (err == 0) { + err = paddedSecretLen != expectedSecretLen; + } + if (err == 0) { + shortSecret = (unsigned char*)OPENSSL_malloc(expectedSecretLen + 1); + err = shortSecret == NULL; + } + if (err == 0) { + XMEMSET(shortSecret, 0xa5, expectedSecretLen + 1); + shortSecretLen = expectedSecretLen - 1; + PRINT_MSG("Reject a short padded DH secret buffer"); + err = EVP_PKEY_derive(ctx, shortSecret + 1, &shortSecretLen) > 0; + } + if (err == 0) { + err = (shortSecret[0] != 0xa5) || + (shortSecret[expectedSecretLen] != 0xa5); + } EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(keyOpenSSL); EVP_PKEY_free(keyWolfEngine); @@ -428,6 +882,10 @@ static int test_dh_pkey_keygen(ENGINE *e, EVP_PKEY *params) OPENSSL_free(secretWolfEngine); if (secretOpenSSL != NULL) OPENSSL_free(secretOpenSSL); + if (paddedSecret != NULL) + OPENSSL_free(paddedSecret); + if (shortSecret != NULL) + OPENSSL_free(shortSecret); return err; } @@ -538,6 +996,13 @@ int test_dh_pkey(ENGINE* e, void* data) if (err == 0) { err = test_dh_pkey_keygen(e, params); } + if (err == 0) { + PRINT_MSG("Treat every nonzero DH padding control value as enabled"); + err = test_dh_pkey_nonzero_padding(e, params, 0); + } + if (err == 0) { + err = test_dh_pkey_nonzero_padding(e, params, 1); + } EVP_PKEY_free(params); DH_free(dh); @@ -549,6 +1014,7 @@ int test_dh_ctrl(ENGINE* e, void* data) { int err; EVP_PKEY_CTX* ctx = NULL; + EVP_PKEY* key = NULL; int primeLengths[] = {1024, 2048, 3072}; word32 i; @@ -604,6 +1070,15 @@ int test_dh_ctrl(ENGINE* e, void* data) if (err == 0) { err = EVP_PKEY_CTX_ctrl_str(ctx, "dh_param", "ffdhe2048") <= 0; } + #ifndef HAVE_FFDHE_Q + if (err == 0) { + PRINT_MSG("Generate a key with named DH parameters"); + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_keygen(ctx, &key) != 1; + } + #endif #else if (err == 0) { err = EVP_PKEY_CTX_ctrl_str(ctx, "dh_param", "ffdhe2048") > 0; @@ -631,6 +1106,7 @@ int test_dh_ctrl(ENGINE* e, void* data) #endif /* HAVE_FFDHE_4096 */ #endif /* HAVE_PUBLIC_FFDHE */ + EVP_PKEY_free(key); EVP_PKEY_CTX_free(ctx); return err; diff --git a/test/test_dh_alloc.c b/test/test_dh_alloc.c new file mode 100644 index 00000000..c8d86149 --- /dev/null +++ b/test/test_dh_alloc.c @@ -0,0 +1,166 @@ +/* test_dh_alloc.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfengine. + * + * wolfengine is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfengine 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include +#include + +#include +#ifdef WOLFENGINE_USER_SETTINGS +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include + +#if defined(WE_HAVE_DH) && defined(WE_HAVE_EVP_PKEY) && \ + defined(HAVE_PUBLIC_FFDHE) && defined(HAVE_FFDHE_2048) && \ + !defined(HAVE_FFDHE_Q) && !defined(TEST_MULTITHREADED) && \ + !defined(WE_NO_OPENSSL_MALLOC) && !defined(OPENSSL_NO_FILENAMES) + +static int dhAllocTracking = 0; +static size_t dhAllocSizes[32]; +static int dhAllocCount = 0; + +static void* dh_alloc_malloc(size_t len, const char* file, int line) +{ + (void)line; + + if (dhAllocTracking && (file != NULL) && + (strstr(file, "we_dh.c") != NULL) && + (dhAllocCount < (int)(sizeof(dhAllocSizes) / sizeof(*dhAllocSizes)))) { + dhAllocSizes[dhAllocCount++] = len; + } + + return malloc(len); +} + +static void* dh_alloc_realloc(void* ptr, size_t len, const char* file, int line) +{ + (void)file; + (void)line; + + return realloc(ptr, len); +} + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L +static void dh_alloc_free(void* ptr, const char* file, int line) +{ + (void)file; + (void)line; + + free(ptr); +} +#else +static void dh_alloc_free_legacy(void* ptr) +{ + free(ptr); +} +#endif + +int main(void) +{ + int err = 0; + int matched = 0; + int i; + ENGINE* e = NULL; + EVP_PKEY_CTX* ctx = NULL; + EVP_PKEY* key = NULL; + const DH* keyDh = NULL; + const BIGNUM* keyG = NULL; + + /* Memory hooks must precede all OpenSSL initialization in this process. */ +#if OPENSSL_VERSION_NUMBER < 0x10100000L + err = CRYPTO_set_mem_ex_functions(dh_alloc_malloc, dh_alloc_realloc, + dh_alloc_free_legacy) != 1; +#else + err = CRYPTO_set_mem_functions(dh_alloc_malloc, dh_alloc_realloc, + dh_alloc_free) != 1; +#endif + if (err == 0) { + ENGINE_load_wolfengine(); + e = ENGINE_by_id(wolfengine_id); + err = e == NULL; + } + if (err == 0) { + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, e); + err = ctx == NULL; + } + if (err == 0) { + err = EVP_PKEY_paramgen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "dh_param", "ffdhe2048") != 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + dhAllocTracking = 1; + err = EVP_PKEY_keygen(ctx, &key) != 1; + dhAllocTracking = 0; + } + if (err == 0) { + keyDh = EVP_PKEY_get0_DH(key); + if (keyDh != NULL) + keyG = DH_get0_g(keyDh); + err = keyG == NULL; + } + if (err == 0) { + for (i = 0; !matched && (i + 2 < dhAllocCount); i++) { + matched = (dhAllocSizes[i] == (size_t)DH_size(keyDh)) && + (dhAllocSizes[i + 1] == 1) && + (dhAllocSizes[i + 2] == (size_t)BN_num_bytes(keyG)); + } + err = !matched; + } + + EVP_PKEY_free(key); + EVP_PKEY_CTX_free(ctx); + ENGINE_free(e); +#if OPENSSL_VERSION_NUMBER < 0x10100000L + EVP_cleanup(); + ENGINE_cleanup(); + ERR_free_strings(); +#endif + + if (err != 0) + fprintf(stderr, "DH encoded allocation lengths failed\n"); + else + printf("DH encoded allocation lengths passed\n"); + + return err; +} + +#else + +int main(void) +{ + printf("DH allocation tracking unavailable in this configuration\n"); + return 77; +} + +#endif diff --git a/test/test_digest.c b/test/test_digest.c index ff83140c..776c9482 100644 --- a/test/test_digest.c +++ b/test/test_digest.c @@ -21,8 +21,137 @@ #include "unit.h" +#include + #ifdef WE_HAVE_DIGEST +#ifdef WE_USE_HASH +static int test_digest_copy(const EVP_MD *md, ENGINE *e) +{ + int err = 0; + EVP_MD_CTX *src = NULL; + EVP_MD_CTX *dst = NULL; + const EVP_MD *engineMd; + const unsigned char prefix[] = "shared prefix"; + const unsigned char srcSuffix[] = " source"; + const unsigned char dstSuffix[] = " destination"; + const unsigned char srcMsg[] = "shared prefix source"; + const unsigned char dstMsg[] = "shared prefix destination"; + unsigned char srcDigest[EVP_MAX_MD_SIZE]; + unsigned char dstDigest[EVP_MAX_MD_SIZE]; + unsigned char expected[EVP_MAX_MD_SIZE]; + unsigned int srcLen = 0; + unsigned int dstLen = 0; + unsigned int expectedLen = 0; + + engineMd = ENGINE_get_digest(e, EVP_MD_type(md)); + err = (engineMd == NULL) || (EVP_MD_meth_get_copy(engineMd) == NULL); + if (err == 0) { + err = ((src = EVP_MD_CTX_new()) == NULL) || + ((dst = EVP_MD_CTX_new()) == NULL); + } + if (err == 0) { + err = EVP_DigestInit_ex(src, md, e) != 1; + } + if (err == 0) { + err = EVP_DigestUpdate(src, prefix, sizeof(prefix) - 1) != 1; + } + if (err == 0) { + err = EVP_MD_meth_get_copy(engineMd)(src, src) != 1; + } + if (err == 0) { + err = EVP_MD_CTX_copy_ex(dst, src) != 1; + } + if (err == 0) { + err = EVP_DigestUpdate(src, srcSuffix, sizeof(srcSuffix) - 1) != 1; + } + if (err == 0) { + err = EVP_DigestUpdate(dst, dstSuffix, sizeof(dstSuffix) - 1) != 1; + } + if (err == 0) { + err = EVP_DigestFinal_ex(src, srcDigest, &srcLen) != 1; + } + if (err == 0) { + err = EVP_DigestFinal_ex(dst, dstDigest, &dstLen) != 1; + } + if (err == 0) { + err = EVP_Digest(srcMsg, sizeof(srcMsg) - 1, expected, &expectedLen, + md, NULL) != 1; + } + if (err == 0) { + err = (srcLen != expectedLen) || + (XMEMCMP(srcDigest, expected, srcLen) != 0); + } + if (err == 0) { + err = EVP_Digest(dstMsg, sizeof(dstMsg) - 1, expected, &expectedLen, + md, NULL) != 1; + } + if (err == 0) { + err = (dstLen != expectedLen) || + (XMEMCMP(dstDigest, expected, dstLen) != 0); + } + + EVP_MD_CTX_free(dst); + EVP_MD_CTX_free(src); + + return err; +} + +#if defined(WE_HAVE_HMAC) && defined(WE_HAVE_EVP_PKEY) && \ + defined(WE_HAVE_SHA384) +static int test_digest_hmac_reuse(ENGINE *e) +{ + int err; + EVP_MD_CTX *ctx = NULL; + EVP_PKEY *key = NULL; + const EVP_MD *md = EVP_sha384(); + const unsigned char secret[] = "context reuse key"; + const unsigned char message[] = "context reuse message"; + unsigned char mac[EVP_MAX_MD_SIZE]; + unsigned char expected[EVP_MAX_MD_SIZE]; + unsigned int expectedLen = 0; + size_t macLen = sizeof(mac); + + PRINT_MSG("Reuse a finalized digest context for HMAC"); + err = HMAC(md, secret, sizeof(secret) - 1, message, sizeof(message) - 1, + expected, &expectedLen) == NULL; + if (err == 0) { + ctx = EVP_MD_CTX_new(); + key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, secret, + sizeof(secret) - 1); + err = (ctx == NULL) || (key == NULL); + } + if (err == 0) { + err = EVP_DigestInit_ex(ctx, md, e) != 1; + } + if (err == 0) { + err = EVP_DigestUpdate(ctx, message, sizeof(message) - 1) != 1; + } + if (err == 0) { + err = EVP_DigestFinal_ex(ctx, mac, NULL) != 1; + } + if (err == 0) { + err = EVP_DigestSignInit(ctx, NULL, md, e, key) != 1; + } + if (err == 0) { + err = EVP_DigestSignUpdate(ctx, message, sizeof(message) - 1) != 1; + } + if (err == 0) { + err = EVP_DigestSignFinal(ctx, mac, &macLen) != 1; + } + if (err == 0) { + err = (macLen != expectedLen) || + (XMEMCMP(mac, expected, expectedLen) != 0); + } + + EVP_MD_CTX_free(ctx); + EVP_PKEY_free(key); + + return err; +} +#endif +#endif + int test_digest_op(const EVP_MD *md, ENGINE *e, unsigned char *msg, size_t len, unsigned char *prev, unsigned int *prevLen) @@ -36,6 +165,9 @@ int test_digest_op(const EVP_MD *md, ENGINE *e, unsigned char *msg, if (err == 0) { err = EVP_DigestInit_ex(ctx, md, e) != 1; } + if (err == 0) { + err = EVP_MD_CTX_type(ctx) != EVP_MD_type(md); + } if (err == 0) { err = EVP_DigestUpdate(ctx, msg, len/2) != 1; } @@ -73,21 +205,28 @@ static int test_create_digest(const EVP_MD *md, ENGINE *e, void *data) { int err = 0; unsigned char *msg = (unsigned char *)"Test pattern"; - unsigned char longMsg[1300]; + const size_t longMsgLen = (2U * 1024U * 1024U) + 2U; + unsigned char *longMsg = NULL; unsigned char digest[64]; unsigned int dLen; + size_t i; (void)data; - /* Must memset longMsg to make valgrind happy */ XMEMSET(digest, 0, sizeof(digest)); - XMEMSET(longMsg, 0, sizeof(longMsg)); - - RAND_bytes(longMsg, sizeof(longMsg)); + err = (longMsg = OPENSSL_malloc(longMsgLen)) == NULL; + if (err == 0) { + for (i = 0; i < longMsgLen; i++) { + longMsg[i] = (unsigned char)(i * 31U); + } + } dLen = 0; - PRINT_MSG("Digest with OpenSSL"); - err = test_digest_op(md, NULL, msg, strlen((char*)msg), digest, &dLen); + if (err == 0) { + PRINT_MSG("Digest with OpenSSL"); + err = test_digest_op(md, NULL, msg, strlen((char*)msg), digest, + &dLen); + } if (err == 0) { PRINT_MSG("Digest With wolfengine"); err = test_digest_op(md, e, msg, strlen((char*)msg), digest, &dLen); @@ -95,12 +234,19 @@ static int test_create_digest(const EVP_MD *md, ENGINE *e, void *data) if (err == 0) { dLen = 0; PRINT_MSG("Digest with OpenSSL"); - err = test_digest_op(md, NULL, longMsg, sizeof(longMsg), digest, &dLen); + err = test_digest_op(md, NULL, longMsg, longMsgLen, digest, &dLen); } if (err == 0) { PRINT_MSG("Digest With wolfengine"); - err = test_digest_op(md, e, longMsg, sizeof(longMsg), digest, &dLen); + err = test_digest_op(md, e, longMsg, longMsgLen, digest, &dLen); } +#ifdef WE_USE_HASH + if (err == 0) { + err = test_digest_copy(md, e); + } +#endif + + OPENSSL_free(longMsg); return err; } @@ -109,7 +255,21 @@ static int test_create_digest(const EVP_MD *md, ENGINE *e, void *data) int test_sha(ENGINE *e, void *data) { - return test_create_digest(EVP_sha1(), e, data); + int err = 0; + +#ifdef WE_HAVE_ECDSA + const EVP_MD *md = ENGINE_get_digest(e, NID_ecdsa_with_SHA1); + + err = md == NULL; + if (err == 0) { + err = EVP_MD_block_size(md) != WC_SHA_BLOCK_SIZE; + } +#endif + if (err == 0) { + err = test_create_digest(EVP_sha1(), e, data); + } + + return err; } #endif /* WE_HAVE_SHA1 */ @@ -132,7 +292,15 @@ int test_sha256(ENGINE *e, void *data) #ifdef WE_HAVE_SHA384 int test_sha384(ENGINE *e, void *data) { - return test_create_digest(EVP_sha384(), e, data); + int err = test_create_digest(EVP_sha384(), e, data); + +#if defined(WE_USE_HASH) && defined(WE_HAVE_HMAC) && defined(WE_HAVE_EVP_PKEY) + if (err == 0) { + err = test_digest_hmac_reuse(e); + } +#endif + + return err; } #endif diff --git a/test/test_ecc.c b/test/test_ecc.c index 8eb852ce..69d4bc1d 100644 --- a/test/test_ecc.c +++ b/test/test_ecc.c @@ -402,6 +402,60 @@ int test_eckeygen_p224(ENGINE *e, void *data) #endif /* WE_HAVE_EC_P224 */ #ifdef WE_HAVE_EC_P256 +#if defined(WE_HAVE_EC_P384) && OPENSSL_VERSION_NUMBER < 0x30000000L +static int test_eckeygen_copy(ENGINE *e) +{ + int err; + int shared = 0; + EVP_PKEY_CTX *src = NULL; + EVP_PKEY_CTX *dst = NULL; + EVP_PKEY *key = NULL; + EC_KEY *ecKey = NULL; + const EC_GROUP *group = NULL; + + err = (src = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, e)) == NULL; + if (err == 0) { + err = EVP_PKEY_keygen_init(src) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(src, + NID_X9_62_prime256v1) != 1; + } + if (err == 0) { + dst = EVP_PKEY_CTX_dup(src); + err = dst == NULL; + } + if (err == 0) { + shared = EVP_PKEY_CTX_get_data(src) == EVP_PKEY_CTX_get_data(dst); + err = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(src, NID_secp384r1) != 1; + } + if (err == 0) { + err = EVP_PKEY_keygen(dst, &key) != 1; + } + if (err == 0) { + ecKey = EVP_PKEY_get1_EC_KEY(key); + err = ecKey == NULL; + } + if (err == 0) { + group = EC_KEY_get0_group(ecKey); + err = group == NULL; + } + if (err == 0) { + err = EC_GROUP_get_curve_name(group) != NID_X9_62_prime256v1; + } + + if (shared) { + EVP_PKEY_CTX_set_data(dst, NULL); + } + EC_KEY_free(ecKey); + EVP_PKEY_free(key); + EVP_PKEY_CTX_free(dst); + EVP_PKEY_CTX_free(src); + + return err; +} +#endif + int test_eckeygen_p256_by_nid(ENGINE *e, void *data) { int err; @@ -420,6 +474,11 @@ int test_eckeygen_p256_by_nid(ENGINE *e, void *data) PRINT_MSG("Generate key"); err = EVP_PKEY_keygen(ctx, &key) != 1; } +#if defined(WE_HAVE_EC_P384) && OPENSSL_VERSION_NUMBER < 0x30000000L + if (err == 0) { + err = test_eckeygen_copy(e); + } +#endif EVP_PKEY_free(key); EVP_PKEY_CTX_free(ctx); @@ -815,12 +874,165 @@ int test_ecdh_p224(ENGINE *e, void *data) #endif /* WE_HAVE_EC_P224 */ #ifdef WE_HAVE_EC_P256 +#ifdef WE_HAVE_SHA256 +static int test_ecdh_kdf_output_length(ENGINE *e) +{ + int err = 0; + int i; + EVP_PKEY *key = NULL; + EVP_PKEY *peerKey = NULL; +#ifdef WE_HAVE_EC_P384 + EVP_PKEY *otherPeer = NULL; +#endif + unsigned char output[2][16]; + const unsigned char *p; + + p = ecc_key_der_256; + key = d2i_PrivateKey(EVP_PKEY_EC, NULL, &p, sizeof(ecc_key_der_256)); + if (key == NULL) + err = 1; + if (err == 0) { + p = ecc_peerkey_der_256; + peerKey = d2i_PrivateKey(EVP_PKEY_EC, NULL, &p, + sizeof(ecc_peerkey_der_256)); + err = peerKey == NULL; + } +#ifdef WE_HAVE_EC_P384 + if (err == 0) { + p = ecc_peerkey_der_384; + otherPeer = d2i_PrivateKey(EVP_PKEY_EC, NULL, &p, + sizeof(ecc_peerkey_der_384)); + err = otherPeer == NULL; + } +#endif + + for (i = 0; (i < 2) && (err == 0); i++) { + EVP_PKEY_CTX *ctx; + int configuredLen = 0; + size_t outputLen = sizeof(output[i]); + +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + if (i == 1) + err = EVP_PKEY_set1_engine(key, e) != 1; + ctx = err == 0 ? EVP_PKEY_CTX_new(key, NULL) : NULL; +#else + ctx = EVP_PKEY_CTX_new(key, i == 0 ? NULL : e); +#endif + if (ctx == NULL) + err = 1; + if (err == 0) + err = EVP_PKEY_derive_init(ctx) != 1; +#ifdef WE_HAVE_EC_P384 + if ((err == 0) && (i == 1)) + err = EVP_PKEY_derive_set_peer(ctx, otherPeer) == 1; +#endif + if (err == 0) + err = EVP_PKEY_derive_set_peer(ctx, peerKey) != 1; + if (err == 0) + err = EVP_PKEY_CTX_set_ecdh_kdf_type(ctx, + EVP_PKEY_ECDH_KDF_X9_63) != 1; + if (err == 0) + err = EVP_PKEY_CTX_set_ecdh_kdf_md(ctx, EVP_sha256()) != 1; + if (err == 0) + err = EVP_PKEY_CTX_set_ecdh_kdf_outlen(ctx, (int)outputLen) != 1; + if (err == 0) + err = EVP_PKEY_CTX_get_ecdh_kdf_outlen(ctx, &configuredLen) != 1; + if (err == 0) + err = configuredLen != (int)outputLen; + if ((err == 0) && (i == 1)) { + err = EVP_PKEY_CTX_set_ecdh_kdf_md(ctx, NULL) != 1; + if (err == 0) + err = EVP_PKEY_CTX_set_ecdh_kdf_md(ctx, EVP_sha256()) != 1; + if (err == 0) + err = EVP_PKEY_CTX_set_ecdh_kdf_outlen(ctx, 0) == 1; + } + if (err == 0) + err = EVP_PKEY_derive(ctx, output[i], &outputLen) != 1; + if (err == 0) { + err = outputLen != sizeof(output[i]); + if (err != 0) { + PRINT_ERR_MSG("ECDH KDF output length differs from result"); + } + } + if ((err == 0) && (i == 1)) { + size_t shortLen = sizeof(output[i]) - 1; + + err = EVP_PKEY_derive(ctx, output[i], &shortLen) == 1; + } + + EVP_PKEY_CTX_free(ctx); + } + if (err == 0) + err = XMEMCMP(output[0], output[1], sizeof(output[0])) != 0; + +#ifdef WE_HAVE_EC_P384 + EVP_PKEY_free(otherPeer); +#endif + EVP_PKEY_free(peerKey); + EVP_PKEY_free(key); + + return err; +} +#endif /* WE_HAVE_SHA256 */ + +#if defined(WE_HAVE_ECKEYGEN) && OPENSSL_VERSION_NUMBER >= 0x1000212fL +static int test_ec_paramgen_string_controls(ENGINE *e) +{ + int err; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *params = NULL; + const EC_KEY *ecKey; + const EC_GROUP *group; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, e); + err = ctx == NULL; + if (err == 0) + err = EVP_PKEY_paramgen_init(ctx) != 1; + if (err == 0) + err = EVP_PKEY_CTX_ctrl_str(ctx, "ec_paramgen_curve", "P-256") != 1; + if (err == 0) + err = EVP_PKEY_CTX_ctrl_str(ctx, "ec_param_enc", "named_curve") != 1; + if (err == 0) + err = EVP_PKEY_CTX_ctrl_str(ctx, "ec_param_enc", "explicit") != -2; + if (err == 0) + err = EVP_PKEY_paramgen(ctx, ¶ms) != 1; + if (err == 0) { + ecKey = EVP_PKEY_get0_EC_KEY(params); + group = ecKey != NULL ? EC_KEY_get0_group(ecKey) : NULL; + err = group == NULL || + EC_GROUP_get_curve_name(group) != NID_X9_62_prime256v1 || + EC_GROUP_get_asn1_flag(group) != OPENSSL_EC_NAMED_CURVE; + } + + EVP_PKEY_free(params); + EVP_PKEY_CTX_free(ctx); + + return err; +} +#endif /* WE_HAVE_ECKEYGEN && OPENSSL_VERSION_NUMBER >= 0x1000212fL */ + int test_ecdh_p256(ENGINE *e, void *data) { + int err; + (void)data; - return test_ecdh(e, ecc_key_der_256, sizeof(ecc_key_der_256), - ecc_peerkey_der_256, sizeof(ecc_peerkey_der_256), - ecc_derived_256, sizeof(ecc_derived_256)); + err = test_ecdh(e, ecc_key_der_256, sizeof(ecc_key_der_256), + ecc_peerkey_der_256, sizeof(ecc_peerkey_der_256), + ecc_derived_256, sizeof(ecc_derived_256)); +#ifdef WE_HAVE_SHA256 + if (err == 0) { + PRINT_MSG("Check ECDH KDF output length"); + err = test_ecdh_kdf_output_length(e); + } +#endif /* WE_HAVE_SHA256 */ +#if defined(WE_HAVE_ECKEYGEN) && OPENSSL_VERSION_NUMBER >= 0x1000212fL + if (err == 0) { + PRINT_MSG("Check EC parameter string controls"); + err = test_ec_paramgen_string_controls(e); + } +#endif /* WE_HAVE_ECKEYGEN && OPENSSL_VERSION_NUMBER >= 0x1000212fL */ + + return err; } #endif /* WE_HAVE_EC_P256 */ @@ -1824,15 +2036,21 @@ int test_ec_key_ecdsa_sign(EC_KEY *key, unsigned char *hash, int err; unsigned int sigLen; PRINT_MSG("test_ec_key_ecdsa_sign"); - sigLen = (unsigned int)*ecdsaSigLen; + sigLen = 0; err = ECDSA_sign(0, hash, (int)hashLen, ecdsaSig, &sigLen, key) != 1; + if (err == 0) { + err = (sigLen == 0) || (sigLen > *ecdsaSigLen); + } if (err == 0) { PRINT_BUFFER("Signature", ecdsaSig, sigLen); } if (err == 0) { - sigLen = (unsigned int)*ecdsaSigLen; + sigLen = 0; err = ECDSA_sign(0, hash, (int)hashLen, ecdsaSig, &sigLen, key) != 1; } + if (err == 0) { + err = (sigLen == 0) || (sigLen > *ecdsaSigLen); + } if (err == 0) { PRINT_BUFFER("Signature", ecdsaSig, sigLen); *ecdsaSigLen = sigLen; @@ -1869,6 +2087,132 @@ int test_ec_key_ecdsa_verify(EC_KEY *key, unsigned char *hash, return err; } +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) +static int test_ecdsa_verify_error_logs; + +static void test_ecdsa_verify_logging(const int level, const int component, + const char *const message) +{ + if ((level == WE_LOG_ERROR) && (component == WE_LOG_PK) && + strstr(message, "wc_ecc_verify_hash") != NULL) { + test_ecdsa_verify_error_logs++; + } +} +#endif + +static int test_ec_key_ecdsa_scalar_range(EC_KEY *key, unsigned char *hash, + size_t hashLen) +{ + int err = 0; + int i; + int sigLen; + BIGNUM *order = NULL; + BIGNUM *r = NULL; + BIGNUM *s = NULL; + ECDSA_SIG *sig = NULL; + unsigned char der[140]; + unsigned char *p; + +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) + test_ecdsa_verify_error_logs = 0; + if (wolfEngine_SetLoggingCb(test_ecdsa_verify_logging) != 0 || + wolfEngine_Debugging_ON() != 0 || + wolfEngine_SetLogLevel(WE_LOG_ERROR) != 0 || + wolfEngine_SetLogComponents(WE_LOG_PK) != 0) { + err = 1; + goto end; + } +#endif + order = BN_new(); + sig = ECDSA_SIG_new(); + if (order == NULL || sig == NULL || + EC_GROUP_get_order(EC_KEY_get0_group(key), order, NULL) != 1) { + err = 1; + goto end; + } + + /* ECDSA scalars must be strictly between zero and the group order. */ + for (i = 0; i < 4 && err == 0; i++) { + r = BN_new(); + s = BN_new(); + if (r == NULL || s == NULL || BN_one(r) != 1 || BN_one(s) != 1) { + err = 1; + goto end; + } + if (i < 2) { + BN_zero(i == 0 ? r : s); + } + else if (BN_copy(i == 2 ? r : s, order) == NULL) { + err = 1; + goto end; + } + if (ECDSA_SIG_set0(sig, r, s) != 1) { + err = 1; + goto end; + } + r = NULL; + s = NULL; + sigLen = i2d_ECDSA_SIG(sig, NULL); + if (sigLen <= 0 || sigLen > (int)sizeof(der)) { + err = 1; + goto end; + } + p = der; + err = i2d_ECDSA_SIG(sig, &p) != sigLen; + if (err == 0) { + err = ECDSA_verify(0, hash, (int)hashLen, der, sigLen, key) != 0; + } + } + +end: + BN_free(s); + BN_free(r); + BN_free(order); + ECDSA_SIG_free(sig); +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) + (void)wolfEngine_SetLoggingCb(NULL); + (void)wolfEngine_SetLogLevel(WE_LOG_ERROR | WE_LOG_INFO); + (void)wolfEngine_SetLogComponents(WE_LOG_COMPONENTS_DEFAULT); + wolfEngine_Debugging_OFF(); + if (test_ecdsa_verify_error_logs != 0) { + PRINT_MSG("Invalid ECDSA scalars produced backend error diagnostics"); + err = 1; + } +#endif + return err; +} + +static int test_ec_key_ecdsa_encoding(EC_KEY *key, unsigned char *hash, + size_t hashLen) +{ + static const unsigned char invalidInteger[2][8] = { + { 0x30, 0x06, 0x02, 0x01, 0xff, 0x02, 0x01, 0x01 }, + { 0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0xff } + }; + static const unsigned char invalidEncoding[2][9] = { + { 0x30, 0x07, 0x02, 0x02, 0x00, 0x01, 0x02, 0x01, 0x01 }, + { 0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x00 } + }; + int i; + + for (i = 0; i < 2; i++) { + if (ECDSA_verify(0, hash, (int)hashLen, invalidInteger[i], + (int)sizeof(invalidInteger[i]), key) != -1) { + PRINT_MSG("Invalid ECDSA integer encoding did not return an error"); + return 1; + } + } + for (i = 0; i < 2; i++) { + if (ECDSA_verify(0, hash, (int)hashLen, invalidEncoding[i], + (int)sizeof(invalidEncoding[i]), key) != -1) { + PRINT_MSG("Noncanonical ECDSA encoding did not return an error"); + return 1; + } + } + + return 0; +} + int test_ec_key_ecdsa(ENGINE *e, const unsigned char *privKey, size_t privKeyLen) { @@ -1912,6 +2256,22 @@ int test_ec_key_ecdsa(ENGINE *e, const unsigned char *privKey, err = test_ec_key_ecdsa_verify(key, buf, sizeof(buf), ecdsaSig, ecdsaSigLen); } + if (err == 0) { + PRINT_MSG("Verify ECDSA scalar range with wolfengine"); + err = test_ec_key_ecdsa_scalar_range(key, buf, sizeof(buf)); + } + if (err == 0) { + PRINT_MSG("Verify ECDSA scalar range with OpenSSL"); + err = test_ec_key_ecdsa_scalar_range(keyOSSL, buf, sizeof(buf)); + } + if (err == 0) { + PRINT_MSG("Reject invalid ECDSA integer encoding with wolfengine"); + err = test_ec_key_ecdsa_encoding(key, buf, sizeof(buf)); + } + if (err == 0) { + PRINT_MSG("Reject invalid ECDSA integer encoding with OpenSSL"); + err = test_ec_key_ecdsa_encoding(keyOSSL, buf, sizeof(buf)); + } if (err == 0) { PRINT_MSG("Verify bad signature with wolfengine"); ecdsaSig[1] ^= 0x80; diff --git a/test/test_engine_lifetime.c b/test/test_engine_lifetime.c new file mode 100644 index 00000000..e7e37d7d --- /dev/null +++ b/test/test_engine_lifetime.c @@ -0,0 +1,143 @@ +/* test_engine_lifetime.c + * + * Copyright (C) 2006-2026 wolfSSL Inc. + * + * This file is part of wolfengine. + * + * wolfengine is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfengine 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#include +#ifdef WOLFENGINE_USER_SETTINGS +#include "user_settings.h" +#endif +#include +#include +#include +#ifdef HAVE_DLFCN_H +#include +#endif + +#if defined(WE_HAVE_SHARED_LIBRARY) && !defined(WE_NO_DYNAMIC_ENGINE) && \ + !defined(WE_HAVE_PBE) && OPENSSL_VERSION_NUMBER < 0x10100000L && \ + defined(HAVE_PTHREAD) && \ + !defined(WE_SINGLE_THREADED) +#include +static pthread_mutex_t test_openssl_locks[CRYPTO_NUM_LOCKS]; + +static void test_openssl_lock(int mode, int index, const char *file, int line) +{ + (void)file; + (void)line; + if ((mode & CRYPTO_LOCK) != 0) + pthread_mutex_lock(&test_openssl_locks[index]); + else + pthread_mutex_unlock(&test_openssl_locks[index]); +} +#endif + +int main(void) +{ +#if defined(WE_HAVE_SHARED_LIBRARY) && !defined(WE_NO_DYNAMIC_ENGINE) && \ + !defined(WE_HAVE_PBE) + ENGINE *engine; + const char *id; + const char *path; + int i; + int ret = 1; +#if OPENSSL_VERSION_NUMBER < 0x10100000L && defined(HAVE_PTHREAD) && \ + !defined(WE_SINGLE_THREADED) + int initialized = 0; + + for (i = 0; i < CRYPTO_NUM_LOCKS; i++) { + if (pthread_mutex_init(&test_openssl_locks[i], NULL) != 0) + goto cleanup; + initialized++; + } + CRYPTO_set_locking_callback(test_openssl_lock); +#endif +#if defined(HAVE_DLFCN_H) && defined(RTLD_NOLOAD) + void *module; +#endif + +#ifdef _WIN32 + id = "wolfEngine"; +#elif OPENSSL_VERSION_NUMBER >= 0x10100000L + id = "libwolfengine"; +#else + id = "wolfengine"; +#endif +#if defined(__CYGWIN__) + path = ".libs/cygwolfengine-1.dll"; +#elif defined(__MINGW32__) + path = ".libs/libwolfengine-1.dll"; +#elif defined(_WIN32) + path = ".libs/wolfEngine.dll"; +#elif defined(__APPLE__) + path = ".libs/libwolfengine.dylib"; +#else + path = ".libs/libwolfengine.so"; +#endif + + ENGINE_load_dynamic(); + for (i = 0; i < 100; i++) { + engine = ENGINE_by_id("dynamic"); + if ((engine == NULL) || + (ENGINE_ctrl_cmd_string(engine, "SO_PATH", path, 0) != 1) || + (ENGINE_ctrl_cmd_string(engine, "ID", id, 0) != 1) || + (ENGINE_ctrl_cmd_string(engine, "LIST_ADD", + (i % 2 == 0) ? "0" : "1", 0) != 1) || + (ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0) != 1)) { + ENGINE_free(engine); + fprintf(stderr, "Failed to load engine in lifetime test\n"); + goto cleanup; + } + if (ENGINE_free(engine) != 1) { + fprintf(stderr, "Failed to release engine in lifetime test\n"); + goto cleanup; + } + if ((i % 2 != 0) && (ENGINE_remove(engine) != 1)) { + fprintf(stderr, "Failed to remove engine in lifetime test\n"); + goto cleanup; + } +#if defined(HAVE_DLFCN_H) && defined(RTLD_NOLOAD) + module = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + if (module != NULL) { + dlclose(module); + fprintf(stderr, "Engine module remained loaded after release\n"); + goto cleanup; + } +#endif + } + ret = 0; +cleanup: +#if OPENSSL_VERSION_NUMBER < 0x10100000L + ENGINE_cleanup(); +#endif + ERR_clear_error(); +#if OPENSSL_VERSION_NUMBER < 0x10100000L && defined(HAVE_PTHREAD) && \ + !defined(WE_SINGLE_THREADED) + CRYPTO_set_locking_callback(NULL); + for (i = 0; i < initialized; i++) + pthread_mutex_destroy(&test_openssl_locks[i]); +#endif + return ret; +#else + return 77; +#endif +} diff --git a/test/test_engine_pbe_init.c b/test/test_engine_pbe_init.c new file mode 100644 index 00000000..adbd5e44 --- /dev/null +++ b/test/test_engine_pbe_init.c @@ -0,0 +1,522 @@ +/* test_engine_pbe_init.c + * + * Copyright (C) 2006-2026 wolfSSL Inc. + * + * This file is part of wolfengine. + * + * wolfengine is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfengine 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef WOLFENGINE_USER_SETTINGS +#include "user_settings.h" +#else +#include +#endif +#include + +#if defined(WE_HAVE_PBE) && !defined(NO_PWDBASED) && \ + !defined(WE_NO_DYNAMIC_ENGINE) +extern int bind_engine(ENGINE *engine, const char *id, + const dynamic_fns *functions); + +static int test_failure_enabled; +static int test_pbe_failures; +static int test_method_failures; +static int test_pbe_attempts; +static int test_source_missing; +static int test_method_attempts; +static int test_method_failure_at; +static int test_methods_live; +static void *test_methods[128]; +static int test_method_sequence[128]; +static unsigned int test_method_failed_classes; + +enum { + TEST_METHOD_EVP = 1, + TEST_METHOD_ASN1 = 2, + TEST_METHOD_RSA = 4, + TEST_METHOD_DH = 8, + TEST_METHOD_EC_KEY = 16, + TEST_METHOD_ECDSA = 32 +}; + +static const int test_pbe_types[] = { EVP_PBE_TYPE_OUTER, +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + EVP_PBE_TYPE_KDF, +#else + EVP_PBE_TYPE_OUTER, +#endif + EVP_PBE_TYPE_OUTER }; +static const int test_pbe_nids[] = { NID_id_pbkdf2, +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + NID_id_pbkdf2, +#else + NID_pbes2, +#endif + NID_pbe_WithSHA1And3_Key_TripleDES_CBC }; + +static void test_pbe_callbacks(EVP_PBE_KEYGEN **callbacks) +{ + int i; + + for (i = 0; i < 3; i++) { + callbacks[i] = NULL; + EVP_PBE_find(test_pbe_types[i], test_pbe_nids[i], NULL, NULL, + &callbacks[i]); + } +} + +static int test_pbe_callbacks_equal(EVP_PBE_KEYGEN **expected) +{ + int i; + EVP_PBE_KEYGEN *current[3]; + + test_pbe_callbacks(current); + for (i = 0; i < 3; i++) { + if (current[i] != expected[i]) + return 0; + } + return 1; +} + +static int test_pbe_callback_result(int expected) +{ + static const unsigned char parameters[] = { + 0x30, 0x24, 0x04, 0x10, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x02, 0x02, 0x08, 0x00, + 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x02, 0x09, 0x05, 0x00 + }; + int err = 1; + EVP_PBE_KEYGEN *callback = NULL; + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + ASN1_TYPE *param = ASN1_TYPE_new(); + ASN1_STRING *sequence = ASN1_STRING_type_new(V_ASN1_SEQUENCE); + + if ((ctx == NULL) || (param == NULL) || (sequence == NULL)) { + goto cleanup; + } + if (ASN1_STRING_set(sequence, parameters, sizeof(parameters)) != 1) { + goto cleanup; + } + ASN1_TYPE_set(param, V_ASN1_SEQUENCE, sequence); + sequence = NULL; + if ((EVP_PBE_find(EVP_PBE_TYPE_OUTER, NID_id_pbkdf2, NULL, NULL, + &callback) != 1) || (callback == NULL)) { + goto cleanup; + } + if (EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, NULL, NULL, 1) != 1) { + goto cleanup; + } + err = callback(ctx, "initialization-check", 20, param, NULL, NULL, 1) != + expected; +cleanup: + ASN1_STRING_free(sequence); + ASN1_TYPE_free(param); + EVP_CIPHER_CTX_free(ctx); + return err; +} + +static const char *test_allocation_source(const char *file) +{ + const char *name; + const char *windowsName; + + name = (file == NULL) ? "" : file; + windowsName = strrchr(name, '\\'); + if (windowsName != NULL) + name = windowsName + 1; + file = strrchr(name, '/'); + if (file != NULL) + name = file + 1; + return name; +} + +static unsigned int test_method_source(const char *file) +{ + const char *name = test_allocation_source(file); + + if ((strcmp(name, "evp_lib.c") == 0) || + (strcmp(name, "cmeth_lib.c") == 0) || + (strcmp(name, "pmeth_lib.c") == 0) || + (strcmp(name, "we_openssl_bc.c") == 0)) { + return TEST_METHOD_EVP; + } + if (strcmp(name, "ameth_lib.c") == 0) + return TEST_METHOD_ASN1; + if (strcmp(name, "rsa_meth.c") == 0) + return TEST_METHOD_RSA; + if (strcmp(name, "dh_meth.c") == 0) + return TEST_METHOD_DH; + if (strcmp(name, "ec_kmeth.c") == 0) + return TEST_METHOD_EC_KEY; + if (strcmp(name, "ecs_lib.c") == 0) + return TEST_METHOD_ECDSA; + return 0; +} + +static void test_method_registry_aliases(void) +{ + const EVP_PKEY_ASN1_METHOD *method; + int flags; + int i; + int j; + + /* Callback-free aliases belong to OpenSSL's process-wide registry. */ + for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { + method = EVP_PKEY_asn1_get0(i); + flags = 0; + if ((EVP_PKEY_asn1_get0_info(NULL, NULL, &flags, NULL, NULL, + method) == 1) && + ((flags & ASN1_PKEY_ALIAS) != 0)) { + for (j = 0; j < 128; j++) { + if (test_methods[j] == method) { + test_methods[j] = NULL; + test_methods_live--; + break; + } + } + } + } +} + +static int test_allocation_allowed(const char *file) +{ + const char *name; + + if (test_failure_enabled == 0) + return 1; + name = test_allocation_source(file); + if (name[0] == '\0') { + test_source_missing = 1; + return 1; + } + if (test_method_source(file)) { + test_method_attempts++; + if ((test_failure_enabled == 1) || + ((test_failure_enabled == 4) && + (test_method_attempts == test_method_failure_at))) { + test_method_failures++; + if (test_failure_enabled == 4) + test_method_failed_classes |= test_method_source(file); + return 0; + } + } + if (strcmp(name, "evp_pbe.c") == 0) { + test_pbe_attempts++; + if ((test_failure_enabled == 2) || + ((test_failure_enabled == 3) && (test_pbe_attempts == 2))) { + test_pbe_failures++; + return 0; + } + } + return 1; +} + +static void *test_openssl_malloc(size_t size, const char *file, int line) +{ + void *ptr; + int i; + + (void)line; + ptr = test_allocation_allowed(file) ? malloc(size) : NULL; + if ((ptr != NULL) && (test_failure_enabled == 4) && + test_method_source(file)) { + for (i = 0; i < 128; i++) { + if (test_methods[i] == NULL) { + test_methods[i] = ptr; + test_method_sequence[i] = test_method_attempts; + test_methods_live++; + break; + } + } + if (i == 128) { + free(ptr); + ptr = NULL; + } + } + return ptr; +} + +static void *test_openssl_realloc(void *ptr, size_t size, + const char *file, int line) +{ + (void)line; + return test_allocation_allowed(file) ? realloc(ptr, size) : NULL; +} + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L +static void test_openssl_free(void *ptr, const char *file, int line) +#else +static void test_openssl_free(void *ptr) +#endif +{ + int i; + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + (void)file; + (void)line; +#endif + for (i = 0; (ptr != NULL) && (i < 128); i++) { + if (test_methods[i] == ptr) { + test_methods[i] = NULL; + test_methods_live--; + break; + } + } + free(ptr); +} +#endif + +int main(void) +{ +#if defined(WE_HAVE_PBE) && !defined(NO_PWDBASED) && \ + !defined(WE_NO_DYNAMIC_ENGINE) + int err = 0; + int attempt; + int rc; + ENGINE *engine; + ENGINE *pendingEngine = NULL; + EVP_PKEY_CTX *keyCtx = NULL; + ENGINE_PKEY_METHS_PTR keyMethods; + const int *keyNids = NULL; + EVP_PKEY_METHOD *method; + dynamic_fns functions; + EVP_PBE_KEYGEN *original[3]; + int targets[128]; + int targetCount = 0; + unsigned int expectedClasses = 0; + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + rc = CRYPTO_set_mem_functions(test_openssl_malloc, + test_openssl_realloc, test_openssl_free); +#else + rc = CRYPTO_set_mem_ex_functions(test_openssl_malloc, + test_openssl_realloc, test_openssl_free); +#endif + if (rc != 1) { + fprintf(stderr, "Failed to install PBE allocation test callbacks\n"); + return 1; + } + test_failure_enabled = 1; + method = EVP_PKEY_meth_new(EVP_PKEY_HMAC, 0); + test_failure_enabled = 0; + if (test_source_missing != 0) { + EVP_PKEY_meth_free(method); + fprintf(stderr, "SKIP: OpenSSL allocation source names unavailable\n"); + return 77; + } + if ((method != NULL) || (test_method_failures != 1)) { + EVP_PKEY_meth_free(method); + fprintf(stderr, "Method allocation failure hook did not run\n"); + return 1; + } + test_method_failures = 0; + memset(&functions, 0, sizeof(functions)); + functions.static_state = ENGINE_get_static_state(); + ERR_put_error(ERR_LIB_EVP, 0, ERR_R_MALLOC_FAILURE, __FILE__, __LINE__); + ERR_clear_error(); + test_pbe_callbacks(original); + + for (attempt = 0; (attempt < 3) && (err == 0); attempt++) { + engine = ENGINE_new(); + if (engine == NULL) + return 1; + test_failure_enabled = 1; + rc = bind_engine(engine, wolfengine_id, &functions); + test_failure_enabled = 0; + if ((rc != 0) || (test_method_failures != attempt + 1) || + (test_pbe_attempts != 0) || !test_pbe_callbacks_equal(original)) { + fprintf(stderr, "Failed engine initialization changed PBE callbacks\n"); + err = 1; + } + ENGINE_free(engine); + ERR_clear_error(); + } + for (attempt = 0; (attempt < 3) && (err == 0); attempt++) { + engine = ENGINE_new(); + if (engine == NULL) + return 1; + test_failure_enabled = 2; + rc = bind_engine(engine, wolfengine_id, &functions); + test_failure_enabled = 0; + if ((rc != 0) || (test_pbe_failures != attempt + 1) || + !test_pbe_callbacks_equal(original)) { + fprintf(stderr, "Failed PBE setup changed registry callbacks\n"); + err = 1; + } + if ((rc == 0) && ((ENGINE_get_pkey_meths(engine) != NULL) || + (ENGINE_get_pkey_asn1_meths(engine) != NULL))) { + fprintf(stderr, "Failed bind retained key method callbacks\n"); + err = 1; + } + ENGINE_free(engine); + ERR_clear_error(); + } + if (err == 0) { + engine = ENGINE_new(); + if (engine == NULL) + return 1; + test_pbe_attempts = 0; + test_failure_enabled = 3; + rc = bind_engine(engine, wolfengine_id, &functions); + test_failure_enabled = 0; + if ((rc != 0) || (test_pbe_attempts != 2) || + (test_pbe_failures != 4) || (test_pbe_callback_result(0) != 0)) { + fprintf(stderr, "Incomplete PBE registration enabled callbacks\n"); + err = 1; + } + if ((rc == 0) && ((ENGINE_get_pkey_meths(engine) != NULL) || + (ENGINE_get_pkey_asn1_meths(engine) != NULL))) { + fprintf(stderr, "Failed bind retained key method callbacks\n"); + err = 1; + } + pendingEngine = engine; + ERR_clear_error(); + } + if (err == 0) { + engine = ENGINE_new(); + if ((engine == NULL) || + (bind_engine(engine, wolfengine_id, &functions) != 1)) { + fprintf(stderr, "Engine did not recover after PBE setup failure\n"); + err = 1; + } + ENGINE_free(pendingEngine); + pendingEngine = NULL; + if (err == 0) { + keyMethods = ENGINE_get_pkey_meths(engine); + if ((keyMethods != NULL) && + (keyMethods(engine, NULL, &keyNids, 0) > 0)) { + keyCtx = EVP_PKEY_CTX_new_id(keyNids[0], engine); + if (keyCtx == NULL) { + fprintf(stderr, "Accepted key method is unavailable\n"); + err = 1; + } + EVP_PKEY_CTX_free(keyCtx); + } + } + ENGINE_free(engine); + if ((err == 0) && (test_pbe_callback_result(1) != 0)) { + fprintf(stderr, "Accepted PBE callbacks did not retain their lifetime\n"); + err = 1; + } + } + ENGINE_free(pendingEngine); + if (err == 0) { + engine = ENGINE_new(); + test_method_attempts = 0; + test_method_failure_at = 0; + test_failure_enabled = 4; + rc = (engine == NULL) ? 0 : + bind_engine(engine, wolfengine_id, &functions); + test_failure_enabled = 0; + if (rc != 1) { + fprintf(stderr, "Failed to collect engine method allocations\n"); + err = 1; + } + test_method_registry_aliases(); + for (attempt = 0; attempt < 128; attempt++) { + if (test_methods[attempt] != NULL) + targets[targetCount++] = test_method_sequence[attempt]; + } + ENGINE_free(engine); + if (test_methods_live != 0) { + fprintf(stderr, "Accepted engine retained method allocations\n"); + err = 1; + } + ERR_clear_error(); + } +#if defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC) + expectedClasses |= TEST_METHOD_ASN1; +#endif +#if OPENSSL_VERSION_NUMBER >= 0x10100000L +#ifdef WE_HAVE_RSA + expectedClasses |= TEST_METHOD_RSA; +#endif +#ifdef WE_HAVE_DH + expectedClasses |= TEST_METHOD_DH; +#endif +#if defined(WE_HAVE_ECC) && defined(WE_HAVE_EC_KEY) + expectedClasses |= TEST_METHOD_EC_KEY; +#endif +#else +#if defined(WE_HAVE_RSA) || defined(WE_HAVE_DH) + expectedClasses |= TEST_METHOD_EVP; +#endif +#if defined(WE_HAVE_ECC) && defined(WE_HAVE_ECDSA) + expectedClasses |= TEST_METHOD_ECDSA; +#endif +#if defined(WE_HAVE_ECC) && defined(WE_HAVE_ECDH) + expectedClasses |= TEST_METHOD_EVP; +#endif +#endif + for (attempt = 0; (attempt < targetCount) && (err == 0); attempt++) { + engine = ENGINE_new(); + if (engine == NULL) + return 1; + test_method_attempts = 0; + test_method_failures = 0; + test_method_failure_at = targets[attempt]; + test_failure_enabled = 4; + rc = bind_engine(engine, wolfengine_id, &functions); + test_failure_enabled = 0; + ENGINE_free(engine); + test_method_registry_aliases(); + if ((rc != 0) || (test_methods_live != 0) || + (test_method_failures != 1)) { + fprintf(stderr, "Method rollback returned %d with %d failures " + "and %d live allocations\n", rc, test_method_failures, + test_methods_live); + err = 1; + } + ERR_clear_error(); + if (err != 0) + break; + engine = ENGINE_new(); + if ((engine == NULL) || + (bind_engine(engine, wolfengine_id, &functions) != 1)) { + fprintf(stderr, "Engine did not recover after method setup failure\n"); + err = 1; + } + ENGINE_free(engine); + ERR_clear_error(); + } + if ((err == 0) && ((test_method_failed_classes & expectedClasses) != + expectedClasses)) { + fprintf(stderr, "Method allocation sweep missed enabled constructors\n"); + err = 1; + } + if (err == 0) { + printf("PASS: initialization rollback and retry across %d method " + "allocation failures, constructor classes 0x%x\n", targetCount, + test_method_failed_classes); + } + EVP_PBE_cleanup(); + ERR_clear_error(); + return err; +#else + return 77; +#endif +} diff --git a/test/test_hkdf.c b/test/test_hkdf.c index dcfb09ae..67df419a 100644 --- a/test/test_hkdf.c +++ b/test/test_hkdf.c @@ -23,6 +23,15 @@ #ifdef WE_HAVE_HKDF +typedef struct test_HkdfState { + int mode; + int mdType; + unsigned char *key; + size_t keySz; + unsigned char *salt; + size_t saltSz; +} test_HkdfState; + static int test_hkdf_calc(ENGINE *e, unsigned char *key, int keyLen, const EVP_MD *md, int mode) { @@ -96,6 +105,170 @@ static int test_hkdf_calc(ENGINE *e, unsigned char *key, int keyLen, return err; } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L +static int test_hkdf_extract_size_calc(ENGINE *e) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + unsigned char inKey[32] = { 0, }; + size_t len = 0; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if (ctx == NULL) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive_init(ctx) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_hkdf_mode(ctx, + EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, inKey, sizeof(inKey)) != 1)) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive(ctx, NULL, &len) != 1)) { + err = 1; + } + if ((err == 0) && (len != (size_t)EVP_MD_size(EVP_sha256()))) { + err = 1; + } + + EVP_PKEY_CTX_free(ctx); + return err; +} + +static int test_hkdf_extract_size(ENGINE *e) +{ + int err; + + PRINT_MSG("Extract size with OpenSSL"); + err = test_hkdf_extract_size_calc(NULL); + if (err == 0) { + PRINT_MSG("Extract size with wolfSSL"); + err = test_hkdf_extract_size_calc(e); + } + + return err; +} + +#if defined(WE_HAVE_SHA256) || defined(WE_HAVE_SHA512) +static int test_hkdf_extract_capacity(ENGINE *e, const EVP_MD *md) +{ + int err = 0; + int i; + int rc; + EVP_PKEY_CTX *ctx = NULL; + unsigned char inKey[32] = { 0 }; + unsigned char salt[32] = { 0 }; + unsigned char reference[EVP_MAX_MD_SIZE]; + unsigned char out[EVP_MAX_MD_SIZE + 3]; + unsigned char expected[sizeof(out)]; + size_t digestSz = (size_t)EVP_MD_size(md); + size_t capacities[4]; + size_t len = 0; + + capacities[0] = 0; + capacities[1] = digestSz - 1; + capacities[2] = digestSz; + capacities[3] = digestSz + 1; + err = test_hkdf_calc(NULL, reference, (int)digestSz, md, + EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY); + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if ((ctx == NULL) || (EVP_PKEY_derive_init(ctx) != 1) || + (EVP_PKEY_CTX_hkdf_mode(ctx, + EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) != 1) || + (EVP_PKEY_CTX_set_hkdf_md(ctx, md) != 1) || + (EVP_PKEY_CTX_set1_hkdf_key(ctx, inKey, sizeof(inKey)) != 1) || + (EVP_PKEY_CTX_set1_hkdf_salt(ctx, salt, sizeof(salt)) != 1)) { + err = 1; + } + if ((err == 0) && + ((EVP_PKEY_derive(ctx, NULL, &len) != 1) || (len != digestSz))) { + err = 1; + } + for (i = 0; (err == 0) && (i < 4); i++) { + memset(out, 0xa5, sizeof(out)); + memset(expected, 0xa5, sizeof(expected)); + len = capacities[i]; + rc = EVP_PKEY_derive(ctx, out + 1, &len); + if (capacities[i] < digestSz) { + if ((rc != 0) || (len != capacities[i])) { + PRINT_MSG("Extract accepted insufficient output capacity"); + err = 1; + } + } + else { + memcpy(expected + 1, reference, digestSz); + if ((rc != 1) || (len != digestSz)) { + err = 1; + } + } + if (memcmp(out, expected, sizeof(out)) != 0) { + PRINT_MSG("Extract changed data outside its output capacity"); + err = 1; + } + } + + EVP_PKEY_CTX_free(ctx); + return err; +} +#endif + +static int test_hkdf_oversized_output(ENGINE *e, int mode) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + unsigned char key[32] = { 0 }; + unsigned char out[1]; + size_t len = (size_t)(word32)-1; + + if (sizeof(size_t) == sizeof(word32)) { + return 0; + } + len += 2U; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if (ctx == NULL) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive_init(ctx) != 1)) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_CTX_hkdf_mode(ctx, mode) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, key, sizeof(key)) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_add1_hkdf_info(ctx, key, sizeof(key)) != 1)) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive(ctx, out, &len) == 1)) { + err = 1; + } + len = ((size_t)EVP_MD_size(EVP_sha256()) * 255U) + 1U; + if ((err == 0) && (EVP_PKEY_derive(ctx, out, &len) == 1)) { + err = 1; + } + + EVP_PKEY_CTX_free(ctx); + return err; +} +#endif + static int test_hkdf_md(ENGINE *e, const EVP_MD *md, int mode) { int err = 0; @@ -129,6 +302,185 @@ static int test_hkdf_md(ENGINE *e, const EVP_MD *md, int mode) return err; } +static int test_hkdf_empty_key_calc(ENGINE *e, unsigned char *out, + size_t outSz) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + unsigned char empty = 0; + size_t len = outSz; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if (ctx == NULL) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive_init(ctx) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, &empty, 0) != 1)) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive(ctx, out, &len) != 1)) { + err = 1; + } + if ((err == 0) && (len != outSz)) { + err = 1; + } + + EVP_PKEY_CTX_free(ctx); + return err; +} + +static int test_hkdf_empty_key(ENGINE *e) +{ + unsigned char key[32]; + + return test_hkdf_empty_key_calc(e, key, sizeof(key)); +} + +static int test_hkdf_setter_order_calc(ENGINE *e, int lastCtrl, + unsigned char *out, size_t outSz) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + unsigned char key[32] = { 1 }; + unsigned char salt[32] = { 2 }; + unsigned char info[32] = { 3 }; + size_t len = outSz; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if (ctx == NULL) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive_init(ctx) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) != 1)) { + err = 1; + } + if ((err == 0) && (lastCtrl != EVP_PKEY_CTRL_HKDF_KEY) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, key, sizeof(key)) != 1)) { + err = 1; + } + if ((err == 0) && (lastCtrl != EVP_PKEY_CTRL_HKDF_SALT) && + (EVP_PKEY_CTX_set1_hkdf_salt(ctx, salt, sizeof(salt)) != 1)) { + err = 1; + } + if ((err == 0) && (lastCtrl != EVP_PKEY_CTRL_HKDF_INFO) && + (EVP_PKEY_CTX_add1_hkdf_info(ctx, info, sizeof(info)) != 1)) { + err = 1; + } + if ((err == 0) && (lastCtrl == EVP_PKEY_CTRL_HKDF_KEY) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, key, sizeof(key)) != 1)) { + err = 1; + } + if ((err == 0) && (lastCtrl == EVP_PKEY_CTRL_HKDF_SALT) && + (EVP_PKEY_CTX_set1_hkdf_salt(ctx, salt, sizeof(salt)) != 1)) { + err = 1; + } + if ((err == 0) && (lastCtrl == EVP_PKEY_CTRL_HKDF_INFO) && + (EVP_PKEY_CTX_add1_hkdf_info(ctx, info, sizeof(info)) != 1)) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive(ctx, out, &len) != 1)) { + err = 1; + } + if ((err == 0) && (len != outSz)) { + err = 1; + } + + EVP_PKEY_CTX_free(ctx); + return err; +} + +static int test_hkdf_setter_order(ENGINE *e) +{ + int err; + unsigned char expected[32]; + unsigned char actual[32]; + + err = test_hkdf_setter_order_calc(NULL, EVP_PKEY_CTRL_HKDF_INFO, + expected, sizeof(expected)); + if (err == 0) { + err = test_hkdf_setter_order_calc(e, EVP_PKEY_CTRL_HKDF_KEY, + actual, sizeof(actual)); + } + if ((err == 0) && (memcmp(expected, actual, sizeof(expected)) != 0)) { + err = 1; + } + if (err == 0) { + err = test_hkdf_setter_order_calc(e, EVP_PKEY_CTRL_HKDF_SALT, + actual, sizeof(actual)); + } + if ((err == 0) && (memcmp(expected, actual, sizeof(expected)) != 0)) { + err = 1; + } + + return err; +} + +static int test_hkdf_reuse(ENGINE *e) +{ + int err = 0; + int i; + EVP_PKEY_CTX *ctx = NULL; + unsigned char key[32] = { 1 }; + unsigned char salt[32] = { 2 }; + unsigned char info[32] = { 3 }; + unsigned char expected[32]; + unsigned char actual[32]; + size_t len; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if (ctx == NULL) { + err = 1; + } + for (i = 0; (err == 0) && (i < 2); i++) { + len = sizeof(actual); + if (EVP_PKEY_derive_init(ctx) != 1) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, key, sizeof(key)) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_salt(ctx, salt, sizeof(salt)) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_add1_hkdf_info(ctx, info, sizeof(info)) != 1)) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive(ctx, actual, &len) != 1)) { + err = 1; + } + if ((err == 0) && (len != sizeof(actual))) { + err = 1; + } + if ((err == 0) && (i == 0)) { + XMEMCPY(expected, actual, sizeof(expected)); + } + else if ((err == 0) && + (memcmp(expected, actual, sizeof(expected)) != 0)) { + err = 1; + } + } + + EVP_PKEY_CTX_free(ctx); + return err; +} + static int test_hkdf_str_calc(ENGINE *e, unsigned char *key, int keyLen, const char *md, const char *mode) { @@ -400,6 +752,139 @@ static int test_hkdf_fail_calc(ENGINE *e) return err; } +static int test_hkdf_key_failure_state(ENGINE *e) +{ + int err = 0; + int i; + EVP_PKEY_CTX *ctx = NULL; + unsigned char key[1] = { 0 }; + unsigned char out[32]; + unsigned char unchanged[sizeof(out)]; + size_t len = 0; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if (ctx == NULL) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive_init(ctx) != 1)) { + err = 1; + } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L + if ((err == 0) && + (EVP_PKEY_CTX_hkdf_mode(ctx, + EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY) != 1)) { + err = 1; + } +#endif + if ((err == 0) && + (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) != 1)) { + err = 1; + } + memset(unchanged, 0xa5, sizeof(unchanged)); + for (i = 0; (err == 0) && (i < 2); i++) { + if (EVP_PKEY_CTX_set1_hkdf_key(ctx, key, sizeof(key)) != 1) { + err = 1; + } + len = sizeof(out); + if ((err == 0) && (EVP_PKEY_derive(ctx, out, &len) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, i == 0 ? NULL : key, + i == 0 ? 1 : -1) != 0)) { + err = 1; + } + len = 0; + if ((err == 0) && (EVP_PKEY_derive(ctx, NULL, &len) != 0)) { + err = 1; + } + memcpy(out, unchanged, sizeof(out)); + len = sizeof(out); + if ((err == 0) && ((EVP_PKEY_derive(ctx, out, &len) != 0) || + (len != sizeof(out)) || + (memcmp(out, unchanged, sizeof(out)) != 0))) { + err = 1; + } + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, key, sizeof(key)) != 1)) { + err = 1; + } + len = sizeof(out); + if ((err == 0) && ((EVP_PKEY_derive(ctx, out, &len) != 1) || + (len != sizeof(out)))) { + err = 1; + } + + EVP_PKEY_CTX_free(ctx); + return err; +} + +static int test_hkdf_salt_failure_state(ENGINE *e) +{ + int err = 0; + int i; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY_CTX *reference = NULL; + test_HkdfState *state = NULL; + unsigned char key[32] = { 0 }; + unsigned char salt[32] = { 1 }; + unsigned char out[32]; + unsigned char expected[sizeof(out)]; + size_t len = sizeof(out); + + reference = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL); + if ((reference == NULL) || (EVP_PKEY_derive_init(reference) != 1) || + (EVP_PKEY_CTX_set_hkdf_md(reference, EVP_sha256()) != 1) || + (EVP_PKEY_CTX_set1_hkdf_key(reference, key, sizeof(key)) != 1) || + (EVP_PKEY_derive(reference, expected, &len) != 1) || + (len != sizeof(expected))) { + err = 1; + } + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, e); + if (ctx == NULL) { + err = 1; + } + if ((err == 0) && (EVP_PKEY_derive_init(ctx) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_sha256()) != 1)) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_key(ctx, key, sizeof(key)) != 1)) { + err = 1; + } + for (i = 0; (err == 0) && (i < 2); i++) { + if (EVP_PKEY_CTX_set1_hkdf_salt(ctx, salt, sizeof(salt)) != 1) { + err = 1; + } + if ((err == 0) && + (EVP_PKEY_CTX_set1_hkdf_salt(ctx, i == 0 ? NULL : salt, + i == 0 ? 1 : -1) != 0)) { + err = 1; + } + if (err == 0) { + state = (test_HkdfState *)EVP_PKEY_CTX_get_data(ctx); + if ((state == NULL) || (state->salt != NULL) || + (state->saltSz != 0)) { + err = 1; + } + } + len = sizeof(out); + if ((err == 0) && ((EVP_PKEY_derive(ctx, out, &len) != 1) || + (len != sizeof(out)) || + (memcmp(out, expected, sizeof(out)) != 0))) { + err = 1; + } + } + + EVP_PKEY_CTX_free(reference); + EVP_PKEY_CTX_free(ctx); + return err; +} + static int test_hkdf_fail(ENGINE *e) { int err; @@ -410,6 +895,14 @@ static int test_hkdf_fail(ENGINE *e) PRINT_MSG("Failure cases with wolfSSL"); err = test_hkdf_fail_calc(e); } + if (err == 0) { + PRINT_MSG("Key failure state with wolfSSL"); + err = test_hkdf_key_failure_state(e); + } + if (err == 0) { + PRINT_MSG("Salt failure state with wolfSSL"); + err = test_hkdf_salt_failure_state(e); + } return err; } @@ -449,6 +942,41 @@ int test_hkdf(ENGINE *e, void *data) if (err == 0) { err = test_hkdf_fail(e); } + if (err == 0) { + err = test_hkdf_empty_key(e); + } + if (err == 0) { + err = test_hkdf_setter_order(e); + } + if (err == 0) { + PRINT_MSG("Context reuse with wolfSSL"); + err = test_hkdf_reuse(e); + } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L + if (err == 0) { + err = test_hkdf_extract_size(e); + } +#ifdef WE_HAVE_SHA256 + if (err == 0) { + PRINT_MSG("Extract capacity with SHA-256"); + err = test_hkdf_extract_capacity(e, EVP_sha256()); + } +#endif +#ifdef WE_HAVE_SHA512 + if (err == 0) { + PRINT_MSG("Extract capacity with SHA-512"); + err = test_hkdf_extract_capacity(e, EVP_sha512()); + } +#endif + if (err == 0) { + err = test_hkdf_oversized_output(e, + EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND); + } + if (err == 0) { + err = test_hkdf_oversized_output(e, + EVP_PKEY_HKDEF_MODE_EXPAND_ONLY); + } +#endif return err; } @@ -462,6 +990,7 @@ int test_hkdf_bad_md(ENGINE *e, void *data) #else int err = 0; EVP_PKEY_CTX *ctx = NULL; + const EVP_MD *unsupported = NULL; (void)data; @@ -474,6 +1003,20 @@ int test_hkdf_bad_md(ENGINE *e, void *data) /* Unknown digest name must fail, not dereference a NULL digest. */ err = EVP_PKEY_CTX_ctrl_str(ctx, "md", "notadigest") > 0; } + if (err == 0) { + unsupported = EVP_md_null(); + err = unsupported == NULL; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "md", "SHA512-224") > 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_hkdf_md(ctx, unsupported) > 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_DERIVE, + EVP_PKEY_CTRL_HKDF_MD, 0, NULL) > 0; + } EVP_PKEY_CTX_free(ctx); diff --git a/test/test_hmac.c b/test/test_hmac.c index 99810fc2..a4b2be77 100644 --- a/test/test_hmac.c +++ b/test/test_hmac.c @@ -20,9 +20,171 @@ */ #include "unit.h" +#include +#include +#include +#include #ifdef WE_HAVE_HMAC +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FIND) && \ + !defined(TEST_MULTITHREADED) +#include +#include + +#define TEST_HMAC_CB_DEVID 27182 + +typedef struct TestHmacCallback { + byte expectedKey[64]; + uintptr_t sourceKey; + int stage; +} TestHmacCallback; + +static TestHmacCallback* testHmacCallback; + +static int test_hmac_find_device(int devId, int algoType) +{ + if (testHmacCallback != NULL && algoType == WC_ALGO_TYPE_HMAC && + devId == INVALID_DEVID) { + return TEST_HMAC_CB_DEVID; + } + return devId; +} + +static int test_hmac_crypto_callback(int devId, wc_CryptoInfo* info, + void* context) +{ + static const byte message[] = "Hi There"; + TestHmacCallback* state = (TestHmacCallback*)context; + const byte* key; + unsigned int macLen = 0; + + if (info == NULL || info->algo_type != WC_ALGO_TYPE_HMAC) + return CRYPTOCB_UNAVAILABLE; + if (devId != TEST_HMAC_CB_DEVID || state == NULL || + info->hmac.hmac == NULL || info->hmac.macType != WC_SHA256) + return BAD_FUNC_ARG; + + key = info->hmac.hmac->keyRaw; + if (key == NULL || info->hmac.hmac->keyLen != sizeof(state->expectedKey) || + memcmp(key, state->expectedKey, sizeof(state->expectedKey)) != 0) + return BAD_FUNC_ARG; + + if (state->stage == 0 && info->hmac.digest == NULL && + info->hmac.inSz == 3 && memcmp(info->hmac.in, "Hi ", 3) == 0) { + state->sourceKey = (uintptr_t)key; + state->stage = 1; + return 0; + } + if (state->stage == 1 && info->hmac.digest == NULL && + info->hmac.inSz == 5 && memcmp(info->hmac.in, "There", 5) == 0 && + (uintptr_t)key != state->sourceKey) { + state->stage = 2; + return 0; + } + if (state->stage == 2 && info->hmac.in == NULL && + info->hmac.digest != NULL && + HMAC(EVP_sha256(), key, info->hmac.hmac->keyLen, message, + sizeof(message) - 1, info->hmac.digest, &macLen) != NULL && + macLen == 32) { + state->stage = 3; + return 0; + } + return BAD_FUNC_ARG; +} + +static int test_hmac_callback_copy(ENGINE* e, void* data) +{ + static const byte expected[32] = { + 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, + 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, + 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, + 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7 + }; + byte key[20]; + byte mac[sizeof(expected)]; + size_t macLen = sizeof(mac); + TestHmacCallback state; + EVP_MD_CTX *source = NULL, *copy = NULL; + EVP_PKEY* pkey = NULL; + int registered = 0, ret = -1; + + (void)data; + if (e == NULL) + return -1; + memset(&state, 0, sizeof(state)); + memset(key, 0x0b, sizeof(key)); + memset(state.expectedKey, 0x0b, sizeof(key)); + + if (wc_CryptoCb_RegisterDevice(TEST_HMAC_CB_DEVID, + test_hmac_crypto_callback, &state) != 0) { + goto exit; + } + registered = 1; + testHmacCallback = &state; + wc_CryptoCb_SetDeviceFindCb(test_hmac_find_device); + + source = EVP_MD_CTX_new(); + copy = EVP_MD_CTX_new(); + pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, key, sizeof(key)); + if (source == NULL || copy == NULL || pkey == NULL || + EVP_DigestSignInit(source, NULL, EVP_sha256(), e, pkey) != 1 || + EVP_DigestSignUpdate(source, "Hi ", 3) != 1 || + EVP_MD_CTX_copy_ex(copy, source) != 1) { + goto exit; + } + + EVP_MD_CTX_free(source); + source = NULL; + EVP_PKEY_free(pkey); + pkey = NULL; + + if (EVP_DigestSignUpdate(copy, "There", 5) == 1 && + EVP_DigestSignFinal(copy, mac, &macLen) == 1 && + state.stage == 3 && macLen == sizeof(expected) && + memcmp(mac, expected, sizeof(expected)) == 0) + ret = 0; + +exit: + EVP_MD_CTX_free(copy); + EVP_MD_CTX_free(source); + EVP_PKEY_free(pkey); + if (registered) { + wc_CryptoCb_SetDeviceFindCb(NULL); + testHmacCallback = NULL; + wc_CryptoCb_UnRegisterDevice(TEST_HMAC_CB_DEVID); + } + return ret; +} +#endif + +static int test_hmac_ctrl_str(ENGINE *e, const char *type, + const char *value) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, type, value) != 1; + } + if (err == 0) { + err = EVP_PKEY_keygen(ctx, &pkey) != 1; + } + + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(ctx); + + return err; +} + static int test_mac_generation(ENGINE *e, const EVP_MD *md, int pkeyType, unsigned char *pswd, int pswdSz, unsigned char *msg, int len, unsigned char *mac, int *macLen) @@ -113,6 +275,296 @@ static int test_hmac_create_helper(ENGINE *e, void *data, const EVP_MD *md, return ret; } +static int test_hmac_cipher_ctrl(ENGINE *e) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_CIPHER, 0, (void *)EVP_aes_128_cbc()) != 1; + } + + EVP_PKEY_CTX_free(ctx); + + return err; +} + +static int test_hmac_copy_without_key(ENGINE *e) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) + int err = 0; + int allocationFailed; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY_CTX *copy = NULL; + + if (!test_openssl_mem_has_source()) { + PRINT_MSG("Skipping allocation-callsite check without source filenames"); + return 0; + } + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + test_openssl_mem_fail_once(1); + copy = EVP_PKEY_CTX_dup(ctx); + /* The incomplete context cannot copy its HMAC state, but it must not + * try to allocate storage for a key that was never configured. */ + allocationFailed = test_openssl_mem_failure_triggered(); + err = (copy != NULL) || allocationFailed; + } + + EVP_PKEY_CTX_free(copy); + EVP_PKEY_CTX_free(ctx); + + return err; +#else + (void)e; + return 0; +#endif +} + +static int test_hmac_key_replacement_failure(ENGINE *e) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) + int err = 0; + unsigned char oldKey[] = "original key"; + unsigned char newKey[] = "replacement key"; + const unsigned char *key = NULL; + size_t keySz = 0; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + + if (!test_openssl_mem_has_source()) { + PRINT_MSG("Skipping allocation-callsite check without source filenames"); + return 0; + } + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(oldKey), oldKey) != 1; + } + if (err == 0) { + test_openssl_mem_fail_once(sizeof(newKey) + 1); + err = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(newKey), newKey) > 0; + if (!test_openssl_mem_failure_triggered()) { + err = 1; + } + } + if (err == 0) { + err = EVP_PKEY_keygen(ctx, &pkey) != 1; + } + if (err == 0) { + key = EVP_PKEY_get0_hmac(pkey, &keySz); + err = (key == NULL) || (keySz != sizeof(oldKey)) || + (XMEMCMP(key, oldKey, sizeof(oldKey)) != 0); + } + + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(ctx); + + return err; +#else + (void)e; + return 0; +#endif +} + +static int test_hmac_short_key_init(ENGINE *e) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) + int err = 0; + int allocationFailed; + unsigned char key[] = "short HMAC key"; + EVP_MD_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + + if (!test_openssl_mem_has_source()) { + PRINT_MSG("Skipping allocation-callsite check without source filenames"); + return 0; + } + ctx = EVP_MD_CTX_new(); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, key, sizeof(key)); + err = pkey == NULL; + } + if (err == 0) { + test_openssl_mem_fail_once(64); + err = EVP_DigestSignInit(ctx, NULL, EVP_sha256(), e, pkey) != 1; + allocationFailed = test_openssl_mem_failure_triggered(); + if (allocationFailed) { + err = 1; + } + } + + EVP_PKEY_free(pkey); + EVP_MD_CTX_free(ctx); + + return err; +#else + (void)e; + return 0; +#endif +} + +static int test_hmac_failed_copy_cleanup(ENGINE *e) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) + int err = 0; + unsigned char key[] = "duplicate key"; + size_t allocations; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY_CTX *copy = NULL; + + if (!test_openssl_mem_has_source()) { + PRINT_MSG("Skipping allocation-callsite check without source filenames"); + return 0; + } + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HMAC, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_SET_MAC_KEY, sizeof(key), key) != 1; + } + if (err == 0) { + allocations = test_openssl_mem_active(); + test_openssl_mem_expect_next_clear(sizeof(key) + 1); + copy = EVP_PKEY_CTX_dup(ctx); + err = (copy != NULL) || + (test_openssl_mem_active() != allocations) || + (test_openssl_mem_clear_result() != 1); + } + + EVP_PKEY_CTX_free(copy); + EVP_PKEY_CTX_free(ctx); + + return err; +#else + (void)e; + return 0; +#endif +} + +static int test_hmac_alignment_buffer_cleanup(void) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + defined(WE_ALIGNMENT_SAFETY) && !defined(TEST_MULTITHREADED) && \ + !defined(WE_NO_OPENSSL_MALLOC) && \ + ((!defined(WOLFENGINE_DLL) && !defined(HAVE_VISIBILITY)) || \ + defined(WE_MAC_STATIC_TEST)) + int err = 0; + unsigned char key[32] = { 0 }; + unsigned char data[257] = { 0 }; + Hmac hmac; + + if (!test_openssl_mem_has_source()) { + PRINT_MSG("Skipping allocation-callsite check without source filenames"); + return 0; + } + err = wc_HmacInit(&hmac, NULL, INVALID_DEVID) != 0; + if (err == 0) { + err = wc_HmacSetKey(&hmac, WC_SHA512, key, sizeof(key)) != 0; + } + if (err == 0) { + test_openssl_mem_expect_next_clear(WC_SHA512_BLOCK_SIZE); + err = we_hmac_update(&hmac, data + 1, sizeof(data) - 1) != 1; + } + if (err == 0) { + err = test_openssl_mem_clear_result() != 1; + } + + wc_HmacFree(&hmac); + return err; +#else + return 0; +#endif +} + +#if !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) && \ + ((!defined(WOLFENGINE_DLL) && !defined(HAVE_VISIBILITY)) || \ + defined(WE_MAC_STATIC_TEST)) +static int test_hmac_init_failure(Hmac *hmac, void *heap, int devId) +{ + (void)hmac; + (void)heap; + (void)devId; + + return MEMORY_E; +} +#endif + +static int test_hmac_failed_init_cleanup(void) +{ +#if !defined(TEST_MULTITHREADED) && !defined(WE_NO_OPENSSL_MALLOC) && \ + ((!defined(WOLFENGINE_DLL) && !defined(HAVE_VISIBILITY)) || \ + defined(WE_MAC_STATIC_TEST)) + int err = 0; + size_t allocations; + void *data = NULL; + void *originalData = NULL; + EVP_PKEY_CTX *ctx = NULL; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + originalData = EVP_PKEY_CTX_get_data(ctx); + EVP_PKEY_CTX_set_data(ctx, NULL); + allocations = test_openssl_mem_active(); + err = we_hmac_pkey_init_ex(ctx, test_hmac_init_failure) != 0; + data = EVP_PKEY_CTX_get_data(ctx); + if ((data != NULL) || + (test_openssl_mem_active() != allocations)) { + err = 1; + } + } + + if (data != NULL) { + EVP_PKEY_CTX_set_data(ctx, NULL); + OPENSSL_free(data); + } + if (ctx != NULL) { + EVP_PKEY_CTX_set_data(ctx, originalData); + } + EVP_PKEY_CTX_free(ctx); + + return err; +#else + return 0; +#endif +} + int test_hmac_create(ENGINE *e, void *data) { int ret = 0; @@ -123,10 +575,12 @@ int test_hmac_create(ENGINE *e, void *data) PRINT_MSG("Testing with SHA1"); ret = test_hmac_create_helper(e, data, EVP_sha1(), pswd, sizeof(pswd)); +#ifndef HAVE_FIPS if (ret == 0) { PRINT_MSG("Testing with SHA1, 0 length key"); ret = test_hmac_create_helper(e, data, EVP_sha1(), pswd, 0); } +#endif if (ret == 0) { PRINT_MSG("Testing with SHA1, key length larger than block size"); RAND_bytes(bigPswd, sizeof(bigPswd)); @@ -204,8 +658,210 @@ int test_hmac_create(ENGINE *e, void *data) } } #endif + if (ret == 0) { + ret = test_hmac_cipher_ctrl(e); + } + if (ret == 0) { + ret = test_hmac_copy_without_key(e); + } + if (ret == 0) { + ret = test_hmac_key_replacement_failure(e); + } + if (ret == 0) { + ret = test_hmac_short_key_init(e); + } + if (ret == 0) { + ret = test_hmac_failed_copy_cleanup(e); + } + if (ret == 0) { + ret = test_hmac_alignment_buffer_cleanup(); + } + if (ret == 0) { + ret = test_hmac_failed_init_cleanup(); + } +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FIND) && \ + !defined(TEST_MULTITHREADED) + if (ret == 0) { + ret = test_hmac_callback_copy(e, data); + } +#endif + if (ret == 0) { + PRINT_MSG("Testing string key controls"); + ret = test_hmac_ctrl_str(NULL, "key", "string key"); + } + if (ret == 0) { + ret = test_hmac_ctrl_str(e, "key", "string key"); + } + if (ret == 0) { + ret = test_hmac_ctrl_str(NULL, "hexkey", "0011223344556677"); + } + if (ret == 0) { + ret = test_hmac_ctrl_str(e, "hexkey", "0011223344556677"); + } + return ret; +} + +int test_hmac_output_size(ENGINE *e, void *data) +{ + int ret = 0; + unsigned char key[] = "My empire of dirt"; + unsigned char msg[] = "Test message"; + unsigned char mac[EVP_MAX_MD_SIZE]; + unsigned char expected[EVP_MAX_MD_SIZE]; + unsigned int expectedLen = 0; + size_t macLen = 1; + EVP_MD_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + + (void)data; + XMEMSET(mac, 0, sizeof(mac)); + + if (HMAC(EVP_sha256(), key, (int)sizeof(key), msg, sizeof(msg), expected, + &expectedLen) == NULL) + ret = -1; + if (ret == 0) { + ctx = EVP_MD_CTX_new(); + if (ctx == NULL) + ret = -1; + } + if (ret == 0) { + pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, key, sizeof(key)); + if (pkey == NULL) + ret = -1; + } + if (ret == 0) { + ret = EVP_DigestSignInit(ctx, NULL, EVP_sha256(), e, pkey) != 1; + } + if (ret == 0) { + ret = EVP_DigestSignUpdate(ctx, msg, sizeof(msg)) != 1; + } + /* Undersized length, as OpenSSL's TLS PRF passes: the full MAC is still + * written, matching OpenSSL's own HMAC method. */ + if (ret == 0) { + ret = EVP_DigestSignFinal(ctx, mac, &macLen) != 1; + } + if ((ret == 0) && ((macLen != SHA256_DIGEST_LENGTH) || + (macLen != expectedLen))) + ret = -1; + if ((ret == 0) && (XMEMCMP(mac, expected, macLen) != 0)) + ret = -1; + + EVP_PKEY_free(pkey); + EVP_MD_CTX_free(ctx); + + return ret; +} + +int test_hmac_pkey_size(ENGINE *e, void *data) +{ + int ret = 0; + unsigned char key[] = "My empire of dirt"; + EVP_PKEY *pkey; + + (void)data; + pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, key, sizeof(key)); + if (pkey == NULL) + ret = -1; + if ((ret == 0) && (EVP_PKEY_size(pkey) != WC_MAX_DIGEST_SIZE)) + ret = -1; + + EVP_PKEY_free(pkey); + + return ret; +} + +int test_hmac_update_size(ENGINE *e, void *data) +{ + int ret = 0; + unsigned char key[] = "My empire of dirt"; + unsigned char msg = 0; + EVP_MD_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + + (void)data; + ctx = EVP_MD_CTX_new(); + if (ctx == NULL) + ret = -1; + if (ret == 0) { + pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, key, sizeof(key)); + if (pkey == NULL) + ret = -1; + } + if (ret == 0) { + ret = EVP_DigestSignInit(ctx, NULL, EVP_sha256(), e, pkey) != 1; + } + if (ret == 0) { + if (sizeof(size_t) > sizeof(word32)) { + size_t updateLen = UINT32_MAX; + + updateLen++; + if (EVP_DigestSignUpdate(ctx, &msg, updateLen) == 1) + ret = -1; + } + } + + EVP_PKEY_free(pkey); + EVP_MD_CTX_free(ctx); + + return ret; +} + +#if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(TEST_MULTITHREADED) +int test_hmac_raw_key_output_size(ENGINE *e, void *data) +{ + int ret = 0; + int i; + int registered = 0; + unsigned char key[] = "My empire of dirt"; + unsigned char out[sizeof(key)]; + size_t outLen = 0; + EVP_PKEY *pkey = NULL; + + (void)data; + if (ENGINE_register_pkey_asn1_meths(e) != 1) + ret = -1; + else + registered = 1; + if (ret == 0) { + pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL, key, + sizeof(key)); + if (pkey == NULL) + ret = -1; + } + if (registered) + ENGINE_unregister_pkey_asn1_meths(e); +#if OPENSSL_VERSION_NUMBER >= 0x1010103fL + if ((ret == 0) && (EVP_PKEY_get0_engine(pkey) != e)) + ret = -1; +#else + if ((ret == 0) && ((EVP_PKEY_get0_asn1(pkey) == NULL) || + (EVP_PKEY_get0_asn1(pkey) != + ENGINE_get_pkey_asn1_meth(e, EVP_PKEY_HMAC)))) + ret = -1; +#endif + if (ret == 0) { + ret = EVP_PKEY_get_raw_private_key(pkey, NULL, &outLen) != 1; + } + if ((ret == 0) && (outLen != sizeof(key))) + ret = -1; + if (ret == 0) { + XMEMSET(out, 0xa5, sizeof(out)); + outLen = 1; + if (EVP_PKEY_get_raw_private_key(pkey, out, &outLen) == 1) + ret = -1; + } + if ((ret == 0) && (outLen != sizeof(key))) + ret = -1; + for (i = 0; (ret == 0) && (i < (int)sizeof(out)); i++) { + if (out[i] != 0xa5) + ret = -1; + } + + EVP_PKEY_free(pkey); + return ret; } +#endif /* OPENSSL_VERSION_NUMBER >= 0x10101000L && !TEST_MULTITHREADED */ #endif /* WE_HAVE_HMAC */ diff --git a/test/test_openssl_bc.c b/test/test_openssl_bc.c new file mode 100644 index 00000000..89be50b9 --- /dev/null +++ b/test/test_openssl_bc.c @@ -0,0 +1,175 @@ +/* test_openssl_bc.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfengine. + * + * wolfengine is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfengine 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, + * USA + */ + +#include "unit.h" + +#if OPENSSL_VERSION_NUMBER < 0x10100000L + +int test_openssl_bc_method_name(ENGINE *e, void *data) +{ + int err = 0; + RSA_METHOD *rsaMethod = NULL; + DH_METHOD *dhMethod = NULL; + + (void)e; + (void)data; + + rsaMethod = RSA_meth_new(NULL, 0); + if (rsaMethod != NULL) { + PRINT_ERR_MSG("RSA method accepted a NULL name"); + err = 1; + } + RSA_meth_free(rsaMethod); + + dhMethod = DH_meth_new(NULL, 0); + if (dhMethod != NULL) { + PRINT_ERR_MSG("DH method accepted a NULL name"); + err = 1; + } + DH_meth_free(dhMethod); + + return err; +} + +int test_openssl_bc_public_ec_key(ENGINE *e, void *data) +{ + int err = 0; + EC_KEY *key = NULL; + unsigned char *buf = NULL; + + (void)e; + (void)data; + + key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + if (key == NULL) { + PRINT_ERR_MSG("EC key allocation failed"); + err = 1; + } + if ((err == 0) && (EC_KEY_priv2buf(key, &buf) != 0)) { + PRINT_ERR_MSG("Public EC key produced private bytes"); + err = 1; + } + if (buf != NULL) { + PRINT_ERR_MSG("Public EC key allocated a private buffer"); + err = 1; + } + + OPENSSL_free(buf); + EC_KEY_free(key); + return err; +} + +static int test_openssl_bc_ec_private_scalar(int nid, size_t expectedLen) +{ + int err = 0; + size_t i; + size_t len = 0; + EC_KEY *key = NULL; + BIGNUM *priv = NULL; + unsigned char *buf = NULL; + + key = EC_KEY_new_by_curve_name(nid); + priv = BN_new(); + if ((key == NULL) || (priv == NULL)) { + PRINT_ERR_MSG("EC private key allocation failed"); + err = 1; + } + if ((err == 0) && (BN_set_word(priv, 1) != 1)) { + PRINT_ERR_MSG("EC private scalar setup failed"); + err = 1; + } + if ((err == 0) && (EC_KEY_set_private_key(key, priv) != 1)) { + PRINT_ERR_MSG("EC private key setup failed"); + err = 1; + } + if (err == 0) { + len = EC_KEY_priv2buf(key, &buf); + if ((len != expectedLen) || (buf == NULL)) { + PRINT_ERR_MSG("EC private scalar has the wrong encoded length"); + err = 1; + } + } + if (err == 0) { + for (i = 0; i < len - 1; i++) { + if (buf[i] != 0) { + PRINT_ERR_MSG("EC private scalar has invalid leading padding"); + err = 1; + break; + } + } + if ((err == 0) && (buf[len - 1] != 1)) { + PRINT_ERR_MSG("EC private scalar has the wrong encoded value"); + err = 1; + } + } + + OPENSSL_clear_free(buf, len); + BN_clear_free(priv); + EC_KEY_free(key); + return err; +} + +int test_openssl_bc_ec_private_padding(ENGINE *e, void *data) +{ + int err = 0; + size_t len = 0; + EC_KEY *key = NULL; + BIGNUM *priv = NULL; + unsigned char *buf = NULL; + + (void)e; + (void)data; + + err = test_openssl_bc_ec_private_scalar(NID_X9_62_prime256v1, 32); + if (err == 0) { + err = test_openssl_bc_ec_private_scalar(NID_secp521r1, 66); + } + if (err == 0) { + key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + priv = BN_new(); + if ((key == NULL) || (priv == NULL)) { + PRINT_ERR_MSG("EC private key allocation failed"); + err = 1; + } + } + if (err == 0) { + BN_zero(priv); + if (EC_KEY_set_private_key(key, priv) != 1) { + PRINT_ERR_MSG("Zero EC private scalar setup failed"); + err = 1; + } + } + if (err == 0) { + len = EC_KEY_priv2buf(key, &buf); + if ((len != 0) || (buf != NULL)) { + PRINT_ERR_MSG("Zero EC private scalar was encoded"); + err = 1; + } + } + + OPENSSL_clear_free(buf, len); + BN_clear_free(priv); + EC_KEY_free(key); + return err; +} + +#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */ diff --git a/test/test_pbe.c b/test/test_pbe.c index 548fa6a8..ecde6c05 100644 --- a/test/test_pbe.c +++ b/test/test_pbe.c @@ -23,6 +23,8 @@ #ifdef WE_HAVE_PBE +#include + static const unsigned char pbeData[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, @@ -73,7 +75,7 @@ static const unsigned char pbeParamPbe[] = { * OBJ */ static const unsigned char pbeParamPbes2Aes128Cbc[] = { - 0x30, 0x39, + 0x30, 0x4b, 0x30, 0x2a, 0x06, 0x09, 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x05,0x0C, @@ -85,9 +87,12 @@ static const unsigned char pbeParamPbes2Aes128Cbc[] = { 0x30, 0x0a, 0x06, 0x08, 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x02,0x09, - 0x30, 0x0b, + 0x30, 0x1d, 0x06, 0x09, 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x02, + 0x04, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; /* Format of parameters: @@ -105,7 +110,7 @@ static const unsigned char pbeParamPbes2Aes128Cbc[] = { * OBJ */ static const unsigned char pbeParamPbes2Aes256Cbc[] = { - 0x30, 0x36, + 0x30, 0x48, 0x30, 0x27, 0x06, 0x09, 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x05,0x0C, @@ -116,9 +121,12 @@ static const unsigned char pbeParamPbes2Aes256Cbc[] = { 0x30, 0x0a, 0x06, 0x08, 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x02,0x0A, - 0x30, 0x0b, + 0x30, 0x1d, 0x06, 0x09, 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x01,0x2A, + 0x04, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static int test_pbe_encipher(ASN1_OBJECT *obj, ASN1_TYPE *param, @@ -214,6 +222,65 @@ static int test_pbe_sha1_des3_pbkdf1_op(const unsigned char *in, size_t inLen, sizeof(pbeParamPbe), in, inLen, out, outLen, enc_dec); } +int test_pbe_invalid_params(ENGINE *e, void *data) +{ +#ifdef NO_PWDBASED + (void)e; + (void)data; + PRINT_MSG("Not using wolfEngine - PBKDF not available in wolfCrypt"); + return 0; +#else + int err = 0; + int cipherNid = 0; + int digestNid = 0; + EVP_PBE_KEYGEN *keygen = NULL; + EVP_CIPHER_CTX *ctx = NULL; + ASN1_TYPE *param = NULL; + + (void)e; + (void)data; + + if (EVP_PBE_find(EVP_PBE_TYPE_OUTER, NID_id_pbkdf2, &cipherNid, + &digestNid, &keygen) != 1 || keygen == NULL) { + PRINT_MSG("Failed to find PBKDF2 callback"); + err = 1; + } + ctx = EVP_CIPHER_CTX_new(); + if ((err == 0) && (ctx == NULL)) { + PRINT_MSG("Failed to create PBKDF2 cipher context"); + err = 1; + } + if ((err == 0) && (keygen(ctx, "password", 8, NULL, NULL, NULL, 1) != 0)) { + PRINT_MSG("PBKDF2 callback accepted missing parameters"); + err = 1; + } + param = ASN1_TYPE_new(); + if ((err == 0) && (param == NULL)) { + PRINT_MSG("Failed to create PBKDF2 parameters"); + err = 1; + } + if (err == 0) { + ASN1_TYPE_set(param, V_ASN1_NULL, NULL); + if (keygen(ctx, "password", 8, param, NULL, NULL, 1) != 0) { + PRINT_MSG("PBKDF2 callback accepted non-sequence parameters"); + err = 1; + } + } + if (err == 0) { + ASN1_TYPE_set(param, V_ASN1_SEQUENCE, NULL); + if (keygen(ctx, "password", 8, param, NULL, NULL, 1) != 0) { + PRINT_MSG("PBKDF2 callback accepted an empty sequence"); + err = 1; + } + } + + ASN1_TYPE_free(param); + EVP_CIPHER_CTX_free(ctx); + ERR_clear_error(); + return err; +#endif +} + static int test_pbe_sha1_des3_pbkdf1(void) { int err; @@ -339,6 +406,9 @@ static int test_pbe_pbes2_aes256_cbc(void) int test_pbe(ENGINE *e, void *data) { int err; + int cipherNid = NID_undef; + int digestNid = NID_undef; + EVP_PBE_KEYGEN *keygen = NULL; (void)e; (void)data; @@ -347,8 +417,20 @@ int test_pbe(ENGINE *e, void *data) PRINT_MSG("Not using wolfEngine - PBKDF not available in wolfCrypt"); #endif - PRINT_MSG("PBE DES-EDE3-CBC SHA-1"); - err = test_pbe_sha1_des3_pbkdf1(); +#ifndef NO_PWDBASED + if ((EVP_PBE_find(EVP_PBE_TYPE_OUTER, + NID_pbe_WithSHA1And3_Key_TripleDES_CBC, &cipherNid, &digestNid, + &keygen) != 1) || (keygen == NULL) || + (keygen == PKCS12_PBE_keyivgen)) { + PRINT_MSG("wolfEngine PBE key generation is not registered"); + err = 1; + } + else +#endif + { + PRINT_MSG("PBE DES-EDE3-CBC SHA-1"); + err = test_pbe_sha1_des3_pbkdf1(); + } if (err == 0) { PRINT_MSG("PBES2 AES128-CBC HMAC-SHA-256"); err = test_pbe_pbes2_aes128_cbc(); diff --git a/test/test_pbe_lifetime.c b/test/test_pbe_lifetime.c new file mode 100644 index 00000000..51adc998 --- /dev/null +++ b/test/test_pbe_lifetime.c @@ -0,0 +1,216 @@ +/* test_pbe_lifetime.c + * + * Copyright (C) 2006-2026 wolfSSL Inc. + * + * This file is part of wolfengine. + * + * wolfengine is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfengine 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif + +#include + +#include +#ifdef WE_PBE_STATIC_LINK +#include +#endif +#include +#include +#include +#ifdef WOLFENGINE_USER_SETTINGS +#include "user_settings.h" +#else +#include +#endif +#include + +#if defined(_WIN32) +#include +#elif defined(WE_HAVE_DLADDR) +#include +#endif + +#if defined(WE_HAVE_PBE) && !defined(NO_PWDBASED) && \ + (defined(WE_PBE_STATIC_LINK) || (defined(WE_HAVE_SHARED_LIBRARY) && \ + !defined(WE_NO_DYNAMIC_ENGINE))) +static int test_pbe_callback_owner(ENGINE *engine, EVP_PBE_KEYGEN *keygen) +{ + ENGINE_GEN_INT_FUNC_PTR destroy = ENGINE_get_destroy_function(engine); +#if defined(_WIN32) + HMODULE engineModule = NULL; + HMODULE callbackModule = NULL; + DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; +#elif defined(WE_HAVE_DLADDR) + Dl_info engineInfo; + Dl_info callbackInfo; +#endif + + if ((keygen == NULL) || (destroy == NULL)) + return 0; +#if defined(_WIN32) + return (GetModuleHandleExA(flags, (LPCSTR)(const void *)destroy, + &engineModule) != 0) && + (GetModuleHandleExA(flags, (LPCSTR)(const void *)keygen, + &callbackModule) != 0) && + (engineModule == callbackModule); +#elif defined(WE_HAVE_DLADDR) + return (dladdr((const void *)destroy, &engineInfo) != 0) && + (dladdr((const void *)keygen, &callbackInfo) != 0) && + (engineInfo.dli_fbase != NULL) && + (engineInfo.dli_fbase == callbackInfo.dli_fbase); +#elif defined(WE_PBE_STATIC_LINK) && defined(WE_NO_DYNAMIC_ENGINE) + /* Static callbacks replace the built-in entries in the main executable. */ + return 1; +#else + return 0; +#endif +} + +static ENGINE *test_load_pbe_engine(void) +{ + ENGINE *engine = NULL; + +#ifdef WE_PBE_STATIC_LINK + ENGINE_load_wolfengine(); + engine = ENGINE_by_id(wolfengine_id); + if ((engine != NULL) && (ENGINE_remove(engine) != 1)) { + ENGINE_free(engine); + engine = NULL; + } +#else + const char *id; + const char *path; + +#ifdef _WIN32 + id = "wolfEngine"; +#elif OPENSSL_VERSION_NUMBER >= 0x10100000L + id = "libwolfengine"; +#else + id = "wolfengine"; +#endif +#if defined(__CYGWIN__) + path = ".libs/cygwolfengine-1.dll"; +#elif defined(__MINGW32__) + path = ".libs/libwolfengine-1.dll"; +#elif defined(_WIN32) + path = ".libs/wolfEngine.dll"; +#elif defined(__APPLE__) + path = ".libs/libwolfengine.dylib"; +#else + path = ".libs/libwolfengine.so"; +#endif + + ENGINE_load_dynamic(); + engine = ENGINE_by_id("dynamic"); + if ((engine == NULL) || + (ENGINE_ctrl_cmd_string(engine, "SO_PATH", path, 0) != 1) || + (ENGINE_ctrl_cmd_string(engine, "ID", id, 0) != 1) || + (ENGINE_ctrl_cmd_string(engine, "LIST_ADD", "0", 0) != 1) || + (ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0) != 1)) { + if (engine != NULL) + ENGINE_free(engine); + engine = NULL; + } +#endif + return engine; +} +#endif + +int main(void) +{ +#if defined(WE_HAVE_PBE) && !defined(NO_PWDBASED) && \ + (defined(WE_PBE_STATIC_LINK) || (defined(WE_HAVE_SHARED_LIBRARY) && \ + !defined(WE_NO_DYNAMIC_ENGINE))) + int err = 0; + int cipherNid = 0; + int digestNid = 0; + int attempt; + int i; + const int nids[] = { NID_id_pbkdf2, +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + NID_id_pbkdf2, +#else + NID_pbes2, +#endif + NID_pbe_WithSHA1And3_Key_TripleDES_CBC }; + const int types[] = { EVP_PBE_TYPE_OUTER, +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + EVP_PBE_TYPE_KDF, +#else + EVP_PBE_TYPE_OUTER, +#endif + EVP_PBE_TYPE_OUTER }; + ENGINE *engine = NULL; + EVP_CIPHER_CTX *ctx = NULL; + EVP_PBE_KEYGEN *keygen = NULL; + EVP_PBE_KEYGEN *builtin[3] = { NULL, NULL, NULL }; + EVP_PBE_KEYGEN *expected[3] = { NULL, NULL, NULL }; + + ctx = EVP_CIPHER_CTX_new(); + if (ctx == NULL) { + fprintf(stderr, "Failed to create PBE cipher context\n"); + return 1; + } + for (i = 0; i < 3; i++) { + (void)EVP_PBE_find(types[i], nids[i], &cipherNid, &digestNid, + &builtin[i]); + } + for (attempt = 0; (attempt < 2) && (err == 0); attempt++) { + engine = test_load_pbe_engine(); + if (engine == NULL) { + fprintf(stderr, "Failed to load PBE engine\n"); + err = 1; + } + for (i = 0; (i < 3) && (err == 0); i++) { + keygen = NULL; + if ((EVP_PBE_find(types[i], nids[i], &cipherNid, &digestNid, + &keygen) != 1) || (keygen == NULL)) { + fprintf(stderr, "Failed to find registered PBE callback\n"); + err = 1; + } + else if ((keygen == builtin[i]) || + !test_pbe_callback_owner(engine, keygen)) { + fprintf(stderr, "PBE callback does not belong to the engine\n"); + err = 1; + } + else if (attempt == 0) { + expected[i] = keygen; + } + else if (keygen != expected[i]) { + fprintf(stderr, "PBE callback changed after registry cleanup\n"); + err = 1; + } + } + if (engine != NULL) + ENGINE_free(engine); + if ((err == 0) && + (expected[0](ctx, "password", 8, NULL, NULL, NULL, 1) != 0)) { + fprintf(stderr, "PBKDF2 callback accepted missing parameters\n"); + err = 1; + } + if (attempt == 0) + EVP_PBE_cleanup(); + } + EVP_CIPHER_CTX_free(ctx); + ERR_clear_error(); + return err; +#else + return 77; +#endif +} diff --git a/test/test_rand.c b/test/test_rand.c index 1487df07..746ca277 100644 --- a/test/test_rand.c +++ b/test/test_rand.c @@ -20,9 +20,163 @@ */ #include "unit.h" +#if !defined(_WIN32) && !defined(TEST_MULTITHREADED) +#include +#include +#endif #ifdef WE_HAVE_RANDOM +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) +#ifndef WE_STATIC_WOLFSSL +static int seedMixCount; +#endif +static int entropyLogSeen; + +static void test_random_logging_cb(const int logLevel, const int component, + const char *const logMessage) +{ +#ifndef WE_STATIC_WOLFSSL + if (logLevel == WE_LOG_ENTER && component == WE_LOG_RNG && + strcmp(logMessage, "wolfEngine Entering we_rand_mix_seed") == 0) { + seedMixCount++; + } +#endif + if (logLevel == WE_LOG_VERBOSE && component == WE_LOG_RNG && + strstr(logMessage, "entropy = 12.500000]") != NULL) { + entropyLogSeen = 1; + } +} +#endif + +static int test_random_seed_failure(ENGINE *e) +{ + const RAND_METHOD *method = ENGINE_get_RAND(e); + + if (method == NULL || method->seed == NULL) { + return 1; + } + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + return method->seed(NULL, 1) != 0; +#else + return 0; +#endif +} + +static int test_random_status_after_teardown(ENGINE *e) +{ +#if !defined(_WIN32) && !defined(TEST_MULTITHREADED) + const RAND_METHOD *method = ENGINE_get_RAND(e); + ENGINE_GEN_INT_FUNC_PTR destroy = ENGINE_get_destroy_function(e); + int status; + pid_t pid; + + if (method == NULL || method->cleanup == NULL || method->status == NULL || + destroy == NULL) { + return 1; + } + + pid = fork(); + if (pid == -1) { + return 1; + } + if (pid == 0) { + if (destroy(e) != 1) { + _exit(1); + } + if (method->status() != 0) { + _exit(1); + } + method->cleanup(); + method->cleanup(); + _exit(0); + } + + if (waitpid(pid, &status, 0) != pid) { + return 1; + } + + return !WIFEXITED(status) || WEXITSTATUS(status) != 0; +#else + (void)e; + return 0; +#endif +} + +static int test_random_cleanup(ENGINE *e) +{ +#if defined(WOLFENGINE_DEBUG) && !defined(WE_STATIC_WOLFSSL) && \ + !defined(TEST_MULTITHREADED) + const RAND_METHOD *method = ENGINE_get_RAND(e); + unsigned char buf[16] = { 0 }; + int err = 0; + + if (method == NULL || method->seed == NULL || method->cleanup == NULL || + method->bytes == NULL) { + err = 1; + } + if (err == 0 && (wolfEngine_Debugging_ON() != 0 || + wolfEngine_SetLoggingCb(test_random_logging_cb) != 0 || + wolfEngine_SetLogLevel(WE_LOG_ENTER) != 0 || + wolfEngine_SetLogComponents(WE_LOG_RNG) != 0)) { + err = 1; + } + if (err == 0) { + method->seed(buf, sizeof(buf)); + seedMixCount = 0; + method->cleanup(); + if (method->bytes(buf, sizeof(buf)) != 1 || seedMixCount != 1) { + err = 1; + } + } + + (void)wolfEngine_SetLoggingCb(NULL); + (void)wolfEngine_SetLogLevel(WE_LOG_ERROR | WE_LOG_INFO); + (void)wolfEngine_SetLogComponents(WE_LOG_COMPONENTS_DEFAULT); + wolfEngine_Debugging_OFF(); + + return err; +#else + (void)e; + return 0; +#endif +} + +static int test_random_entropy_logging(ENGINE *e) +{ +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) + const RAND_METHOD *method = ENGINE_get_RAND(e); + unsigned char buf[16] = { 0 }; + int err = 0; + + if (method == NULL || method->add == NULL) { + err = 1; + } + if (err == 0 && (wolfEngine_Debugging_ON() != 0 || + wolfEngine_SetLoggingCb(test_random_logging_cb) != 0 || + wolfEngine_SetLogLevel(WE_LOG_VERBOSE) != 0 || + wolfEngine_SetLogComponents(WE_LOG_RNG) != 0)) { + err = 1; + } + if (err == 0) { + entropyLogSeen = 0; + method->add(buf, sizeof(buf), 12.5); + err = !entropyLogSeen; + } + + (void)wolfEngine_SetLoggingCb(NULL); + (void)wolfEngine_SetLogLevel(WE_LOG_ERROR | WE_LOG_INFO); + (void)wolfEngine_SetLogComponents(WE_LOG_COMPONENTS_DEFAULT); + wolfEngine_Debugging_OFF(); + + return err; +#else + (void)e; + return 0; +#endif +} + static int test_random_api(void) { int err; @@ -76,16 +230,30 @@ static int test_random_api(void) int test_random(ENGINE *e, void *data) { int err; + unsigned long flags; - (void)data; + flags = *(unsigned long*)data; err = test_random_api(); if (err == 0) { err = RAND_set_rand_engine(e) != 1; } + if (err == 0) { + err = test_random_seed_failure(e); + } if (err == 0) { err = test_random_api(); } + if (err == 0) { + err = test_random_cleanup(e); + } + if (err == 0) { + err = test_random_entropy_logging(e); + } + /* The child skips OpenSSL's method frees, so memcheck reports leaks. */ + if ((err == 0) && ((flags & WE_VALGRIND_TEST) == 0)) { + err = test_random_status_after_teardown(e); + } return err; } diff --git a/test/test_rsa.c b/test/test_rsa.c index eb0d0eb5..c3ff26b7 100644 --- a/test/test_rsa.c +++ b/test/test_rsa.c @@ -19,8 +19,13 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#include #include "unit.h" #include +#if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) && \ + defined(WOLFSSL_PTHREADS) && !defined(TEST_MULTITHREADED) +#include +#endif #ifdef WE_HAVE_RSA @@ -581,6 +586,7 @@ int test_rsa_ctrl_str(ENGINE* e, void* data) { int err; EVP_PKEY_CTX* ctx = NULL; + void* engineData = NULL; (void)data; @@ -613,7 +619,25 @@ int test_rsa_ctrl_str(ENGINE* e, void* data) err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_keygen_bits", "2048") <= 0; } if (err == 0) { - err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_keygen_bits", "-1") > 0; + err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_keygen_bits", "-1") != -2; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_unknown_option", "1") != -2; + } + if (err == 0) { + engineData = EVP_PKEY_CTX_get_data(ctx); + EVP_PKEY_CTX_set_data(ctx, NULL); + err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_keygen_bits", "2048") != 0; + EVP_PKEY_CTX_set_data(ctx, engineData); + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_padding_mode", "pkcs1") <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_mgf1_md", "SHA256") != -2; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "rsa_oaep_md", "SHA256") != -2; } /* rsa_pss_saltlen */ @@ -780,6 +804,179 @@ int test_rsa_direct_priv_enc(ENGINE *e, void *data) return err; } +#if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) && \ + defined(WOLFSSL_PTHREADS) && !defined(TEST_MULTITHREADED) +static int test_rsa_priv_dec_lock_failure(ENGINE *e) +{ + int err = 0; + int encryptedLen = 0; + int decryptedLen; + int attrInited = 0; + int mutexInited = 0; + int mutexLocked = 0; + int rngMutexSet = 0; + unsigned char plain[20] = { 0 }; + unsigned char* encrypted = NULL; + unsigned char* decrypted = NULL; + RSA* weRsaKey = NULL; + RSA* osslRsaKey = NULL; + pthread_mutexattr_t attr; + wolfSSL_Mutex mutex; + wolfSSL_Mutex* savedRngMutex = NULL; + + err = load_static_rsa_key(e, rsa_key_der_1024, + sizeof(rsa_key_der_1024), &weRsaKey, + &osslRsaKey) != 1; + if (err == 0) { + encrypted = OPENSSL_malloc(RSA_size(osslRsaKey)); + decrypted = OPENSSL_malloc(RSA_size(weRsaKey)); + err = encrypted == NULL || decrypted == NULL; + } + if (err == 0) { + encryptedLen = RSA_public_encrypt(sizeof(plain), plain, encrypted, + osslRsaKey, RSA_PKCS1_PADDING); + err = encryptedLen <= 0; + } + if (err == 0) { + err = pthread_mutexattr_init(&attr) != 0; + attrInited = err == 0; + } + if (err == 0) { + err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK) != 0; + } + if (err == 0) { + err = pthread_mutex_init(&mutex, &attr) != 0; + mutexInited = err == 0; + } + if (err == 0) { + err = pthread_mutex_lock(&mutex) != 0; + mutexLocked = err == 0; + } + if (err == 0) { + savedRngMutex = we_rng_mutex; + we_rng_mutex = &mutex; + rngMutexSet = 1; + + decryptedLen = RSA_private_decrypt(encryptedLen, encrypted, decrypted, + weRsaKey, RSA_PKCS1_PADDING); + + we_rng_mutex = savedRngMutex; + rngMutexSet = 0; + err = decryptedLen != -1; + } + if (mutexLocked) { + int rc = pthread_mutex_unlock(&mutex); + + if (err == 0) { + err = rc != 0; + } + mutexLocked = 0; + } + + if (rngMutexSet) { + we_rng_mutex = savedRngMutex; + } + if (mutexInited) { + pthread_mutex_destroy(&mutex); + } + if (attrInited) { + pthread_mutexattr_destroy(&attr); + } + OPENSSL_free(decrypted); + OPENSSL_free(encrypted); + RSA_free(osslRsaKey); + RSA_free(weRsaKey); + + return err; +} + +#ifdef WE_HAVE_RSA_X931 +static int test_rsa_x931_lock_failure(ENGINE *e) +{ + int err = 0; + int encryptedLen = 0; + int decryptedLen; + int attrInited = 0; + int mutexInited = 0; + int mutexLocked = 0; + int rngMutexSet = 0; + unsigned char plain[20] = { 0 }; + unsigned char* encrypted = NULL; + unsigned char* decrypted = NULL; + RSA* weRsaKey = NULL; + RSA* osslRsaKey = NULL; + pthread_mutexattr_t attr; + wolfSSL_Mutex mutex; + wolfSSL_Mutex* savedRngMutex = NULL; + + err = load_static_rsa_key(e, rsa_key_der_1024, + sizeof(rsa_key_der_1024), &weRsaKey, + &osslRsaKey) != 1; + if (err == 0) { + encrypted = OPENSSL_malloc(RSA_size(osslRsaKey)); + decrypted = OPENSSL_malloc(RSA_size(weRsaKey)); + err = encrypted == NULL || decrypted == NULL; + } + if (err == 0) { + encryptedLen = RSA_private_encrypt(sizeof(plain), plain, encrypted, + osslRsaKey, RSA_X931_PADDING); + err = encryptedLen <= 0; + } + if (err == 0) { + err = pthread_mutexattr_init(&attr) != 0; + attrInited = err == 0; + } + if (err == 0) { + err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK) != 0; + } + if (err == 0) { + err = pthread_mutex_init(&mutex, &attr) != 0; + mutexInited = err == 0; + } + if (err == 0) { + err = pthread_mutex_lock(&mutex) != 0; + mutexLocked = err == 0; + } + if (err == 0) { + savedRngMutex = we_rng_mutex; + we_rng_mutex = &mutex; + rngMutexSet = 1; + + decryptedLen = RSA_public_decrypt(encryptedLen, encrypted, decrypted, + weRsaKey, RSA_X931_PADDING); + + we_rng_mutex = savedRngMutex; + rngMutexSet = 0; + err = decryptedLen != -1; + } + if (mutexLocked) { + int rc = pthread_mutex_unlock(&mutex); + + if (err == 0) { + err = rc != 0; + } + mutexLocked = 0; + } + + if (rngMutexSet) { + we_rng_mutex = savedRngMutex; + } + if (mutexInited) { + pthread_mutex_destroy(&mutex); + } + if (attrInited) { + pthread_mutexattr_destroy(&attr); + } + OPENSSL_free(decrypted); + OPENSSL_free(encrypted); + RSA_free(osslRsaKey); + RSA_free(weRsaKey); + + return err; +} +#endif +#endif + int test_rsa_direct_priv_dec(ENGINE *e, void *data) { int err = 0; @@ -794,6 +991,13 @@ int test_rsa_direct_priv_dec(ENGINE *e, void *data) err = test_rsa_direct(e, rsa_key_der_1024, sizeof(rsa_key_der_1024), PRIVATE_DECRYPT); } +#if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) && \ + defined(WOLFSSL_PTHREADS) && !defined(TEST_MULTITHREADED) + if (err == 0) { + PRINT_MSG("Check lock failure preserves RSA RNG mutex ownership."); + err = test_rsa_priv_dec_lock_failure(e); + } +#endif return err; } @@ -832,6 +1036,14 @@ int test_rsa_direct_pub_dec(ENGINE *e, void *data) err = test_rsa_direct(e, rsa_key_der_1024, sizeof(rsa_key_der_1024), PUBLIC_DECRYPT); } +#if defined(WE_RSA_USE_GLOBAL_RNG) && !defined(WE_SINGLE_THREADED) && \ + defined(WOLFSSL_PTHREADS) && !defined(TEST_MULTITHREADED) && \ + defined(WE_HAVE_RSA_X931) + if (err == 0) { + PRINT_MSG("Check RSA X9.31 public decrypt locks the global RNG."); + err = test_rsa_x931_lock_failure(e); + } +#endif return err; } @@ -961,6 +1173,87 @@ static int test_rsa_sign_verify_pad(ENGINE *e, int padMode, const EVP_MD *md, return err; } +#ifdef WE_HAVE_RSA_X931 +static int test_rsa_x931_fixed_width(ENGINE *e) +{ + int err = 0; + EVP_PKEY *pkey = NULL; + EVP_PKEY_CTX *ctx = NULL; + const unsigned char *p = rsa_key_der_2048; + unsigned char buf[20] = { 0 }; + unsigned char *rsaSig = NULL; + unsigned char *recovered = NULL; + size_t rsaSigLen = 0; + size_t rsaSigCap = 0; + size_t recoveredLen = 0; + + buf[sizeof(buf) - 2] = 0x01; + buf[sizeof(buf) - 1] = 0x6c; + + pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p, sizeof(rsa_key_der_2048)); + err = pkey == NULL; + if (err == 0) { + rsaSigCap = (size_t)EVP_PKEY_size(pkey) + 16; + rsaSig = (unsigned char *)OPENSSL_malloc(rsaSigCap); + err = rsaSig == NULL; + } + + if (err == 0) { + XMEMSET(rsaSig, 0xa5, rsaSigCap); + rsaSigLen = rsaSigCap; + err = test_digest_sign(pkey, e, buf, sizeof(buf), EVP_sha256(), + rsaSig, &rsaSigLen, RSA_X931_PADDING); + } + if (err == 0) { + err = rsaSigLen != (size_t)EVP_PKEY_size(pkey); + } + if (err == 0) { + err = test_digest_verify(pkey, NULL, buf, sizeof(buf), EVP_sha256(), + rsaSig, rsaSigLen, RSA_X931_PADDING); + } + if (err == 0) { + recoveredLen = rsaSigCap; + recovered = (unsigned char *)OPENSSL_malloc(recoveredLen); + err = recovered == NULL; + } + if (err == 0) { + #if OPENSSL_VERSION_NUMBER >= 0x30000000L + err = EVP_PKEY_set1_engine(pkey, e) != 1; + if (err == 0) { + ctx = EVP_PKEY_CTX_new(pkey, NULL); + } + #else + ctx = EVP_PKEY_CTX_new(pkey, e); + #endif + err = (err != 0) || (ctx == NULL); + } + if (err == 0) { + err = EVP_PKEY_verify_recover_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_X931_PADDING) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()) <= 0; + } + if (err == 0) { + XMEMSET(recovered, 0xa5, recoveredLen); + err = EVP_PKEY_verify_recover(ctx, recovered, &recoveredLen, rsaSig, + rsaSigLen) != 1; + } + if (err == 0) { + err = recoveredLen > (size_t)EVP_PKEY_size(pkey); + } + + EVP_PKEY_CTX_free(ctx); + EVP_PKEY_free(pkey); + OPENSSL_free(recovered); + OPENSSL_free(rsaSig); + + return err; +} +#endif + int test_rsa_sign_sha1(ENGINE *e, void *data) { int err = 0; @@ -1044,6 +1337,93 @@ int test_rsa_sign_verify_no_pad(ENGINE *e, void *data) #endif } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L +static int test_rsa_pss_saltlen_persistence(ENGINE *e) +{ + int err = 0; + int saltLen = 0; + EVP_PKEY *pkey = NULL; + EVP_PKEY_CTX *ctx = NULL; + const unsigned char *p = rsa_key_der_2048; + unsigned char hash[SHA384_DIGEST_LENGTH] = { 0 }; + unsigned char *sig = NULL; + size_t sigLen = 0; + + pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p, sizeof(rsa_key_der_2048)); + err = pkey == NULL; +#if OPENSSL_VERSION_NUMBER >= 0x30000000L + if (err == 0) { + err = EVP_PKEY_set1_engine(pkey, e) != 1; + } + if (err == 0) { + ctx = EVP_PKEY_CTX_new(pkey, NULL); + err = ctx == NULL; + } +#else + if (err == 0) { + ctx = EVP_PKEY_CTX_new(pkey, e); + err = ctx == NULL; + } +#endif + if (err == 0) { + err = EVP_PKEY_sign_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, + RSA_PSS_SALTLEN_AUTO) <= 0; + } + if (err == 0) { + sigLen = (size_t)EVP_PKEY_size(pkey); + sig = (unsigned char *)OPENSSL_malloc(sigLen); + err = sig == NULL; + } + if (err == 0) { + err = EVP_PKEY_sign(ctx, sig, &sigLen, hash, + SHA256_DIGEST_LENGTH) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_get_rsa_pss_saltlen(ctx, &saltLen) <= 0; + } + if (err == 0) { +#ifdef WOLFSSL_PSS_LONG_SALT + err = saltLen != RSA_PSS_SALTLEN_AUTO; +#else + err = saltLen != EVP_MD_size(EVP_sha256()); +#endif + } + if (err == 0) { + err = EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha384()) <= 0; + } + if (err == 0) { + sigLen = (size_t)EVP_PKEY_size(pkey); + err = EVP_PKEY_sign(ctx, sig, &sigLen, hash, + SHA384_DIGEST_LENGTH) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_get_rsa_pss_saltlen(ctx, &saltLen) <= 0; + } + if (err == 0) { +#ifdef WOLFSSL_PSS_LONG_SALT + err = saltLen != RSA_PSS_SALTLEN_AUTO; +#else + err = saltLen != EVP_MD_size(EVP_sha384()); +#endif + } + + OPENSSL_free(sig); + EVP_PKEY_CTX_free(ctx); + EVP_PKEY_free(pkey); + + return err; +} +#endif + int test_rsa_sign_verify_pss(ENGINE *e, void *data) { int err = 0; @@ -1062,16 +1442,79 @@ int test_rsa_sign_verify_pss(ENGINE *e, void *data) err = test_rsa_sign_verify_pad(e, RSA_PKCS1_PSS_PADDING, EVP_sha384(), EVP_sha512()) == 1; } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L + if (err == 0) { + err = test_rsa_pss_saltlen_persistence(e); + } +#endif return err; } #ifdef WE_HAVE_RSA_X931 +static int test_rsa_x931_sig_leading_zero(ENGINE *e) +{ + int err; + EVP_PKEY *pkey = NULL; + unsigned char sslSig[256]; + unsigned char weSig[256]; + size_t sslSigLen = sizeof(sslSig); + size_t weSigLen = sizeof(weSig); + /* SHA-256 X9.31 signature of this message under rsa_key_der_2048 is + * n - s with a leading zero byte. */ + unsigned char msg[20] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x6c + }; + const unsigned char *p = rsa_key_der_2048; + + PRINT_MSG("Sign message whose X9.31 signature has a leading zero byte"); + pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p, sizeof(rsa_key_der_2048)); + err = pkey == NULL; + if (err == 0) { + err = test_digest_sign(pkey, NULL, msg, sizeof(msg), EVP_sha256(), + sslSig, &sslSigLen, RSA_X931_PADDING); + } + if (err == 0) { + err = sslSigLen != sizeof(sslSig) || sslSig[0] != 0x00; + } + if (err == 0) { + err = test_digest_sign(pkey, e, msg, sizeof(msg), EVP_sha256(), + weSig, &weSigLen, RSA_X931_PADDING); + } + if (err == 0) { + err = weSigLen != sslSigLen || + memcmp(weSig, sslSig, sslSigLen) != 0; + } + if (err == 0) { + err = test_digest_verify(pkey, NULL, msg, sizeof(msg), EVP_sha256(), + weSig, weSigLen, RSA_X931_PADDING); + } + if (err == 0) { + err = test_digest_verify(pkey, e, msg, sizeof(msg), EVP_sha256(), + sslSig, sslSigLen, RSA_X931_PADDING); + } + + EVP_PKEY_free(pkey); + + return err; +} + int test_rsa_sign_verify_x931(ENGINE *e, void *data) { + int err; + (void)data; - return test_rsa_sign_verify_pad(e, RSA_X931_PADDING, NULL, NULL); + err = test_rsa_sign_verify_pad(e, RSA_X931_PADDING, NULL, NULL); + if (err == 0) { + err = test_rsa_x931_fixed_width(e); + } + if (err == 0) { + err = test_rsa_x931_sig_leading_zero(e); + } + + return err; } #endif /* WE_HAVE_RSA_X931 */ @@ -1261,6 +1704,124 @@ int test_rsa_enc_dec_oaep(ENGINE *e, void *data) return err; } +static int test_rsa_set_oaep_label(EVP_PKEY_CTX *ctx, + const unsigned char *value, int len) +{ + unsigned char *label = NULL; + int ret = 0; + + label = (unsigned char *)OPENSSL_malloc((size_t)len); + if (label != NULL) { + XMEMCPY(label, value, (size_t)len); + ret = EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, label, len); + if (ret <= 0) { + OPENSSL_free(label); + } + } + + return ret; +} + +int test_rsa_oaep_label(ENGINE *e, void *data) +{ + int err = 0; + int labelLen; + const unsigned char *der = rsa_key_der_2048; + const unsigned char labelA[] = "label A"; + const unsigned char labelB[] = "label B"; + const unsigned char message[] = "OAEP label test"; + unsigned char ciphertext[256]; + unsigned char plaintext[256]; + unsigned char *gotLabel = NULL; + unsigned char *copiedLabel = NULL; + size_t ciphertextLen = sizeof(ciphertext); + size_t plaintextLen = sizeof(plaintext); + EVP_PKEY *pkey = NULL; + EVP_PKEY_CTX *encryptCtx = NULL; + EVP_PKEY_CTX *copyCtx = NULL; + EVP_PKEY_CTX *decryptCtx = NULL; + + (void)data; + + pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &der, + (long)sizeof(rsa_key_der_2048)); + err = pkey == NULL; + if (err == 0) { + encryptCtx = EVP_PKEY_CTX_new(pkey, e); + err = encryptCtx == NULL; + } + if (err == 0) { + err = EVP_PKEY_encrypt_init(encryptCtx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(encryptCtx, + RSA_PKCS1_OAEP_PADDING) <= 0; + } + if (err == 0) { + err = test_rsa_set_oaep_label(encryptCtx, labelA, + (int)sizeof(labelA)) <= 0; + } + if (err == 0) { + labelLen = EVP_PKEY_CTX_get0_rsa_oaep_label(encryptCtx, &gotLabel); + err = labelLen != (int)sizeof(labelA) || gotLabel == NULL || + XMEMCMP(gotLabel, labelA, sizeof(labelA)) != 0; + } + if (err == 0) { + copyCtx = EVP_PKEY_CTX_dup(encryptCtx); + err = copyCtx == NULL; + } + if (err == 0) { + labelLen = EVP_PKEY_CTX_get0_rsa_oaep_label(copyCtx, &copiedLabel); + err = labelLen != (int)sizeof(labelA) || copiedLabel == gotLabel || + XMEMCMP(copiedLabel, labelA, sizeof(labelA)) != 0; + } + EVP_PKEY_CTX_free(encryptCtx); + encryptCtx = NULL; + if (err == 0) { + err = EVP_PKEY_encrypt(copyCtx, ciphertext, &ciphertextLen, message, + sizeof(message)) != 1; + } + if (err == 0) { + decryptCtx = EVP_PKEY_CTX_new(pkey, e); + err = decryptCtx == NULL; + } + if (err == 0) { + err = EVP_PKEY_decrypt_init(decryptCtx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(decryptCtx, + RSA_PKCS1_OAEP_PADDING) <= 0; + } + if (err == 0) { + err = test_rsa_set_oaep_label(decryptCtx, labelA, + (int)sizeof(labelA)) <= 0; + } + if (err == 0) { + err = EVP_PKEY_decrypt(decryptCtx, plaintext, &plaintextLen, + ciphertext, ciphertextLen) != 1; + } + if (err == 0) { + err = plaintextLen != sizeof(message) || + XMEMCMP(plaintext, message, sizeof(message)) != 0; + } + if (err == 0) { + err = test_rsa_set_oaep_label(decryptCtx, labelB, + (int)sizeof(labelB)) <= 0; + } + if (err == 0) { + plaintextLen = sizeof(plaintext); + err = EVP_PKEY_decrypt(decryptCtx, plaintext, &plaintextLen, + ciphertext, ciphertextLen) > 0; + } + + EVP_PKEY_CTX_free(decryptCtx); + EVP_PKEY_CTX_free(copyCtx); + EVP_PKEY_CTX_free(encryptCtx); + EVP_PKEY_free(pkey); + + return err; +} + int test_rsa_pkey_keygen(ENGINE *e, void *data) { int err; @@ -1310,6 +1871,9 @@ int test_rsa_pkey_keygen(ENGINE *e, void *data) PRINT_MSG("Change the public exponent w/ ctrl command"); err = EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_KEYGEN, EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, eCmd) <= 0; + if (err == 0) { + eCmd = NULL; + } } if (err == 0) { PRINT_MSG("Generate RSA key w/ new parameters"); @@ -1325,7 +1889,7 @@ int test_rsa_pkey_keygen(ENGINE *e, void *data) err = BN_num_bits(n) != newKeySize; } if (err == 0) { - err = BN_cmp(eCmd, eKey) != 0; + err = BN_get_word(eKey) != 3; } if (err == 0) { @@ -1344,6 +1908,270 @@ int test_rsa_pkey_keygen(ENGINE *e, void *data) return err; } +int test_rsa_pkey_large_exponent(ENGINE *e, void *data) +{ + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *pkey = NULL; + BIGNUM *requestedExp = NULL; + const BIGNUM *keyExp = NULL; + const RSA *rsaKey = NULL; + + (void)data; + + if (sizeof(long) <= sizeof(int)) { + return 0; + } + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, e); + err = ctx == NULL; + if (err == 0) { + err = EVP_PKEY_keygen_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048) <= 0; + } + if (err == 0) { + requestedExp = BN_new(); + err = requestedExp == NULL; + } + if (err == 0) { + err = BN_set_word(requestedExp, (BN_ULONG)INT_MAX + 6U) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_keygen_pubexp(ctx, requestedExp) <= 0; + if (err == 0) { + requestedExp = NULL; + } + } + if (err == 0) { + err = EVP_PKEY_keygen(ctx, &pkey) != 1; + } + if (err == 0) { + rsaKey = EVP_PKEY_get0_RSA(pkey); + err = rsaKey == NULL; + } + if (err == 0) { + RSA_get0_key(rsaKey, NULL, &keyExp, NULL); + err = keyExp == NULL || + BN_get_word(keyExp) != (BN_ULONG)INT_MAX + 6U; + } + + BN_free(requestedExp); + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(ctx); + + return err; +} + +int test_rsa_pkey_sign_missing_data(ENGINE *e, void *data) +{ + int err = 0; + const unsigned char *der = rsa_key_der_1024; + unsigned char digest[20] = {0}; + size_t sigLen = 0; + EVP_PKEY *pkey = NULL; + EVP_PKEY_CTX *ctx = NULL; + void *engineData = NULL; + + (void)data; + + pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &der, + (long)sizeof(rsa_key_der_1024)); + err = pkey == NULL; + if (err == 0) { + ctx = EVP_PKEY_CTX_new(pkey, e); + err = ctx == NULL; + } + if (err == 0) { + err = EVP_PKEY_sign_init(ctx) != 1; + } + if (err == 0) { + engineData = EVP_PKEY_CTX_get_data(ctx); + err = engineData == NULL; + } + if (err == 0) { + EVP_PKEY_CTX_set_data(ctx, NULL); + err = EVP_PKEY_sign(ctx, NULL, &sigLen, digest, sizeof(digest)) > 0; + EVP_PKEY_CTX_set_data(ctx, engineData); + } + + EVP_PKEY_CTX_free(ctx); + EVP_PKEY_free(pkey); + + return err; +} + +int test_rsa_pkey_sign_digest_length(ENGINE *e, void *data) +{ + int err = 0; + const unsigned char *der = rsa_key_der_2048; + unsigned char digest[128] = {0}; + unsigned char sig[256]; + size_t sigLen = sizeof(sig); + EVP_PKEY *pkey = NULL; + EVP_PKEY_CTX *ctx = NULL; + + (void)data; + + pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &der, + (long)sizeof(rsa_key_der_2048)); + err = pkey == NULL; + if (err == 0) { + ctx = EVP_PKEY_CTX_new(pkey, e); + err = ctx == NULL; + } + if (err == 0) { + err = EVP_PKEY_sign_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()) <= 0; + } + if (err == 0) { + err = EVP_PKEY_sign(ctx, sig, &sigLen, digest, sizeof(digest)) > 0; + } + + EVP_PKEY_CTX_free(ctx); + EVP_PKEY_free(pkey); + + return err; +} + +static int test_rsa_verify_recover_digest_padding(ENGINE *e, EVP_PKEY *pkey, + int padding) +{ + int err = 0; + unsigned char digest[32] = {0}; + unsigned char signature[256]; + unsigned char recovered[32]; + unsigned char shortRecovered[33]; + size_t signatureLen = sizeof(signature); + size_t recoveredLen = sizeof(recovered); + EVP_PKEY_CTX *signCtx = NULL; + EVP_PKEY_CTX *recoverCtx = NULL; + EVP_PKEY_CTX *verifyCtx = NULL; + + digest[0] = 0x12; + digest[sizeof(digest) - 1] = 0x34; + + signCtx = EVP_PKEY_CTX_new(pkey, e); + err = signCtx == NULL; + if (err == 0) { + err = EVP_PKEY_sign_init(signCtx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(signCtx, padding) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_signature_md(signCtx, EVP_sha256()) <= 0; + } + if (err == 0) { + err = EVP_PKEY_sign(signCtx, signature, &signatureLen, digest, + sizeof(digest)) != 1; + } + + if (err == 0) { + recoverCtx = EVP_PKEY_CTX_new(pkey, e); + err = recoverCtx == NULL; + } + if (err == 0) { + err = EVP_PKEY_verify_recover_init(recoverCtx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(recoverCtx, padding) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_signature_md(recoverCtx, EVP_sha256()) <= 0; + } + if (err == 0) { + err = EVP_PKEY_verify_recover(recoverCtx, recovered, &recoveredLen, + signature, signatureLen) != 1; + } + if (err == 0) { + err = recoveredLen != sizeof(digest) || + XMEMCMP(recovered, digest, sizeof(digest)) != 0; + } + if (err == 0) { + XMEMSET(shortRecovered, 0xa5, sizeof(shortRecovered)); + recoveredLen = sizeof(digest) - 1; + err = EVP_PKEY_verify_recover(recoverCtx, shortRecovered, &recoveredLen, + signature, signatureLen) > 0 || + shortRecovered[sizeof(digest) - 1] != 0xa5 || + shortRecovered[sizeof(digest)] != 0xa5; + } + + if (err == 0) { + verifyCtx = EVP_PKEY_CTX_new(pkey, e); + err = verifyCtx == NULL; + } + if (err == 0) { + err = EVP_PKEY_verify_init(verifyCtx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_rsa_padding(verifyCtx, padding) <= 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_signature_md(verifyCtx, EVP_sha256()) <= 0; + } + if (err == 0) { + err = EVP_PKEY_verify(verifyCtx, signature, signatureLen, digest, + sizeof(digest)) != 1; + } + +#if defined(WE_HAVE_SHA3_256) && !defined(HAVE_FIPS) && \ + !defined(HAVE_FIPS_VERSION) + if (err == 0 && padding == RSA_PKCS1_PADDING) { + err = EVP_PKEY_CTX_set_signature_md(signCtx, EVP_sha3_256()) <= 0; + } + if (err == 0 && padding == RSA_PKCS1_PADDING) { + signatureLen = sizeof(signature); + err = EVP_PKEY_sign(signCtx, signature, &signatureLen, digest, + sizeof(digest)) != 1; + } + if (err == 0 && padding == RSA_PKCS1_PADDING) { + recoveredLen = sizeof(recovered); + err = EVP_PKEY_verify_recover(recoverCtx, recovered, &recoveredLen, + signature, signatureLen) > 0; + } +#endif + + EVP_PKEY_CTX_free(verifyCtx); + EVP_PKEY_CTX_free(recoverCtx); + EVP_PKEY_CTX_free(signCtx); + + return err; +} + +int test_rsa_verify_recover_digest(ENGINE *e, void *data) +{ + int err = 0; + const unsigned char *der = rsa_key_der_2048; + EVP_PKEY *pkey = NULL; + + (void)data; + + pkey = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &der, + (long)sizeof(rsa_key_der_2048)); + err = pkey == NULL; + if (err == 0) { + err = test_rsa_verify_recover_digest_padding(e, pkey, + RSA_PKCS1_PADDING); + } +#ifdef WE_HAVE_RSA_X931 + if (err == 0) { + err = test_rsa_verify_recover_digest_padding(e, pkey, + RSA_X931_PADDING); + } +#endif + + EVP_PKEY_free(pkey); + + return err; +} + int test_rsa_pkey_invalid_key_size(ENGINE *e, void *data) { int err; EVP_PKEY *pkey = NULL; diff --git a/test/test_tls1_prf.c b/test/test_tls1_prf.c index 7ecf9436..4a910eed 100644 --- a/test/test_tls1_prf.c +++ b/test/test_tls1_prf.c @@ -21,8 +21,25 @@ #include "unit.h" +#include + #ifdef WE_HAVE_TLS1_PRF +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) +static int tls1PrfMissingSecretLogged; + +static void test_tls1_prf_log_cb(const int logLevel, const int component, + const char *const logMessage) +{ + (void)logLevel; + (void)component; + + if (strstr(logMessage, "No secret from app.") != NULL) { + tls1PrfMissingSecretLogged = 1; + } +} +#endif + static int test_tls1_prf_calc(ENGINE *e, unsigned char *key, int keyLen, const EVP_MD *md) { @@ -404,6 +421,13 @@ int test_tls1_prf_bad_md(ENGINE *e, void *data) /* Unknown digest name must fail, not dereference a NULL digest. */ err = EVP_PKEY_CTX_ctrl_str(ctx, "md", "notadigest") > 0; } + if (err == 0) { + /* Digests unsupported by TLS1-PRF must be rejected. */ + err = EVP_PKEY_CTX_set_tls1_prf_md(ctx, EVP_sha512()) > 0; + } + if (err == 0) { + err = EVP_PKEY_CTX_ctrl_str(ctx, "md", "sha512") > 0; + } EVP_PKEY_CTX_free(ctx); @@ -411,6 +435,118 @@ int test_tls1_prf_bad_md(ENGINE *e, void *data) #endif } +/******************************************************************************/ + +int test_tls1_prf_secret_failure(ENGINE *e, void *data) +{ +#if defined(WOLFENGINE_DEBUG) && !defined(TEST_MULTITHREADED) + int err = 0; + int initialDebug = 0; + EVP_PKEY_CTX *ctx = NULL; + unsigned char secret[16] = { 0 }; + unsigned char seed[16] = { 0 }; + unsigned char key[16]; + size_t keySz = sizeof(key); + + if (data == NULL) { + err = 1; + } + else { + initialDebug = *(int *)data; + } + if (err == 0) { + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, e); + err = ctx == NULL; + } + if (err == 0) { + err = EVP_PKEY_derive_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_tls1_prf_md(ctx, EVP_sha256()) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set1_tls1_prf_secret(ctx, secret, + sizeof(secret)) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_add1_tls1_prf_seed(ctx, seed, sizeof(seed)) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set1_tls1_prf_secret(ctx, NULL, 1) > 0; + } + if (err == 0) { + err = wolfEngine_SetLoggingCb(test_tls1_prf_log_cb) != 0; + } + if (err == 0) { + err = wolfEngine_Debugging_ON() != 0; + } + if (err == 0) { + tls1PrfMissingSecretLogged = 0; + err = EVP_PKEY_derive(ctx, key, &keySz) > 0; + } + if (err == 0) { + err = tls1PrfMissingSecretLogged == 0; + } + + (void)wolfEngine_SetLoggingCb(NULL); + if (!initialDebug) { + wolfEngine_Debugging_OFF(); + } + EVP_PKEY_CTX_free(ctx); + + return err; +#else + (void)e; + (void)data; + return 0; +#endif +} + +/******************************************************************************/ + +int test_tls1_prf_output_size(ENGINE *e, void *data) +{ +#if SIZE_MAX > UINT32_MAX + int err = 0; + EVP_PKEY_CTX *ctx = NULL; + unsigned char secret[16] = { 0 }; + unsigned char seed[16] = { 0 }; + unsigned char key[1] = { 0 }; + size_t keySz = (size_t)UINT32_MAX + 2U; + + (void)data; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, e); + if (ctx == NULL) { + err = 1; + } + if (err == 0) { + err = EVP_PKEY_derive_init(ctx) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set_tls1_prf_md(ctx, EVP_sha256()) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_set1_tls1_prf_secret(ctx, secret, + sizeof(secret)) != 1; + } + if (err == 0) { + err = EVP_PKEY_CTX_add1_tls1_prf_seed(ctx, seed, sizeof(seed)) != 1; + } + if (err == 0) { + err = EVP_PKEY_derive(ctx, key, &keySz) > 0; + } + + EVP_PKEY_CTX_free(ctx); + + return err; +#else + (void)e; + (void)data; + return 0; +#endif +} + #endif /* WE_HAVE_TLS1_PRF */ diff --git a/test/unit.c b/test/unit.c index f04e32fc..f287e3d4 100644 --- a/test/unit.c +++ b/test/unit.c @@ -19,16 +19,274 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +#ifdef HAVE_CONFIG_H +#include +#endif + #ifdef TEST_MULTITHREADED #include #endif +#include + #include +#include +#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__CYGWIN__) && \ + !defined(_WIN32_WCE) +#define WE_TEST_INTERNAL_GLOBALS +#endif #include #include "unit.h" +#if !defined(WE_SINGLE_THREADED) && defined(HAVE_PTHREAD) +#include +#endif + +#ifndef TEST_MULTITHREADED +#if OPENSSL_VERSION_NUMBER < 0x1000209fL +#include +#endif +#ifdef HAVE_VALGRIND_MEMCHECK_H +#include +#include +#endif + +typedef union test_MemHeader { + long double align; + void *ptr; + size_t size; +} test_MemHeader; + +static void *testClearPtr = NULL; +static size_t testClearNextSize = 0; +static int testClearResult = -1; +static size_t testFailSize = 0; +static int testFailCount = 0; +static size_t testActiveAllocs = 0; + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L +static int test_mac_allocation_source(const char *file) +{ + const char *name = file; + + if (file == NULL) + return 0; + while (*file != '\0') { + if ((*file == '/') || (*file == '\\')) { + name = file + 1; + } + file++; + } + return strcmp(name, "we_mac.c") == 0; +} + +static void *test_openssl_malloc(size_t size, const char *file, int line) +#else +static void *test_openssl_malloc(size_t size) +#endif +{ + test_MemHeader *header; + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + (void)line; + + if ((testFailCount > 0) && (size == testFailSize) && + test_mac_allocation_source(file)) { + testFailCount--; + return NULL; + } +#endif + + header = (test_MemHeader *)malloc(sizeof(*header) + size); + if (header != NULL) { + header->size = size; + header++; +#ifdef HAVE_VALGRIND_MEMCHECK_H + VALGRIND_MEMPOOL_ALLOC(&testActiveAllocs, header, size); +#endif + testActiveAllocs++; +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if ((size == testClearNextSize) && test_mac_allocation_source(file)) { + testClearPtr = header; + testClearNextSize = 0; + } +#endif + } + + return header; +} + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L +static void *test_openssl_realloc(void *ptr, size_t size, const char *file, + int line) +#else +static void *test_openssl_realloc(void *ptr, size_t size) +#endif +{ + test_MemHeader *header; +#ifdef HAVE_VALGRIND_MEMCHECK_H + uintptr_t oldAddress = (uintptr_t)ptr; +#endif + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + (void)file; + (void)line; +#endif + + if (ptr == NULL) { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + return test_openssl_malloc(size, file, line); +#else + return test_openssl_malloc(size); +#endif + } + + header = (test_MemHeader *)ptr - 1; + header = (test_MemHeader *)realloc(header, sizeof(*header) + size); + if (header != NULL) { + header->size = size; + header++; +#ifdef HAVE_VALGRIND_MEMCHECK_H + /* realloc preserves the payload's definedness when it moves. */ + VALGRIND_MEMPOOL_CHANGE(&testActiveAllocs, oldAddress, header, size); +#endif + } + + return header; +} + +static int test_openssl_mem_is_clear(const void *ptr, size_t size) +{ + const unsigned char *data = (const unsigned char *)ptr; + size_t i; +#if OPENSSL_VERSION_NUMBER < 0x1000209fL + unsigned char ctr; +#endif + + for (i = 0; i < size; i++) { + if (data[i] != 0) + break; + } + if (i == size) + return 1; + +#if OPENSSL_VERSION_NUMBER < 0x1000209fL + /* Before 1.0.2i, portable OPENSSL_cleanse used a counter pattern. */ + if (size < 2) + return 0; + ctr = data[0]; + for (i = 0; i < size; i++) { + if (data[i] != ctr) + return 0; + ctr = (unsigned char)(ctr + 17 + + ((uintptr_t)(data + i + 1) & 0xf)); + } + return 1; +#else + return 0; +#endif +} + +static int test_openssl_mem_clear_check(void) +{ + unsigned char data[32]; + + memset(data, 0xa5, sizeof(data)); + if (test_openssl_mem_is_clear(data, sizeof(data)) || + test_openssl_mem_is_clear(data, 1)) { + return 0; + } + OPENSSL_cleanse(data, sizeof(data)); + if (!test_openssl_mem_is_clear(data, sizeof(data))) + return 0; + data[sizeof(data) / 2] ^= 1; + if (test_openssl_mem_is_clear(data, sizeof(data))) + return 0; + memset(data, 0, sizeof(data)); + if (!test_openssl_mem_is_clear(data, sizeof(data))) + return 0; + data[sizeof(data) / 2] = 1; + return !test_openssl_mem_is_clear(data, sizeof(data)); +} + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L +static void test_openssl_free(void *ptr, const char *file, int line) +#else +static void test_openssl_free(void *ptr) +#endif +{ + test_MemHeader *header; + +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + (void)file; + (void)line; +#endif + + if (ptr == NULL) { + return; + } + + header = (test_MemHeader *)ptr - 1; + if (ptr == testClearPtr) { + testClearResult = test_openssl_mem_is_clear(ptr, header->size); + testClearPtr = NULL; + } +#ifdef HAVE_VALGRIND_MEMCHECK_H + VALGRIND_MEMPOOL_FREE(&testActiveAllocs, ptr); +#endif + testActiveAllocs--; + free(header); +} + +void test_openssl_mem_expect_clear(void *ptr) +{ + testClearPtr = ptr; + testClearResult = -1; +} + +void test_openssl_mem_expect_next_clear(size_t size) +{ + testClearPtr = NULL; + testClearNextSize = size; + testClearResult = -1; +} + +int test_openssl_mem_clear_result(void) +{ + return testClearResult; +} + +void test_openssl_mem_fail_once(size_t size) +{ + testFailSize = size; + testFailCount = 1; +} + +int test_openssl_mem_failure_triggered(void) +{ + int triggered = testFailCount == 0; + + testFailCount = 0; + return triggered; +} + +size_t test_openssl_mem_active(void) +{ + return testActiveAllocs; +} + +int test_openssl_mem_has_source(void) +{ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + return OPENSSL_FILE[0] != '\0'; +#else + return 0; +#endif +} +#endif /* !TEST_MULTITHREADED */ + #ifdef WOLFENGINE_DEBUG void print_buffer(const char *desc, const unsigned char *buffer, size_t len) { @@ -52,8 +310,499 @@ static int debug = 0; #endif /* WOLFENGINE_DEBUG */ static unsigned long flags = 0; +static int test_engine(ENGINE *e, void *data) +{ + int err = 0; + + (void)data; + +#if defined(WE_HAVE_ECC) && !defined(WE_HAVE_ECDSA) && \ + defined(WE_HAVE_SHA1) + { + ENGINE_DIGESTS_PTR digests = ENGINE_get_digests(e); + const int *nids = NULL; + int count; + int i; + + if (digests == NULL) { + PRINT_ERR_MSG("Engine digest callback is not set"); + err = 1; + } + if (err == 0) { + count = digests(e, NULL, &nids, 0); + for (i = 0; i < count; i++) { + if (nids[i] == NID_ecdsa_with_SHA1) { + PRINT_ERR_MSG("ECDSA-with-SHA1 advertised without ECDSA"); + err = 1; + } + } + } + } +#else + (void)e; +#endif + + return err; +} + +#if !defined(WE_NO_DYNAMIC_ENGINE) && defined(WE_HAVE_SHARED_LIBRARY) +static int test_engine_id_match(const char *dir) +{ + int err = 0; + int len; + ENGINE *engine = NULL; + FILE *file = NULL; + char id[80]; + char path[256]; + + len = snprintf(id, sizeof(id), "%s-suffix", wolfengine_id); + if ((len < 0) || ((size_t)len >= sizeof(id))) { + PRINT_ERR_MSG("Failed to construct mismatched engine identifier"); + err = 1; + } + #if defined(__CYGWIN__) + len = snprintf(path, sizeof(path), "%s/cygwolfengine-1.dll", dir); + #elif defined(__MINGW32__) + len = snprintf(path, sizeof(path), "%s/libwolfengine-1.dll", dir); + #elif defined(_WIN32) + len = snprintf(path, sizeof(path), "%s/wolfEngine.dll", dir); + #elif defined(__APPLE__) + len = snprintf(path, sizeof(path), "%s/libwolfengine.dylib", dir); + #else + len = snprintf(path, sizeof(path), "%s/libwolfengine.so", dir); + #endif + if ((len < 0) || ((size_t)len >= sizeof(path))) { + PRINT_ERR_MSG("Failed to construct engine library path"); + err = 1; + } + if (err == 0) { + file = fopen(path, "rb"); + if (file == NULL) { + PRINT_ERR_MSG("Failed to open engine library for identifier test"); + err = 1; + } + } + if (file != NULL) { + fclose(file); + } + if (err == 0) { + engine = ENGINE_by_id("dynamic"); + } + if ((err == 0) && (engine == NULL)) { + PRINT_ERR_MSG("Failed to load dynamic engine support"); + err = 1; + } + if ((err == 0) && + (ENGINE_ctrl_cmd_string(engine, "SO_PATH", path, 0) != 1)) { + PRINT_ERR_MSG("Failed to set engine library path"); + err = 1; + } + if ((err == 0) && + (ENGINE_ctrl_cmd_string(engine, "ID", id, 0) != 1)) { + PRINT_ERR_MSG("Failed to set mismatched engine identifier"); + err = 1; + } + if ((err == 0) && + (ENGINE_ctrl_cmd_string(engine, "LIST_ADD", "0", 0) != 1)) { + PRINT_ERR_MSG("Failed to configure dynamic engine loading"); + err = 1; + } + if ((err == 0) && + (ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0) != 0)) { + PRINT_ERR_MSG("Accepted an engine identifier with a suffix"); + err = 1; + } + + if (engine != NULL) { + ENGINE_free(engine); + } + ERR_clear_error(); + return err; +} + +static int test_engine_bind_rollback(const char *dir) +{ + int err = 0; + int len; + int rc; + ENGINE *engine = NULL; + const char *name; + char path[256]; + +#if defined(__CYGWIN__) + len = snprintf(path, sizeof(path), "%s/cygwolfengine-1.dll", dir); +#elif defined(__MINGW32__) + len = snprintf(path, sizeof(path), "%s/libwolfengine-1.dll", dir); +#elif defined(_WIN32) + len = snprintf(path, sizeof(path), "%s/wolfEngine.dll", dir); +#elif defined(__APPLE__) + len = snprintf(path, sizeof(path), "%s/libwolfengine.dylib", dir); +#else + len = snprintf(path, sizeof(path), "%s/libwolfengine.so", dir); +#endif + if ((len < 0) || ((size_t)len >= sizeof(path))) { + PRINT_ERR_MSG("Failed to construct engine library path"); + err = 1; + } + if (err == 0) { + engine = ENGINE_by_id("dynamic"); + } + if ((err == 0) && (engine == NULL)) { + PRINT_ERR_MSG("Failed to load dynamic engine support"); + err = 1; + } + if ((err == 0) && + (ENGINE_ctrl_cmd_string(engine, "SO_PATH", path, 0) != 1)) { + PRINT_ERR_MSG("Failed to set engine library path"); + err = 1; + } + if ((err == 0) && + (ENGINE_ctrl_cmd_string(engine, "ID", wolfengine_id, 0) != 1)) { + PRINT_ERR_MSG("Failed to set engine identifier"); + err = 1; + } + if ((err == 0) && + (ENGINE_ctrl_cmd_string(engine, "LIST_ADD", "0", 0) != 1)) { + PRINT_ERR_MSG("Failed to configure dynamic engine loading"); + err = 1; + } + if (err == 0) { + name = wolfengine_name; + wolfengine_name = NULL; + rc = ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0); + wolfengine_name = name; + if (rc != 0) { + PRINT_ERR_MSG("Accepted an incomplete engine binding"); + err = 1; + } + } + + if (engine != NULL) { + ENGINE_free(engine); + } + ERR_clear_error(); + return err; +} + +#endif /* !WE_NO_DYNAMIC_ENGINE && WE_HAVE_SHARED_LIBRARY */ + +#ifndef WE_NO_DYNAMIC_ENGINE +extern int bind_engine(ENGINE *engine, const char *id, + const dynamic_fns *functions); + +#ifdef WOLFENGINE_DEBUG +static ENGINE *we_logging_bind_engine; +static dynamic_fns we_logging_bind_functions; +static int we_logging_bind_phase; +static int we_logging_bind_calls[2]; +static int we_logging_bind_err; +static int we_logging_bind_inside; + +static void test_engine_bind_logging_cb(int level, int component, + const char *const message) +{ + (void)level; + (void)component; + (void)message; + + if (we_logging_bind_inside != 0) + return; + we_logging_bind_inside = 1; + we_logging_bind_calls[we_logging_bind_phase]++; + if (bind_engine(we_logging_bind_engine, wolfengine_id, + &we_logging_bind_functions) != 0) { + we_logging_bind_err = 1; + } + ENGINE_load_wolfengine(); + we_logging_bind_inside = 0; +} + +static int test_engine_logging_bind(void) +{ + int err = 0; + ENGINE *engine = ENGINE_new(); + + we_logging_bind_engine = ENGINE_new(); + if ((engine == NULL) || (we_logging_bind_engine == NULL)) { + err = 1; + } + memset(&we_logging_bind_functions, 0, sizeof(we_logging_bind_functions)); + we_logging_bind_functions.static_state = ENGINE_get_static_state(); + we_logging_bind_phase = 0; + we_logging_bind_calls[0] = 0; + we_logging_bind_calls[1] = 0; + we_logging_bind_err = 0; + we_logging_bind_inside = 0; + if (err == 0) { + wolfEngine_SetLogLevel(WE_LOG_LEVEL_DEFAULT); + wolfEngine_SetLogComponents(WE_LOG_COMPONENTS_ALL); + wolfEngine_SetLoggingCb(test_engine_bind_logging_cb); + wolfEngine_Debugging_ON(); + if (bind_engine(engine, wolfengine_id, + &we_logging_bind_functions) != 1) { + err = 1; + } + we_logging_bind_phase = 1; + ENGINE_free(engine); + engine = NULL; + wolfEngine_Debugging_OFF(); + wolfEngine_SetLoggingCb(NULL); + if ((we_logging_bind_calls[0] == 0) || + (we_logging_bind_calls[1] == 0) || (we_logging_bind_err != 0)) { + PRINT_ERR_MSG("Logging did not preserve engine lifecycle ownership"); + err = 1; + } + } + ENGINE_free(engine); + ENGINE_free(we_logging_bind_engine); + we_logging_bind_engine = NULL; + ERR_clear_error(); + return err; +} +#endif /* WOLFENGINE_DEBUG */ + +#if !defined(WE_SINGLE_THREADED) && defined(HAVE_PTHREAD) && \ + OPENSSL_VERSION_NUMBER >= 0x10100000L +#define WE_BIND_TEST_THREADS 8 + +typedef struct we_bind_test_ctx { + ENGINE *engine; + const dynamic_fns *functions; + pthread_mutex_t *mutex; + pthread_cond_t *condition; + int *ready; + int *start; + int result; +} we_bind_test_ctx; + +static void *test_engine_bind_thread(void *arg) +{ + we_bind_test_ctx *ctx = (we_bind_test_ctx *)arg; + + pthread_mutex_lock(ctx->mutex); + (*ctx->ready)++; + pthread_cond_broadcast(ctx->condition); + while (*ctx->start == 0) { + pthread_cond_wait(ctx->condition, ctx->mutex); + } + pthread_mutex_unlock(ctx->mutex); + + ctx->result = bind_engine(ctx->engine, wolfengine_id, ctx->functions); + return NULL; +} + +static int test_engine_concurrent_bind(void) +{ + int err = 0; + int ready = 0; + int start = 0; + int created = 0; + int success = 0; + int i; + pthread_t threads[WE_BIND_TEST_THREADS]; + pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + pthread_cond_t condition = PTHREAD_COND_INITIALIZER; + dynamic_fns functions; + we_bind_test_ctx ctx[WE_BIND_TEST_THREADS]; + + memset(&functions, 0, sizeof(functions)); + functions.static_state = ENGINE_get_static_state(); + memset(ctx, 0, sizeof(ctx)); + for (i = 0; (err == 0) && (i < WE_BIND_TEST_THREADS); i++) { + ctx[i].engine = ENGINE_new(); + ctx[i].functions = &functions; + ctx[i].mutex = &mutex; + ctx[i].condition = &condition; + ctx[i].ready = &ready; + ctx[i].start = &start; + if (ctx[i].engine == NULL) { + PRINT_ERR_MSG("Failed to allocate concurrent engine binding"); + err = 1; + } + } + for (i = 0; (err == 0) && (i < WE_BIND_TEST_THREADS); i++) { + if (pthread_create(&threads[i], NULL, test_engine_bind_thread, + &ctx[i]) != 0) { + PRINT_ERR_MSG("Failed to create engine binding thread"); + err = 1; + } + else { + created++; + } + } + pthread_mutex_lock(&mutex); + while ((err == 0) && (ready != WE_BIND_TEST_THREADS)) { + pthread_cond_wait(&condition, &mutex); + } + start = 1; + pthread_cond_broadcast(&condition); + pthread_mutex_unlock(&mutex); + + for (i = 0; i < created; i++) { + pthread_join(threads[i], NULL); + } + if (err == 0) { + for (i = 0; i < WE_BIND_TEST_THREADS; i++) { + success += ctx[i].result == 1; + } + if (success != 1) { + PRINT_ERR_MSG("Concurrent engine binding did not select one owner"); + err = 1; + } + } + for (i = 0; i < WE_BIND_TEST_THREADS; i++) { + if (ctx[i].engine != NULL) { + ENGINE_free(ctx[i].engine); + } + } + pthread_cond_destroy(&condition); + pthread_mutex_destroy(&mutex); + ERR_clear_error(); + return err; +} +#endif + +static int test_engine_bind_lifecycle(const char *dir) +{ + int err = 0; + int ran = 0; + + (void)dir; + OpenSSL_add_all_ciphers(); + OpenSSL_add_all_digests(); +#ifdef WE_HAVE_SHARED_LIBRARY + ENGINE_load_dynamic(); + PRINT_MSG("Engine binding rollback and identifiers"); + ran = 1; + err = test_engine_bind_rollback(dir); + if (err == 0) { + err = test_engine_id_match(dir); + } +#endif +#ifdef WOLFENGINE_DEBUG + if (err == 0) { + PRINT_MSG("Engine logging lifecycle ownership"); + ran = 1; + err = test_engine_logging_bind(); + } +#endif +#if !defined(WE_SINGLE_THREADED) && defined(HAVE_PTHREAD) && \ + OPENSSL_VERSION_NUMBER >= 0x10100000L + if (err == 0) { + PRINT_MSG("Concurrent engine binding ownership"); + ran = 1; + err = test_engine_concurrent_bind(); + } +#endif + return ran ? err : 77; +} +#endif /* !WE_NO_DYNAMIC_ENGINE */ +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ + (defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC)) +static int mac_asn1_methods_cleared(void) +{ + int ret = 1; + +#ifdef WE_HAVE_HMAC + if (we_hmac_pkey_asn1_method != NULL) + ret = 0; +#endif +#ifdef WE_HAVE_CMAC + if ((we_cmac_pkey_asn1_method != NULL) || + (we_cmac_we_pkey_asn1_method != NULL)) { + ret = 0; + } +#endif + + return ret; +} +#endif + +#if defined(WE_TEST_INTERNAL_GLOBALS) && \ + OPENSSL_VERSION_NUMBER >= 0x10100000L +static int test_engine_destroyed(void) +{ + int err = 0; + +#ifdef WE_HAVE_HMAC + if (we_hmac_pkey_method != NULL) { + err = 1; + } +#endif +#ifdef WE_HAVE_CMAC + if ((we_cmac_pkey_method != NULL) || + (we_cmac_we_pkey_method != NULL)) { + err = 1; + } +#endif +#if defined(WE_HAVE_TLS1_PRF) && defined(WE_HAVE_EVP_PKEY) + if (we_tls1_prf_method != NULL) { + err = 1; + } +#endif +#if defined(WE_HAVE_HKDF) && defined(WE_HAVE_EVP_PKEY) + if (we_hkdf_method != NULL) { + err = 1; + } +#endif +#if defined(WE_HAVE_DH) && defined(WE_HAVE_EVP_PKEY) + if (we_dh_pkey_method != NULL) { + err = 1; + } +#endif +#if defined(WE_HAVE_RSA) && defined(WE_HAVE_EVP_PKEY) + if (we_rsa_pkey_method != NULL) { + err = 1; + } +#endif +#if defined(WE_HAVE_ECC) && defined(WE_HAVE_EVP_PKEY) + if (we_ec_method != NULL) { + err = 1; + } +#ifdef WE_HAVE_ECKEYGEN +#ifdef WE_HAVE_EC_P192 + if (we_ec_p192_method != NULL) { + err = 1; + } +#endif +#ifdef WE_HAVE_EC_P224 + if (we_ec_p224_method != NULL) { + err = 1; + } +#endif +#ifdef WE_HAVE_EC_P256 + if (we_ec_p256_method != NULL) { + err = 1; + } +#endif +#ifdef WE_HAVE_EC_P384 + if (we_ec_p384_method != NULL) { + err = 1; + } +#endif +#ifdef WE_HAVE_EC_P521 + if (we_ec_p521_method != NULL) { + err = 1; + } +#endif +#endif /* WE_HAVE_ECKEYGEN */ +#endif /* WE_HAVE_ECC && WE_HAVE_EVP_PKEY */ + + if (err != 0) { + PRINT_ERR_MSG("Engine PKEY methods remain allocated after teardown"); + } + + return err; +} +#endif + TEST_CASE test_case[] = { TEST_DECL(test_logging, &debug), +#if OPENSSL_VERSION_NUMBER < 0x10100000L + TEST_DECL(test_openssl_bc_method_name, &flags), + TEST_DECL(test_openssl_bc_public_ec_key, NULL), + TEST_DECL(test_openssl_bc_ec_private_padding, NULL), +#endif #ifdef WE_HAVE_SHA1 TEST_DECL(test_sha, NULL), #endif @@ -69,6 +818,9 @@ TEST_CASE test_case[] = { #ifdef WE_HAVE_SHA512 TEST_DECL(test_sha512, NULL), #endif +#ifdef WE_HAVE_AESCCM + TEST_DECL(test_aes_ccm_keyed_reinit, NULL), +#endif #ifdef WE_HAVE_SHA3_224 TEST_DECL(test_sha3_224, NULL), #endif @@ -83,13 +835,36 @@ TEST_CASE test_case[] = { #endif #ifdef WE_HAVE_HMAC TEST_DECL(test_hmac_create, NULL), + TEST_DECL(test_hmac_output_size, NULL), + TEST_DECL(test_hmac_pkey_size, NULL), + TEST_DECL(test_hmac_update_size, NULL), + #if OPENSSL_VERSION_NUMBER >= 0x10101000L && \ + !defined(TEST_MULTITHREADED) + TEST_DECL(test_hmac_raw_key_output_size, NULL), + #endif #endif #ifdef WE_HAVE_CMAC TEST_DECL(test_cmac_create, &flags), + TEST_DECL(test_cmac_output_size, NULL), + TEST_DECL(test_cmac_update_size, NULL), + #ifndef TEST_MULTITHREADED + TEST_DECL(test_cmac_copy_error, NULL), + #endif + TEST_DECL(test_cmac_copy, NULL), + TEST_DECL(test_cmac_keygen_reuse, NULL), + #ifndef TEST_MULTITHREADED + TEST_DECL(test_cmac_unregistered_engine, NULL), + #endif + TEST_DECL(test_cmac_asn1_registry, NULL), +#endif +#if defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC) + TEST_DECL(test_mac_asn1_ownership, NULL), #endif #ifdef WE_HAVE_TLS1_PRF TEST_DECL(test_tls1_prf, NULL), TEST_DECL(test_tls1_prf_bad_md, NULL), + TEST_DECL(test_tls1_prf_secret_failure, &debug), + TEST_DECL(test_tls1_prf_output_size, NULL), #endif #ifdef WE_HAVE_HKDF TEST_DECL(test_hkdf, NULL), @@ -98,6 +873,9 @@ TEST_CASE test_case[] = { #ifdef WE_HAVE_DES3CBC TEST_DECL(test_des3_cbc, NULL), TEST_DECL(test_des3_cbc_stream, NULL), + TEST_DECL(test_des3_cbc_iv_bounds, NULL), + TEST_DECL(test_des3_cbc_decrypt_error_log, &debug), + TEST_DECL(test_des3_cbc_rekey_cleanup, NULL), #endif #ifdef WE_HAVE_AESECB TEST_DECL(test_aes128_ecb, NULL), @@ -115,6 +893,19 @@ TEST_CASE test_case[] = { TEST_DECL(test_aes192_cbc_stream, NULL), TEST_DECL(test_aes256_cbc_stream, NULL), TEST_DECL(test_aes128_cbc_hmac_tls_short, NULL), + TEST_DECL(test_aes128_cbc_hmac_staged_init, NULL), + TEST_DECL(test_aes128_cbc_hmac_plain_encrypt, NULL), + TEST_DECL(test_aes128_cbc_hmac_tls_bad_length_reset, NULL), + TEST_DECL(test_aes128_cbc_hmac_encrypt_error, NULL), + TEST_DECL(test_aes128_cbc_hmac_ctrl_error, NULL), + TEST_DECL(test_aes128_cbc_hmac_tls_empty, NULL), + TEST_DECL(test_aes128_cbc_hmac_reinit_state, NULL), + TEST_DECL(test_aes128_cbc_hmac_cleanup, NULL), + TEST_DECL(test_aes128_cbc_hmac_tls_lengths, NULL), + TEST_DECL(test_aes128_cbc_hmac_no_tls_mac, NULL), + TEST_DECL(test_aes128_cbc_hmac_tls_extended_padding, NULL), + TEST_DECL(test_aes128_cbc_hmac_tls_retry_after_bad_padding, NULL), + TEST_DECL(test_aes128_cbc_hmac_tls_padding_range, NULL), #endif #ifdef WE_HAVE_AESCTR TEST_DECL(test_aes128_ctr_stream, NULL), @@ -135,6 +926,12 @@ TEST_CASE test_case[] = { TEST_DECL(test_aes_gcm_tls_fixed_iv_required, NULL), TEST_DECL(test_aes_gcm_evp_cipher, NULL), TEST_DECL(test_aes128_gcm_iv_gen_bounds, NULL), + TEST_DECL(test_aes_gcm_ctx_copy_rejected, NULL), + TEST_DECL(test_aes_gcm_keyed_reinit, NULL), + TEST_DECL(test_aes_gcm_cleanup_empty_ctx, NULL), + TEST_DECL(test_aes_gcm_aad_length_bounds, NULL), + TEST_DECL(test_aes_gcm_auth_error_queue, NULL), + TEST_DECL(test_aes_gcm_ctrl_output_buffers, NULL), #endif #ifdef WE_HAVE_AESCCM TEST_DECL(test_aes128_ccm, NULL), @@ -148,7 +945,7 @@ TEST_CASE test_case[] = { #endif #endif #ifdef WE_HAVE_RANDOM - TEST_DECL(test_random, NULL), + TEST_DECL(test_random, &flags), #endif #ifdef WE_HAVE_RSA TEST_DECL(test_rsa_ctrl_str, NULL), @@ -200,7 +997,12 @@ TEST_CASE test_case[] = { TEST_DECL(test_rsa_enc_dec_no_pad, NULL), TEST_DECL(test_rsa_dec_no_pad_size_query, NULL), TEST_DECL(test_rsa_enc_dec_oaep, NULL), + TEST_DECL(test_rsa_oaep_label, NULL), TEST_DECL(test_rsa_pkey_keygen, NULL), + TEST_DECL(test_rsa_pkey_large_exponent, NULL), + TEST_DECL(test_rsa_pkey_sign_missing_data, NULL), + TEST_DECL(test_rsa_pkey_sign_digest_length, NULL), + TEST_DECL(test_rsa_verify_recover_digest, NULL), TEST_DECL(test_rsa_pkey_invalid_key_size, NULL), #endif /* WE_HAVE_RSA */ #ifdef WE_HAVE_EC_P192 @@ -364,8 +1166,10 @@ TEST_CASE test_case[] = { #endif /* WE_HAVE_ECDSA */ #ifdef WE_HAVE_PBE + TEST_DECL(test_pbe_invalid_params, NULL), TEST_DECL(test_pbe, NULL), #endif + TEST_DECL(test_engine, NULL), }; #define TEST_CASE_CNT (int)(sizeof(test_case) / sizeof(*test_case)) @@ -375,6 +1179,7 @@ static void usage(void) printf("Usage: unit.test [options]\n"); printf(" --help Show this usage information.\n"); printf(" --static Run the tests using the static engine.\n"); + printf(" --bind-lifecycle Run the engine lifecycle checks only.\n"); printf(" --dir Location of wolfengine shared library.\n"); printf(" Default: .libs\n"); printf(" --engine Name of wolfsslengine. Default: libwolfengine\n"); @@ -520,6 +1325,22 @@ static int run_tests(ENGINE *e, int runAll) } } + ENGINE_free(e); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + OPENSSL_cleanup(); + #if defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC) + if (!mac_asn1_methods_cleared()) { + fprintf(stderr, "MAC ASN.1 methods not cleared at teardown\n"); + err = 1; + } + #endif +#ifdef WE_TEST_INTERNAL_GLOBALS + if (test_engine_destroyed() != 0) { + err = 1; + } +#endif +#endif + if (err == 0) { printf("###### TESTSUITE SUCCESS\n"); } @@ -532,11 +1353,6 @@ static int run_tests(ENGINE *e, int runAll) printf("###### TESTSUITE FAILED\n"); } - ENGINE_free(e); -#if OPENSSL_VERSION_NUMBER >= 0x10100000L - OPENSSL_cleanup(); -#endif - return err; } @@ -578,6 +1394,22 @@ static int run_tests(ENGINE *e, int runAll) } } + ENGINE_free(e); +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + OPENSSL_cleanup(); + #if defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC) + if (!mac_asn1_methods_cleared()) { + fprintf(stderr, "MAC ASN.1 methods not cleared at teardown\n"); + err = 1; + } + #endif +#ifdef WE_TEST_INTERNAL_GLOBALS + if (test_engine_destroyed() != 0) { + err = 1; + } +#endif +#endif + if (err == 0) { printf("###### TESTSUITE SUCCESS\n"); } @@ -590,11 +1422,6 @@ static int run_tests(ENGINE *e, int runAll) printf("###### TESTSUITE FAILED\n"); } - ENGINE_free(e); -#if OPENSSL_VERSION_NUMBER >= 0x10100000L - OPENSSL_cleanup(); -#endif - return err; } @@ -604,7 +1431,7 @@ int main(int argc, char* argv[]) { int err = 0; ENGINE *e = NULL; -#ifdef WE_NO_DYNAMIC_ENGINE +#if defined(WE_NO_DYNAMIC_ENGINE) || !defined(WE_HAVE_SHARED_LIBRARY) int staticTest = 1; #else int staticTest = 0; @@ -615,6 +1442,37 @@ int main(int argc, char* argv[]) int runAll = 1; int runTests = 1; +#ifndef TEST_MULTITHREADED + if (!test_openssl_mem_clear_check()) { + fprintf(stderr, "Memory clearing observer failed\n"); + return 1; + } +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (!test_mac_allocation_source("src/we_mac.c") || + !test_mac_allocation_source("..\\src\\we_mac.c") || + !test_mac_allocation_source("we_mac.c") || + test_mac_allocation_source("other_we_mac.c") || + test_mac_allocation_source("") || test_mac_allocation_source(NULL)) { + fprintf(stderr, "Allocation callsite matching failed\n"); + return 1; + } +#endif +#ifdef HAVE_VALGRIND_MEMCHECK_H + VALGRIND_CREATE_MEMPOOL(&testActiveAllocs, 0, 0); +#endif + if (CRYPTO_set_mem_functions(test_openssl_malloc, test_openssl_realloc, + test_openssl_free) != 1) { + fprintf(stderr, "Unable to install test memory functions\n"); + return 1; + } +#endif + +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FIND) + if (wolfCrypt_Init() != 0) { + return 1; + } +#endif + for (--argc, ++argv; argc > 0; argc--, argv++) { if (strncmp(*argv, "--help", 6) == 0) { usage(); @@ -668,6 +1526,13 @@ int main(int argc, char* argv[]) printf("Running tests for %d seconds\n", secs); } #endif + else if (strcmp(*argv, "--bind-lifecycle") == 0) { + #ifndef WE_NO_DYNAMIC_ENGINE + return test_engine_bind_lifecycle(dir); + #else + return 77; + #endif + } else if (strncmp(*argv, "--no-debug", 11) == 0) { debug = 0; } @@ -710,8 +1575,10 @@ int main(int argc, char* argv[]) if (staticTest == 1) { printf("Running tests using static engine.\n"); - ENGINE_load_wolfengine(); - name = wolfengine_id; + if (err == 0) { + ENGINE_load_wolfengine(); + name = wolfengine_id; + } } #ifndef WE_NO_DYNAMIC_ENGINE else { @@ -761,9 +1628,15 @@ int main(int argc, char* argv[]) #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_cleanup(); ENGINE_cleanup(); + CRYPTO_cleanup_all_ex_data(); + ERR_remove_thread_state(NULL); ERR_free_strings(); #endif +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FIND) + wolfCrypt_Cleanup(); +#endif + return err; } diff --git a/test/unit.h b/test/unit.h index 2d519726..fb6bdfae 100644 --- a/test/unit.h +++ b/test/unit.h @@ -22,10 +22,16 @@ #ifndef UNIT_H #define UNIT_H +/* Archive-only test builds can enable hidden internal MAC checks. */ +#if defined(WE_MAC_STATIC_TEST) && defined(WOLFENGINE_DLL) +#error WE_MAC_STATIC_TEST requires archive-only linkage +#endif + /* OpenSSL 3.0.0 has deprecated the ENGINE API. */ #define OPENSSL_API_COMPAT 10101 #include +#include #ifdef WOLFENGINE_USER_SETTINGS #include @@ -87,10 +93,28 @@ typedef struct TEST_CASE { #endif } TEST_CASE; +#ifdef WE_HAVE_AESCCM +int test_aes_ccm_keyed_reinit(ENGINE *e, void *data); +#endif + int test_logging(ENGINE *e, void *data); +#if OPENSSL_VERSION_NUMBER < 0x10100000L +int test_openssl_bc_method_name(ENGINE *e, void *data); +int test_openssl_bc_public_ec_key(ENGINE *e, void *data); +int test_openssl_bc_ec_private_padding(ENGINE *e, void *data); +#endif + #define WE_VALGRIND_TEST 0x1 +void test_openssl_mem_expect_clear(void *ptr); +void test_openssl_mem_expect_next_clear(size_t size); +int test_openssl_mem_clear_result(void); +void test_openssl_mem_fail_once(size_t size); +int test_openssl_mem_failure_triggered(void); +size_t test_openssl_mem_active(void); +int test_openssl_mem_has_source(void); + #ifdef WE_HAVE_DIGEST int test_digest_op(const EVP_MD *md, ENGINE *e, unsigned char *msg, @@ -110,15 +134,34 @@ int test_sha3_512(ENGINE *e, void *data); #ifdef WE_HAVE_CMAC int test_cmac_create(ENGINE *e, void *data); -#endif /* WE_HAVE_HMAC */ +int test_cmac_output_size(ENGINE *e, void *data); +int test_cmac_update_size(ENGINE *e, void *data); +int test_cmac_copy_error(ENGINE *e, void *data); +int test_cmac_copy(ENGINE *e, void *data); +int test_cmac_keygen_reuse(ENGINE *e, void *data); +int test_cmac_unregistered_engine(ENGINE *e, void *data); +int test_cmac_asn1_registry(ENGINE *e, void *data); +#endif /* WE_HAVE_CMAC */ + +#if defined(WE_HAVE_HMAC) || defined(WE_HAVE_CMAC) +int test_mac_asn1_ownership(ENGINE *e, void *data); +#endif #ifdef WE_HAVE_HMAC int test_hmac_create(ENGINE *e, void *data); +int test_hmac_output_size(ENGINE *e, void *data); +int test_hmac_pkey_size(ENGINE *e, void *data); +int test_hmac_update_size(ENGINE *e, void *data); +#if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(TEST_MULTITHREADED) +int test_hmac_raw_key_output_size(ENGINE *e, void *data); +#endif #endif /* WE_HAVE_HMAC */ #ifdef WE_HAVE_TLS1_PRF int test_tls1_prf(ENGINE *e, void *data); int test_tls1_prf_bad_md(ENGINE *e, void *data); +int test_tls1_prf_secret_failure(ENGINE *e, void *data); +int test_tls1_prf_output_size(ENGINE *e, void *data); #endif #ifdef WE_HAVE_HKDF @@ -129,6 +172,9 @@ int test_hkdf_bad_md(ENGINE *e, void *data); #ifdef WE_HAVE_DES3CBC int test_des3_cbc(ENGINE *e, void *data); int test_des3_cbc_stream(ENGINE *e, void *data); +int test_des3_cbc_iv_bounds(ENGINE *e, void *data); +int test_des3_cbc_decrypt_error_log(ENGINE *e, void *data); +int test_des3_cbc_rekey_cleanup(ENGINE *e, void *data); #endif #ifdef WE_HAVE_AESECB @@ -151,6 +197,19 @@ int test_aes128_cbc_stream(ENGINE *e, void *data); int test_aes192_cbc_stream(ENGINE *e, void *data); int test_aes256_cbc_stream(ENGINE *e, void *data); int test_aes128_cbc_hmac_tls_short(ENGINE *e, void *data); +int test_aes128_cbc_hmac_staged_init(ENGINE *e, void *data); +int test_aes128_cbc_hmac_plain_encrypt(ENGINE *e, void *data); +int test_aes128_cbc_hmac_tls_bad_length_reset(ENGINE *e, void *data); +int test_aes128_cbc_hmac_encrypt_error(ENGINE *e, void *data); +int test_aes128_cbc_hmac_ctrl_error(ENGINE *e, void *data); +int test_aes128_cbc_hmac_tls_empty(ENGINE *e, void *data); +int test_aes128_cbc_hmac_reinit_state(ENGINE *e, void *data); +int test_aes128_cbc_hmac_cleanup(ENGINE *e, void *data); +int test_aes128_cbc_hmac_tls_lengths(ENGINE *e, void *data); +int test_aes128_cbc_hmac_no_tls_mac(ENGINE *e, void *data); +int test_aes128_cbc_hmac_tls_extended_padding(ENGINE *e, void *data); +int test_aes128_cbc_hmac_tls_retry_after_bad_padding(ENGINE *e, void *data); +int test_aes128_cbc_hmac_tls_padding_range(ENGINE *e, void *data); #endif @@ -178,6 +237,12 @@ int test_aes_gcm_tls_bad_iv_len(ENGINE *e, void *data); int test_aes_gcm_tls_fixed_iv_required(ENGINE *e, void *data); int test_aes_gcm_evp_cipher(ENGINE *e, void *data); int test_aes128_gcm_iv_gen_bounds(ENGINE *e, void *data); +int test_aes_gcm_ctx_copy_rejected(ENGINE *e, void *data); +int test_aes_gcm_keyed_reinit(ENGINE *e, void *data); +int test_aes_gcm_cleanup_empty_ctx(ENGINE *e, void *data); +int test_aes_gcm_aad_length_bounds(ENGINE *e, void *data); +int test_aes_gcm_auth_error_queue(ENGINE *e, void *data); +int test_aes_gcm_ctrl_output_buffers(ENGINE *e, void *data); #endif /* WE_HAVE_AESGCM */ @@ -249,7 +314,12 @@ int test_rsa_enc_dec_pkcs1(ENGINE *e, void *data); int test_rsa_enc_dec_no_pad(ENGINE *e, void *data); int test_rsa_dec_no_pad_size_query(ENGINE *e, void *data); int test_rsa_enc_dec_oaep(ENGINE *e, void *data); +int test_rsa_oaep_label(ENGINE *e, void *data); int test_rsa_pkey_keygen(ENGINE *e, void *data); +int test_rsa_pkey_large_exponent(ENGINE *e, void *data); +int test_rsa_pkey_sign_missing_data(ENGINE *e, void *data); +int test_rsa_pkey_sign_digest_length(ENGINE *e, void *data); +int test_rsa_verify_recover_digest(ENGINE *e, void *data); int test_rsa_pkey_invalid_key_size(ENGINE *e, void *data); #endif /* WE_HAVE_EVP_PKEY */ @@ -506,6 +576,7 @@ int test_ecdsa(ENGINE *e, void *data); #endif /* WE_HAVE_ECC */ #ifdef WE_HAVE_PBE +int test_pbe_invalid_params(ENGINE *e, void *data); int test_pbe(ENGINE *e, void *data); #endif /* WE_HAVE_PBE */ diff --git a/test/unit_static.test b/test/unit_static.test new file mode 100755 index 00000000..c6cd9b5b --- /dev/null +++ b/test/unit_static.test @@ -0,0 +1,3 @@ +#!/bin/sh + +exec ./test/unit.test --static diff --git a/windows/test.vcxproj b/windows/test.vcxproj index 738a21e8..2b964663 100644 --- a/windows/test.vcxproj +++ b/windows/test.vcxproj @@ -326,6 +326,7 @@ + diff --git a/windows/test.vcxproj.filters b/windows/test.vcxproj.filters index 0ad2bdf2..840d08ae 100644 --- a/windows/test.vcxproj.filters +++ b/windows/test.vcxproj.filters @@ -42,6 +42,9 @@ Source Files + + Source Files + Source Files