diff --git a/CMakeLists.txt b/CMakeLists.txt index 4309d387325..8b71b46717d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4228,6 +4228,7 @@ add_option("WOLFSSL_FAULTHARDEN" if(WOLFSSL_FAULTHARDEN) list(APPEND WOLFSSL_DEFINITIONS "-DWOLFSSL_CHECK_SIG_FAULTS" "-DWOLFSSL_CHECK_VER_FAULTS" "-DWC_SHA3_FAULT_HARDEN" "-DWC_MLKEM_FAULT_HARDEN" "-DWC_MLDSA_FAULT_HARDEN" + "-DWOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN" ) endif() diff --git a/cmake/options.h.in b/cmake/options.h.in index c19d8fc163d..2b7eb5b18d7 100644 --- a/cmake/options.h.in +++ b/cmake/options.h.in @@ -620,6 +620,8 @@ extern "C" { #cmakedefine WC_MLKEM_FAULT_HARDEN #undef WC_MLDSA_FAULT_HARDEN #cmakedefine WC_MLDSA_FAULT_HARDEN +#undef WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN +#cmakedefine WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN #undef WOLFSSL_SM3 #cmakedefine WOLFSSL_SM3 #undef WOLFSSL_SM3_SMALL diff --git a/configure.ac b/configure.ac index dbc86034e1c..1580db380a0 100644 --- a/configure.ac +++ b/configure.ac @@ -3640,7 +3640,7 @@ AC_ARG_ENABLE([faultharden], if test "$ENABLED_FAULTHARDEN" = "yes" then - AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CHECK_SIG_FAULTS -DWOLFSSL_CHECK_VER_FAULTS -DWC_SHA3_FAULT_HARDEN -DWC_MLKEM_FAULT_HARDEN -DWC_MLDSA_FAULT_HARDEN" + AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_CHECK_SIG_FAULTS -DWOLFSSL_CHECK_VER_FAULTS -DWC_SHA3_FAULT_HARDEN -DWC_MLKEM_FAULT_HARDEN -DWC_MLDSA_FAULT_HARDEN -DWOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN" fi AC_ARG_ENABLE([compileharden], diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index bcda61001da..e3a48b5f073 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -17508,6 +17508,14 @@ static WARN_UNUSED_RESULT int _AesEcbEncrypt( return MISSING_KEY; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* The key is only on the SE050, so there is no software schedule. */ + if (aes->useSWCrypt == 0) { + return se050_aes_crypt(aes, in, out, sz, AES_ENCRYPTION, + kAlgorithm_SSS_AES_ECB); + } +#endif + VECTOR_REGISTERS_PUSH; #if defined(WOLFSSL_RISCV_ASM) @@ -17627,6 +17635,14 @@ static WARN_UNUSED_RESULT int _AesEcbDecrypt( return MISSING_KEY; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* The key is only on the SE050, so there is no software schedule. */ + if (aes->useSWCrypt == 0) { + return se050_aes_crypt(aes, in, out, sz, AES_DECRYPTION, + kAlgorithm_SSS_AES_ECB); + } +#endif + VECTOR_REGISTERS_PUSH; #if defined(WOLFSSL_RISCV_ASM) diff --git a/wolfcrypt/src/cmac.c b/wolfcrypt/src/cmac.c index 430ff67ff81..f52ba8bb051 100644 --- a/wolfcrypt/src/cmac.c +++ b/wolfcrypt/src/cmac.c @@ -652,6 +652,12 @@ int wc_AesCmacGenerate(byte* out, word32* outSz, wc_MemZero_Add("wc_AesCmacGenerate_ex cmac", ((unsigned char *)cmac) + sizeof(Aes), sizeof(Cmac) - sizeof(Aes)); #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* wc_InitCmac_ex() carries useSWCrypt over its reset of the object, so + * give it the default (use the SE050) rather than whatever this + * uninitialized buffer holds. */ + cmac->useSWCrypt = 0; +#endif ret = wc_AesCmacGenerate_ex(cmac, out, outSz, @@ -754,6 +760,10 @@ int wc_AesCmacVerify(const byte* check, word32 checkSz, wc_MemZero_Add("wc_AesCmacGenerate_ex cmac", ((unsigned char *)cmac) + sizeof(Aes), sizeof(Cmac) - sizeof(Aes)); #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_CRYPT) + /* See wc_AesCmacGenerate(). */ + cmac->useSWCrypt = 0; +#endif ret = wc_AesCmacVerify_ex(cmac, check, checkSz, diff --git a/wolfcrypt/src/ed25519.c b/wolfcrypt/src/ed25519.c index 4e881a3c5da..3630d672182 100644 --- a/wolfcrypt/src/ed25519.c +++ b/wolfcrypt/src/ed25519.c @@ -26,6 +26,9 @@ /* Possible Ed25519 enable options: * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN Default: OFF * Check that the private key didn't change during the signing operations. + * Enabled by --enable-faultharden. Covers the software signer only: a + * signature made by a device (SE050, crypto callback) uses the key the + * device holds and is that device's responsibility. */ #define WC_FIPS_LL_CRYPTO @@ -663,7 +666,9 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_ONLY_KEY_ID) /* Key resident in the SE050: sign in hardware. Software keys fall through - * to the wolfCrypt software implementation below. */ + * to the wolfCrypt software implementation below. The private key never + * leaves the SE050 here, so WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN has no host + * copy to compare; protecting it is the secure element's job. */ if (key->keyIdSet) { /* The SE050 performs only PureEdDSA; it cannot apply the Ed25519ctx or * Ed25519ph variants, so reject them rather than silently signing with @@ -686,6 +691,9 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, if (key->devId != INVALID_DEVID) #endif { + /* A device that signs uses the key it holds, so the + * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN check below, which guards the + * software signer's copy of the key, is the device's to provide. */ ret = wc_CryptoCb_Ed25519Sign(in, inLen, out, outLen, key, type, context, contextLen); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) @@ -860,7 +868,13 @@ int wc_ed25519_sign_msg_ex(const byte* in, word32 inLen, byte* out, for (i = 0; i < ED25519_KEY_SIZE; i++) { c |= key->k[i] ^ orig_k[i]; } - ret = ctMaskGT(c, 0) & SIG_VERIFY_E; + /* ctMaskGT() gives a byte mask: select the error code with it rather + * than AND it into the (negative) error code. */ + ret = ctMaskSelInt(ctMaskGT(c, 0), SIG_VERIFY_E, 0); + if (ret != 0) { + /* Do not hand out a signature made while the key changed. */ + ForceZero(out, ED25519_SIG_SIZE); + } } ForceZero(orig_k, sizeof(orig_k)); #ifdef WOLFSSL_CHECK_MEM_ZERO diff --git a/wolfcrypt/src/ed448.c b/wolfcrypt/src/ed448.c index 93ab3c0d58a..00d0c5ac626 100644 --- a/wolfcrypt/src/ed448.c +++ b/wolfcrypt/src/ed448.c @@ -28,6 +28,9 @@ /* Possible Ed448 enable options: * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN Default: OFF * Check that the private key didn't change during the signing operations. + * Enabled by --enable-faultharden. Covers the software signer only: a + * signature made by a device (SE050, crypto callback) uses the key the + * device holds and is that device's responsibility. */ #define WC_FIPS_LL_CRYPTO @@ -623,6 +626,10 @@ int wc_ed448_sign_msg_ex(const byte* in, word32 inLen, byte* out, if (key->devId != INVALID_DEVID) #endif { + /* A device that signs uses the key it holds, so the + * WOLFSSL_EDDSA_CHECK_PRIV_ON_SIGN check below, which guards the + * software signer's copy of the key, is the device's to + * provide. */ ret = wc_CryptoCb_Ed448Sign(in, inLen, out, outLen, key, type, context, contextLen); if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) @@ -777,7 +784,13 @@ int wc_ed448_sign_msg_ex(const byte* in, word32 inLen, byte* out, for (i = 0; i < ED448_KEY_SIZE; i++) { c |= key->k[i] ^ orig_k[i]; } - ret = ctMaskGT(c, 0) & SIG_VERIFY_E; + /* ctMaskGT() gives a byte mask: select the error code with it rather + * than AND it into the (negative) error code. */ + ret = ctMaskSelInt(ctMaskGT(c, 0), SIG_VERIFY_E, 0); + if (ret != 0) { + /* Do not hand out a signature made while the key changed. */ + ForceZero(out, ED448_SIG_SIZE); + } } ForceZero(orig_k, sizeof(orig_k)); #ifdef WOLFSSL_CHECK_MEM_ZERO diff --git a/wolfcrypt/src/port/nxp/README_SE050.md b/wolfcrypt/src/port/nxp/README_SE050.md index 363b975c56e..f05d77a2f60 100644 --- a/wolfcrypt/src/port/nxp/README_SE050.md +++ b/wolfcrypt/src/port/nxp/README_SE050.md @@ -224,6 +224,16 @@ SHA2-384, SHA2-512) to the SE050. This is MUCH slower than using wolfCrypt software cryptography due to the I2C communication channel. This support is disabled by default unless this define explicitly enables it. +The SHA-256 or SHA-512 inside wolfCrypt's Hash DRBG stays in software either +way, so the DRBG state (V, C and seed material) never crosses the I2C bus and +generating random data sends no commands to the SE050. + +The SE050 keeps no intermediate digest, so the raw hash accessors +(`wc_ShaFinalRaw()`, `wc_Sha512FinalRaw()`, `wc_Sha256FinalRaw()` and the +`wc_Sha*Transform()` functions) return `NOT_COMPILED_IN` for a hash on the +SE050. This define therefore also defines `WOLFSSL_NO_HASH_RAW`, so TLS, LMS +and XMSS use the full hash calls. + **`WOLFSSL_SE050_CRYPT`** wolfSSL supports offloading symmetric crypto operations (AES-ECB/CBC) to the @@ -582,6 +592,35 @@ build routes to the SE05x, while holding this lock; those acquire it internally. wolfCrypt operations on other hardware, such as an on-chip accelerator, do not take this lock and may be used while it is held. +### SE05x Sessions and fork() + +A child created with `fork()` inherits the parent's SE05x session: the +transport file descriptor, the T=1 protocol state and, with Platform SCP03, +the secure channel state. If both processes sent commands on it, the commands +would interleave and break the session for both. The child also inherits the +SE05x mutex, possibly locked by a parent thread that does not exist in the +child. + +On systems with `getpid()`, the port records which process configured the +session and refuses the session in any other process. In a forked child, +`wc_se050_lock()` and every wolfCrypt operation that the build routes to the +SE05x fail with an error (for example `BAD_STATE_E`, `BAD_MUTEX_E` or +`WC_HW_E`) and send nothing. The parent's session is not affected. Without +`WOLFSSL_SE050_NO_TRNG` this includes the seed, so a child cannot reseed or +draw from a `WC_RNG` in those builds either. The DRBG's own hash runs in +software, also with `WOLFSSL_SE050_HASH`, so it does not stop a child. + +A child that needs the SE05x must set up its own session, and only once the +parent no longer uses its session (for example after the parent of a +daemonizing `fork()` has exited): + +- With `WOLFSSL_SE050_INIT`, call `wc_se050_close()` (or `wolfCrypt_Cleanup()` + for the last reference) in the child. In a child this discards the inherited + session without sending anything. Then call `wc_se050_init()` or + `wc_se050_init_ex()`, or `wolfCrypt_Init()`, to open a new one. +- With an application session, open a new one through the middleware and pass + it to `wc_se050_set_config()` in the child. + ### wolfSSL SE050 Key Generation wolfSSL includes APIs for key generation when `WOLFSSL_KEY_GEN` has been diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index 6201b3d183f..9f1f6616407 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -55,11 +55,27 @@ #include +#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) + /* getpid(), to keep a fork() child off the parent's session */ + #include + #define SE050_FORK_CHECK +#endif + #ifdef WOLFSSL_SE050_INIT #ifndef SE050_DEFAULT_PORT #define SE050_DEFAULT_PORT "/dev/i2c-1" #endif + /* With the wolfSSL host crypto, ex_sss_boot.h includes the middleware's + * fsl_sss_wolfssl_types.h, which includes . This file + * is a library object configured through CFLAGS and settings.h has + * already run, so options.h would put back macros that settings.h + * removed, such as WOLFSSL_SMALL_STACK_CACHE without WOLFSSL_SMALL_STACK. + * Headers first read after that point (ecc.h) would then lay out their + * structs differently from the rest of the library. */ + #ifndef WOLFSSL_NO_OPTIONS_H + #define WOLFSSL_NO_OPTIONS_H + #endif #include "ex_sss_boot.h" #if defined(SSS_HAVE_SE05X_AUTH_PLATFSCP03) && \ SSS_HAVE_SE05X_AUTH_PLATFSCP03 @@ -124,6 +140,26 @@ static int se050MutexInit = 0; #endif #endif /* !SINGLE_THREADED */ +#ifdef SE050_FORK_CHECK +/* The process that configured the session, 0 while none is configured. + * A fork() child inherits the session (transport fd, T=1 sequence state and + * any SCP03 MAC chain) along with se050Mutex, which may be locked by a + * parent thread that does not exist in the child. The child must touch + * neither: its APDUs would interleave with the parent's on the one session, + * and the inherited mutex might never be released. */ +static pid_t se050OwnerPid = 0; +#endif + +/* Nonzero in a fork() child of the process that configured the session. */ +static int se050_in_fork_child(void) +{ +#ifdef SE050_FORK_CHECK + return (se050OwnerPid != 0) && (se050OwnerPid != getpid()); +#else + return 0; +#endif +} + static int se050_mutex_init(void) { int ret = 0; @@ -138,6 +174,25 @@ static int se050_mutex_init(void) return ret; } +#ifdef SE050_FORK_CHECK +/* Give a fork() child a fresh port mutex. Its inherited copy may be locked + * by a thread that exists only in the parent, and nothing in the child can + * be holding it: wc_se050_lock() refuses the child until it has a session of + * its own. */ +static int se050_mutex_reset(void) +{ + int ret = 0; +#ifndef SINGLE_THREADED + XMEMSET(&se050Mutex, 0, sizeof(se050Mutex)); + ret = wc_InitMutex(&se050Mutex); +#ifndef WOLFSSL_MUTEX_INITIALIZER + se050MutexInit = (ret == 0) ? 1 : 0; +#endif +#endif + return ret; +} +#endif /* SE050_FORK_CHECK */ + int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, sss_key_store_t *pKeyStore) { @@ -146,7 +201,16 @@ int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, if ((pSession == NULL) || (pKeyStore == NULL)) { return BAD_FUNC_ARG; } - ret = se050_mutex_init(); +#ifdef SE050_FORK_CHECK + if (se050_in_fork_child()) { + /* A fork() child adopting a session of its own. */ + ret = se050_mutex_reset(); + } + else +#endif + { + ret = se050_mutex_init(); + } if (ret != 0) { return ret; } @@ -156,6 +220,9 @@ int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, cfg_se050_i2c_pi = pSession; gHostKeyStore = pHostKeyStore; gKeyStore = pKeyStore; +#ifdef SE050_FORK_CHECK + se050OwnerPid = getpid(); +#endif return 0; } @@ -198,16 +265,22 @@ pSe05xSession_t wc_se050_get_se05x_session(void) int wc_se050_lock(void) { -#ifdef SINGLE_THREADED - return 0; -#else + int ret = 0; + + /* Before the mutex is touched: in a fork() child it may be held by a + * thread that does not exist there. */ + if (se050_in_fork_child()) { + WOLFSSL_MSG("SE05x session belongs to the parent process"); + return BAD_STATE_E; + } +#ifndef SINGLE_THREADED /* Make sure the mutex has been initialized */ - int ret = se050_mutex_init(); + ret = se050_mutex_init(); if (ret == 0) { ret = wc_LockMutex(&se050Mutex); } - return ret; #endif + return ret; } void wc_se050_unlock(void) @@ -699,6 +772,9 @@ static int se050_close_internal(int preservePortName) cfg_se050_i2c_pi = NULL; gHostKeyStore = NULL; gKeyStore = NULL; +#ifdef SE050_FORK_CHECK + se050OwnerPid = 0; +#endif XMEMSET(&gBootCtx, 0, sizeof(gBootCtx)); wc_se050_unlock(); #if defined(SE050_RUNTIME_SCP03) && \ @@ -712,8 +788,37 @@ static int se050_close_internal(int preservePortName) return 0; } +#ifdef SE050_FORK_CHECK +/* wc_se050_close() in a fork() child: forget the session inherited from the + * parent without sending anything. ex_sss_session_close() would end the + * transport session the parent is still using. The child's copies of the + * transport fd and of the middleware's allocations are left as they are. */ +static int se050_drop_inherited_session(void) +{ + if (cfg_se050_i2c_pi != &gBootCtx.session) { + return WC_NO_ERR_TRACE(BAD_STATE_E); + } + cfg_se050_i2c_pi = NULL; + gHostKeyStore = NULL; + gKeyStore = NULL; + se050OwnerPid = 0; + /* May hold SCP03 session state. */ + ForceZero(&gBootCtx, sizeof(gBootCtx)); +#if defined(SE050_RUNTIME_SCP03) && \ + defined(WOLFSSL_SE050_SCP03_ROTATE) + se050_free_port_name(); +#endif + return se050_mutex_reset(); +} +#endif /* SE050_FORK_CHECK */ + int wc_se050_close(void) { +#ifdef SE050_FORK_CHECK + if (se050_in_fork_child()) { + return se050_drop_inherited_session(); + } +#endif return se050_close_internal(0); } #endif @@ -1187,7 +1292,10 @@ int se050_hash_copy(SE050_HASH_Context* src, SE050_HASH_Context* dst) dst->msg = (byte*)XMALLOC(src->used, dst->heap, DYNAMIC_TYPE_TMP_BUFFER); if (dst->msg == NULL) { - PRINTF("Tried to allocate %d bytes\n", dst->used); + WOLFSSL_MSG("se050_hash_copy: buffer allocation failed"); + /* Leave dst empty rather than describing a buffer it lacks. */ + dst->len = 0; + dst->used = 0; return MEMORY_E; } XMEMSET(dst->msg, 0, dst->used); @@ -1208,8 +1316,14 @@ int se050_hash_update(SE050_HASH_Context* se050Ctx, const byte* data, word32 len byte* tmp = NULL; word32 usedSz = 0; - if (se050Ctx == NULL || (len > 0 && data == NULL) || (len == 0) || - !WC_SAFE_SUM_WORD32(se050Ctx->used, len, usedSz)) { + if (se050Ctx == NULL || (len > 0 && data == NULL)) { + return BAD_FUNC_ARG; + } + /* A zero-length update is a valid no-op, as for the software hashes. */ + if (len == 0) { + return 0; + } + if (!WC_SAFE_SUM_WORD32(se050Ctx->used, len, usedSz)) { return BAD_FUNC_ARG; } @@ -1230,6 +1344,9 @@ int se050_hash_update(SE050_HASH_Context* se050Ctx, const byte* data, word32 len } XMEMSET(tmp, 0, usedSz); XMEMCPY(tmp, se050Ctx->msg, se050Ctx->used); + /* The buffered input may be secret (HMAC feeds key-derived pad + * blocks through here), so wipe it before releasing it. */ + ForceZero(se050Ctx->msg, se050Ctx->len); XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); se050Ctx->msg = tmp; } @@ -1248,10 +1365,19 @@ int se050_hash_final(SE050_HASH_Context* se050Ctx, byte* hash, size_t digestLen, int ret; sss_status_t status; sss_digest_t digest_ctx; - const byte* data = se050Ctx->msg; - int size = (se050Ctx->used) / SSS_BLOCK_SIZE; - int leftover = (se050Ctx->used) % SSS_BLOCK_SIZE; - const byte* blocks = data; + const byte* data; + int size; + int leftover; + const byte* blocks; + + if (se050Ctx == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + + data = se050Ctx->msg; + size = (int)(se050Ctx->used / SSS_BLOCK_SIZE); + leftover = (int)(se050Ctx->used % SSS_BLOCK_SIZE); + blocks = data; if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; @@ -1283,7 +1409,7 @@ int se050_hash_final(SE050_HASH_Context* se050Ctx, byte* hash, size_t digestLen, if (status == kStatus_SSS_Success) { /* reset state */ - XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + se050_hash_free(se050Ctx); ret = se050_hash_init(se050Ctx, se050Ctx->heap); } else { ret = WC_HW_E; @@ -1296,7 +1422,14 @@ int se050_hash_final(SE050_HASH_Context* se050Ctx, byte* hash, size_t digestLen, void se050_hash_free(SE050_HASH_Context* se050Ctx) { - XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (se050Ctx == NULL) { + return; + } + if (se050Ctx->msg != NULL) { + /* May hold secret input such as HMAC key-derived pad blocks. */ + ForceZero(se050Ctx->msg, se050Ctx->len); + XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); + } se050Ctx->msg = NULL; se050Ctx->len = 0; se050Ctx->used = 0; @@ -1306,15 +1439,71 @@ void se050_hash_free(SE050_HASH_Context* se050Ctx) #if defined(WOLFSSL_SE050_CRYPT) && !defined(NO_AES) +/* Set up a handle for the transient AES key object at keyId without sending + * any APDU. The port creates every AES key itself (se050_aes_set_key()), so + * it fills in the fields that sss_key_object_allocate_handle() would set + * (one CheckObjectExists APDU) or sss_key_object_get_handle() would read + * back (CheckObjectExists and ReadType, two APDUs). CipherOneShot and + * DeleteSecureObject only use the key ID, and the SE05x itself rejects an ID + * that does not exist or is not an AES key, so a bad ID still fails. */ +static sss_status_t se050_aes_key_object(sss_object_t* keyObject, + sss_key_store_t* keyStore, word32 keyId) +{ + sss_status_t status; + + status = sss_key_store_context_init(keyStore, cfg_se050_i2c_pi); + if (status == kStatus_SSS_Success) { + status = sss_key_store_allocate(keyStore, SE050_KEYSTOREID_AES); + } + if (status == kStatus_SSS_Success) { + /* Zeroes the object: transient, no curve. */ + status = sss_key_object_init(keyObject, keyStore); + } + if (status == kStatus_SSS_Success) { + keyObject->objectType = kSSS_KeyPart_Default; + keyObject->cipherType = kSSS_CipherType_AES; + keyObject->keyId = keyId; + } + + return status; +} + +/* How many IDs se050_aes_set_key() tries before it gives up when objects + * already on the SE050 hold the IDs the allocator returns. */ +#ifndef SE050_AES_KEYID_TRIES + #define SE050_AES_KEYID_TRIES 8 +#endif +#if SE050_AES_KEYID_TRIES < 1 + #error "SE050_AES_KEYID_TRIES must be at least 1" +#endif + +/* Delete an AES key object se050_aes_set_key() created: one + * DeleteSecureObject APDU. Call with the SE050 lock held. */ +static int se050_aes_erase_key_locked(word32 keyId) +{ + sss_status_t status; + sss_object_t keyObject; + sss_key_store_t host_keystore; + + status = se050_aes_key_object(&keyObject, &host_keystore, keyId); + if (status == kStatus_SSS_Success) { + status = sss_key_store_erase_key(&host_keystore, &keyObject); + sss_key_object_free(&keyObject); + } + + return (status == kStatus_SSS_Success) ? 0 : WC_HW_E; +} + int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, const byte* iv, int dir) { int ret = 0; - sss_status_t status; + sss_status_t status = kStatus_SSS_Fail; sss_object_t newKey; sss_key_store_t host_keystore; - word32 keyId; + word32 keyId = 0; int keyCreated = 0; + int tries; if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; @@ -1331,7 +1520,7 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, /* Free an existing key in the slot before storing a replacement. */ if (aes->keyIdSet != 0U) { - ret = se050_erase_object_locked(aes->keyId); + ret = se050_aes_erase_key_locked(aes->keyId); if (ret != 0) { wc_se050_unlock(); return ret; @@ -1340,26 +1529,28 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, aes->keyIdSet = 0; } - status = sss_key_store_context_init(&host_keystore, cfg_se050_i2c_pi); - if (status == kStatus_SSS_Success) { - status = sss_key_store_allocate(&host_keystore, SE050_KEYSTOREID_AES); - } - if (status == kStatus_SSS_Success) { - status = sss_key_object_init(&newKey, &host_keystore); + /* The ID allocator starts again in every process, so an object left by + * an earlier run or another session can already hold the ID it returns. + * Writing the key there would replace that object's key and the failure + * path below would delete it, so skip IDs that are in use. */ + for (tries = 0; tries < SE050_AES_KEYID_TRIES; tries++) { + keyId = se050_allocate_key(SE050_AES_KEY); + status = se050_require_new_object(keyId); + if (status == kStatus_SSS_Success) { + break; + } } if (status == kStatus_SSS_Success) { - keyId = se050_allocate_key(SE050_AES_KEY); - status = sss_key_object_allocate_handle(&newKey, keyId, - kSSS_KeyPart_Default, kSSS_CipherType_AES, keylen, - kKeyObject_Mode_Transient); + status = se050_aes_key_object(&newKey, &host_keystore, keyId); } if (status == kStatus_SSS_Success) { + /* From here on the object must be released on any failure. */ + keyCreated = 1; status = sss_key_store_set_key(&host_keystore, &newKey, key, keylen, keylen * 8, NULL, 0); } if (status == kStatus_SSS_Success) { - keyCreated = 1; aes->keyId = keyId; aes->keyIdSet = 1; ret = 0; @@ -1377,6 +1568,21 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, return ret; } +/* Largest input sent in one CipherOneShot command. It is a multiple of the + * AES block size and, with the TLV and SCP03 overhead, fits the SE05x + * command and response buffers. */ +#ifndef SE050_AES_ONESHOT_MAX + #define SE050_AES_ONESHOT_MAX 448 +#endif +#if (SE050_AES_ONESHOT_MAX < 16) || ((SE050_AES_ONESHOT_MAX % 16) != 0) + #error "SE050_AES_ONESHOT_MAX must be a non-zero multiple of 16" +#endif + +/* Each call is a stateless CipherOneShot. A multi-step cipher context cannot + * be used here: the SE05x keeps one crypto object per cipher mode for the + * whole session, so every Aes using that mode would share its key, direction + * and chaining state. For CBC the chaining value is kept in aes->reg, as in + * the software implementation. */ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, sss_algorithm_t algorithm) { @@ -1384,7 +1590,26 @@ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, sss_status_t status; sss_object_t keyObject; sss_key_store_t host_keystore; + sss_symmetric_t ctx; + int ctxInit = 0; + int isCbc = (algorithm == kAlgorithm_SSS_AES_CBC); + byte nextIv[WC_AES_BLOCK_SIZE]; + + if (aes == NULL || + (dir != AES_ENCRYPTION && dir != AES_DECRYPTION) || + (algorithm != kAlgorithm_SSS_AES_ECB && !isCbc)) { + return BAD_FUNC_ARG; + } + /* The SE05x NOPAD modes only take whole blocks. Like the software path, + * any trailing partial block is left unprocessed. */ + sz -= sz % WC_AES_BLOCK_SIZE; + if (sz == 0) { + return 0; + } + if (in == NULL || out == NULL) { + return BAD_FUNC_ARG; + } if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; } @@ -1392,48 +1617,61 @@ int se050_aes_crypt(Aes* aes, const byte* in, byte* out, word32 sz, int dir, return BAD_FUNC_ARG; } + XMEMSET(&ctx, 0, sizeof(ctx)); + XMEMSET(nextIv, 0, sizeof(nextIv)); + if (wc_se050_lock() != 0) { return BAD_MUTEX_E; } - status = sss_key_store_context_init(&host_keystore, cfg_se050_i2c_pi); - if (status == kStatus_SSS_Success) { - status = sss_key_store_allocate(&host_keystore, SE050_KEYSTOREID_AES); - } - if (status == kStatus_SSS_Success) { - status = sss_key_object_init(&keyObject, &host_keystore); - } + /* No lookup APDUs: each chunk below is the only command sent. */ + status = se050_aes_key_object(&keyObject, &host_keystore, aes->keyId); if (status == kStatus_SSS_Success) { - status = sss_key_object_get_handle(&keyObject, aes->keyId); + status = sss_symmetric_context_init(&ctx, cfg_se050_i2c_pi, + &keyObject, algorithm, + (dir == AES_DECRYPTION) ? kMode_SSS_Decrypt : kMode_SSS_Encrypt); + if (status == kStatus_SSS_Success) { + ctxInit = 1; + } } - /* The first call to this function needs an initialization call, - * subsequent calls just need to call update */ - if (status == kStatus_SSS_Success && aes->ctxInitDone == 0) { - sss_mode_t mode; + while (status == kStatus_SSS_Success && sz > 0) { + word32 chunk = (sz > SE050_AES_ONESHOT_MAX) ? SE050_AES_ONESHOT_MAX + : sz; - XMEMSET(&mode, 0, sizeof(mode)); - if (dir == AES_DECRYPTION) - mode = kMode_SSS_Decrypt; - else if (dir == AES_ENCRYPTION) - mode = kMode_SSS_Encrypt; - - if (status == kStatus_SSS_Success) { - status = sss_symmetric_context_init(&aes->aes_ctx, - cfg_se050_i2c_pi, &keyObject, algorithm, mode); + if (isCbc && dir == AES_DECRYPTION) { + /* Save the next chaining value before an in-place decrypt + * overwrites it. */ + XMEMCPY(nextIv, in + chunk - WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); } - if (status == kStatus_SSS_Success) { - aes->ctxInitDone = 1; - status = sss_cipher_init(&aes->aes_ctx, (uint8_t*)aes->reg, - sizeof(aes->reg)); + + status = sss_cipher_one_go(&ctx, + isCbc ? (uint8_t*)aes->reg : NULL, + isCbc ? (size_t)WC_AES_BLOCK_SIZE : 0, + in, out, (size_t)chunk); + + if (status == kStatus_SSS_Success && isCbc) { + if (dir == AES_DECRYPTION) { + XMEMCPY(aes->reg, nextIv, WC_AES_BLOCK_SIZE); + } + else { + XMEMCPY(aes->reg, out + chunk - WC_AES_BLOCK_SIZE, + WC_AES_BLOCK_SIZE); + } } - } - if (status == kStatus_SSS_Success) { - size_t outSz = (size_t)sz; - status = sss_cipher_update(&aes->aes_ctx, in, sz, out, &outSz); + + in += chunk; + out += chunk; + sz -= chunk; } - ret = (status == kStatus_SSS_Success) ? 0 : WC_HW_E; + if (ctxInit) { + sss_symmetric_context_free(&ctx); + } + if (status != kStatus_SSS_Success) { + ret = WC_HW_E; + } wc_se050_unlock(); @@ -1446,15 +1684,31 @@ void se050_aes_free(Aes* aes) return; } - if (aes->ctxInitDone) { - sss_symmetric_context_free(&aes->aes_ctx); + if (cfg_se050_i2c_pi == NULL) { + /* No session to release the SE050 object through. */ + aes->keyId = 0; + aes->keyIdSet = 0; + return; + } - /* sets back to zero to indicate that a free has been called */ - aes->ctxInitDone = 0; + /* Erasing the key talks to the SE050 and cannot be done safely without + * the lock; wc_AesFree() wipes the Aes next either way. */ + if (wc_se050_lock() != 0) { + WOLFSSL_MSG("SE050 lock failed, AES key object not erased"); + return; } - aes->keyId = 0; - aes->keyIdSet = 0; + /* Erase the transient key object se050_aes_set_key() created, otherwise + * every set key / free cycle leaves an object behind on the SE050. */ + if (aes->keyIdSet != 0U) { + if (se050_aes_erase_key_locked(aes->keyId) != 0) { + WOLFSSL_MSG("Failed to erase SE050 AES key object"); + } + aes->keyId = 0; + aes->keyIdSet = 0; + } + + wc_se050_unlock(); } #endif /* WOLFSSL_SE050_CRYPT && !NO_AES */ @@ -3038,19 +3292,22 @@ static sss_algorithm_t se050_get_rsa_signature_type(int padType, } static sss_algorithm_t se050_get_rsa_encrypt_type(int padType, - enum wc_HashType hash) + enum wc_HashType hash, int mgf) { sss_algorithm_t alg = kAlgorithm_None; - (void)hash; switch (padType) { case WC_RSA_PKCSV15_PAD: alg = kAlgorithm_SSS_RSAES_PKCS1_V1_5; break; case WC_RSA_OAEP_PAD: - /* lower level Se05x API translation maps OAEP-SHA1 alg type to - * kSE05x_RSAEncryptionAlgo_PKCS1_OAEP (generic) */ - alg = kAlgorithm_SSS_RSAES_PKCS1_OAEP_SHA1; + /* The SE05x applet implements OAEP with SHA-1 and MGF1-SHA1 + * only (the SDK maps the other OAEP algorithms to "not + * available"). Refuse anything else rather than silently + * encrypting or decrypting with different parameters. */ + if ((hash == WC_HASH_TYPE_SHA) && (mgf == WC_MGF1SHA1)) { + alg = kAlgorithm_SSS_RSAES_PKCS1_OAEP_SHA1; + } break; case WC_RSA_NO_PAD: alg = kAlgorithm_SSS_RSASSA_NO_PADDING; @@ -3531,8 +3788,8 @@ int se050_rsa_verify(const byte* in, word32 inLen, byte* out, word32 outLen, * WC_RSA_NO_PAD, WC_RSA_PSS_PAD * hash type of hash algorithm, found in wolfssl/wolfcrypt/hash.h * mgf type of mask generation function to use - * label optional label, not supported by SE050, must be NULL - * labelSz size of label, not supported by SE050, must be 0 + * label optional label, not supported by SE050 for OAEP + * labelSz size of label, must be 0 for OAEP * keySz size of RSA key, bytes * * Returns size of encrypted data on success, negative on error. @@ -3555,10 +3812,9 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, byte* derBuf = NULL; int derSz = 0; - /* SE050 does not support optional label */ + /* The SE050 OAEP implementation has no label input: only the empty + * label can be honored. */ (void)label; - (void)labelSz; - (void)mgf; #ifdef SE050_DEBUG printf("se050_rsa_public_encrypt: key %p, in %p (%d), out %p (%d), " @@ -3569,6 +3825,10 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, rsa_type != RSA_PUBLIC_ENCRYPT || pad_value != RSA_BLOCK_TYPE_2) { return BAD_FUNC_ARG; } + if ((pad_type == WC_RSA_OAEP_PAD) && (labelSz != 0)) { + WOLFSSL_MSG("SE050 RSA-OAEP does not support a label"); + return BAD_FUNC_ARG; + } if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; @@ -3586,7 +3846,7 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, return BAD_MUTEX_E; } - algorithm = se050_get_rsa_encrypt_type(pad_type, hash); + algorithm = se050_get_rsa_encrypt_type(pad_type, hash, mgf); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); wc_se050_unlock(); @@ -3707,8 +3967,8 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, * WC_RSA_NO_PAD, WC_RSA_PSS_PAD * hash type of hash algorithm, found in wolfssl/wolfcrypt/hash.h * mgf type of mask generation function to use - * label optional label, not supported by SE050, must be NULL - * labelSz size of label, not supported by SE050, must be 0 + * label optional label, not supported by SE050 for OAEP + * labelSz size of label, must be 0 for OAEP * * Returns size of decrypted data on success, negative on error. */ @@ -3732,10 +3992,9 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, int derSz = 0; int derBufSz = 0; - /* SE050 does not support optional label */ + /* The SE050 OAEP implementation has no label input: only the empty + * label can be honored. */ (void)label; - (void)labelSz; - (void)mgf; #ifdef SE050_DEBUG printf("se050_rsa_public_decrypt: key %p, in %p (%d), out %p (%d), " @@ -3746,6 +4005,10 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, rsa_type != RSA_PRIVATE_DECRYPT || pad_value != RSA_BLOCK_TYPE_2) { return BAD_FUNC_ARG; } + if ((pad_type == WC_RSA_OAEP_PAD) && (labelSz != 0)) { + WOLFSSL_MSG("SE050 RSA-OAEP does not support a label"); + return BAD_FUNC_ARG; + } if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; @@ -3763,7 +4026,7 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, return BAD_MUTEX_E; } - algorithm = se050_get_rsa_encrypt_type(pad_type, hash); + algorithm = se050_get_rsa_encrypt_type(pad_type, hash, mgf); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); wc_se050_unlock(); @@ -5093,6 +5356,105 @@ int se050_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, #ifdef HAVE_ED25519 +/* The SE05x keeps each 32-byte half (R and S) of an Ed25519 signature in the + * reverse byte order of RFC 8032; Plug&Trust swaps them in + * sss_se05x_asymmetric_sign() and _verify(). */ +static void se050_ed25519_reverse_sig(byte* sig) +{ + word32 half; + word32 i; + + for (half = 0; half < ED25519_SIG_SIZE; half += ED25519_SIG_SIZE / 2) { + for (i = 0; i < ED25519_SIG_SIZE / 4; i++) { + byte t = sig[half + i]; + sig[half + i] = sig[half + (ED25519_SIG_SIZE / 2) - 1 - i]; + sig[half + (ED25519_SIG_SIZE / 2) - 1 - i] = t; + } + } +} + +/* EdDSASign / EdDSAVerify of an empty message with Ed25519 key object keyId. + * Plug&Trust's Se05x_API_EdDSASign() and Se05x_API_EdDSAVerify() leave the + * input TLV (TAG_3) out of the command when the input length is 0, and the + * applet rejects that with SW 0x6A80 (seen on an SE051, applet 7.2). With + * TAG_3 present at length 0 it signs and verifies the empty message, so + * build that command here. Verifies verifySig when it is not NULL, else + * writes the signature to signOut; both are ED25519_SIG_SIZE bytes in RFC + * 8032 order. Called only while the SE050 mutex is held. */ +static sss_status_t se050_ed25519_empty_msg(word32 keyId, + const byte* verifySig, byte* signOut) +{ + tlvHeader_t hdr = {{kSE05x_CLA, kSE05x_INS_CRYPTO, kSE05x_P1_SIGNATURE, + kSE05x_P2_SIGN}}; + pSe05xSession_t session = wc_se050_get_se05x_session(); + /* TAG_1 key ID, TAG_2 algorithm, empty TAG_3, TAG_5 signature, plus 16 + * bytes because on an SCP03 session Plug&Trust pads the command data in + * place to a multiple of the 16-byte AES block before encrypting it. */ + uint8_t cmd[6 + 3 + 2 + 2 + ED25519_SIG_SIZE + 16]; + uint8_t* pCmd = cmd; + size_t cmdLen = 0; + uint8_t rsp[2 * ED25519_SIG_SIZE]; + size_t rspLen = sizeof(rsp); + size_t rspIdx = 0; + byte seSig[ED25519_SIG_SIZE]; + size_t seSigLen = sizeof(seSig); + SE05x_Result_t result = kSE05x_Result_NA; + int verify = (verifySig != NULL); + int tlvRet; + + if ((session == NULL) || (!verify && (signOut == NULL))) { + return kStatus_SSS_Fail; + } + if (verify) { + hdr.hdr[3] = kSE05x_P2_VERIFY; + XMEMCPY(seSig, verifySig, ED25519_SIG_SIZE); + se050_ed25519_reverse_sig(seSig); + } + + tlvRet = tlvSet_U32(&pCmd, &cmdLen, kSE05x_TAG_1, keyId); + if (tlvRet == 0) { + tlvRet = tlvSet_U8(&pCmd, &cmdLen, kSE05x_TAG_2, + (uint8_t)kSE05x_EDSignatureAlgo_ED25519PURE_SHA_512); + } + if (tlvRet == 0) { + tlvRet = tlvSet_u8buf(&pCmd, &cmdLen, kSE05x_TAG_3, seSig, 0); + } + if ((tlvRet == 0) && verify) { + tlvRet = tlvSet_u8buf(&pCmd, &cmdLen, kSE05x_TAG_5, seSig, + ED25519_SIG_SIZE); + } + if ((tlvRet != 0) || + (DoAPDUTxRx_s_Case4(session, &hdr, cmd, cmdLen, rsp, &rspLen) != + SM_OK)) { + return kStatus_SSS_Fail; + } + + if (verify) { + tlvRet = tlvGet_Result(rsp, &rspIdx, rspLen, kSE05x_TAG_1, &result); + if (result != kSE05x_Result_SUCCESS) { + tlvRet = 1; + } + } + else { + tlvRet = tlvGet_u8buf(rsp, &rspIdx, rspLen, kSE05x_TAG_1, seSig, + &seSigLen); + if (seSigLen != ED25519_SIG_SIZE) { + tlvRet = 1; + } + } + /* the response must end with SW 0x9000 right after the TLV */ + if ((tlvRet != 0) || (rspIdx + 2 != rspLen) || + ((((word32)rsp[rspIdx] << 8) | rsp[rspIdx + 1]) != SM_OK)) { + return kStatus_SSS_Fail; + } + + if (!verify) { + se050_ed25519_reverse_sig(seSig); + XMEMCPY(signOut, seSig, ED25519_SIG_SIZE); + } + return kStatus_SSS_Success; +} + int se050_ed25519_create_key(ed25519_key* key) { int ret = 0; @@ -5222,9 +5584,6 @@ int se050_ed25519_sign_msg(const byte* in, word32 inLen, byte* out, "keyId %ld\n", key, in, inLen, out, *outLen, key->keyId); #endif - if (in == NULL) - in = (const byte *)""; - if (cfg_se050_i2c_pi == NULL) { return WC_HW_E; } @@ -5280,7 +5639,18 @@ int se050_ed25519_sign_msg(const byte* in, word32 inLen, byte* out, status = sss_key_object_get_handle(&newKey, keyId); } } - if (status == kStatus_SSS_Success) { + if ((status == kStatus_SSS_Success) && (inLen == 0)) { + if (*outLen < ED25519_SIG_SIZE) { + status = kStatus_SSS_Fail; + } + else { + status = se050_ed25519_empty_msg(keyId, NULL, out); + if (status == kStatus_SSS_Success) { + *outLen = ED25519_SIG_SIZE; + } + } + } + else if (status == kStatus_SSS_Success) { status = sss_asymmetric_context_init(&ctx_asymm, cfg_se050_i2c_pi, &newKey, kAlgorithm_SSS_SHA512, kMode_SSS_Sign); if (status == kStatus_SSS_Success) { @@ -5337,9 +5707,6 @@ int se050_ed25519_verify_msg(const byte* signature, word32 signatureLen, key, signature, signatureLen, msg, msgLen); #endif - if (msg == NULL) - msg = (const byte *)""; - *res = 0; if (cfg_se050_i2c_pi == NULL) { @@ -5398,7 +5765,15 @@ int se050_ed25519_verify_msg(const byte* signature, word32 signatureLen, } } - if (status == kStatus_SSS_Success) { + if ((status == kStatus_SSS_Success) && (msgLen == 0)) { + if (signatureLen != ED25519_SIG_SIZE) { + status = kStatus_SSS_Fail; + } + else { + status = se050_ed25519_empty_msg(keyId, signature, NULL); + } + } + else if (status == kStatus_SSS_Success) { status = sss_asymmetric_context_init(&ctx_asymm, cfg_se050_i2c_pi, &newKey, kAlgorithm_SSS_SHA512, kMode_SSS_Verify); if (status == kStatus_SSS_Success) { diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index 463ee25e363..c28f73c82f8 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -1013,6 +1013,30 @@ static WARN_UNUSED_RESULT int wc_RNG_HealthTest_SHA512_ex_internal( * lives below in its own #ifdef WOLFSSL_DRBG_SHA512 section. */ #ifndef NO_SHA256 +/* Initialize one of the DRBG's SHA-256 objects. */ +static WARN_UNUSED_RESULT int Hash_DRBG_InitSha256(DRBG_internal* drbg, + wc_Sha256* sha) +{ + int ret; + +#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) + ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); +#else + (void)drbg; + ret = wc_InitSha256(sha); +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Hash on the host, not the SE05x. On the SE05x, V, C and the seed + * material would cross the bus (in clear without SCP03), every generate + * would cost APDUs, and a fork() child could not reseed: the port + * refuses it the parent's session. */ + if (ret == 0) { + sha->useSWCrypt = 1; + } +#endif + return ret; +} + /* Hash Derivation Function */ /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ static WARN_UNUSED_RESULT int Hash_df(DRBG_internal* drbg, byte* out, @@ -1072,11 +1096,7 @@ static WARN_UNUSED_RESULT int Hash_df(DRBG_internal* drbg, byte* out, ctr = 1; for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); if (ret != 0) break; #endif @@ -1953,11 +1973,7 @@ static WARN_UNUSED_RESULT int Hash_gen(DRBG_internal* drbg, byte* out, #endif for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); if (ret == 0) #endif ret = wc_Sha256Update(sha, data, DRBG_SEED_LEN); @@ -2115,11 +2131,7 @@ static WARN_UNUSED_RESULT int Hash_DRBG_Generate(DRBG_internal* drbg, DYNAMIC_TYPE_TMP_BUFFER, ret = MEMORY_E); if (ret == 0) { thisV = shadowV; - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); } if (ret != 0) { @@ -2182,11 +2194,7 @@ static WARN_UNUSED_RESULT int Hash_DRBG_Generate(DRBG_internal* drbg, ret = Hash_gen(drbg, out, outSz, thisV); if (ret == DRBG_SUCCESS) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(sha); - #endif + ret = Hash_DRBG_InitSha256(drbg, sha); if (ret == 0) #endif ret = wc_Sha256Update(sha, &type, sizeof(type)); @@ -2312,11 +2320,7 @@ static WARN_UNUSED_RESULT int Hash_DRBG_Instantiate(DRBG_internal* drbg, #endif #ifdef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha256_ex(&drbg->sha256, drbg->heap, drbg->devId); - #else - ret = wc_InitSha256(&drbg->sha256); - #endif + ret = Hash_DRBG_InitSha256(drbg, &drbg->sha256); if (ret != 0) return ret; #endif @@ -2365,6 +2369,27 @@ static int Hash_DRBG_Uninstantiate(DRBG_internal* drbg) #define OUTPUT_BLOCK_LEN_SHA512 (WC_SHA512_DIGEST_SIZE) /* 64 bytes */ +/* Initialize one of the SHA-512 DRBG's SHA-512 objects. */ +static WARN_UNUSED_RESULT int Hash512_DRBG_InitSha512( + DRBG_SHA512_internal* drbg, wc_Sha512* sha) +{ + int ret; + +#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) + ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); +#else + (void)drbg; + ret = wc_InitSha512(sha); +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Hash on the host, as Hash_DRBG_InitSha256() does. */ + if (ret == 0) { + sha->useSWCrypt = 1; + } +#endif + return ret; +} + /* Hash Derivation Function using SHA-512 */ /* Returns: DRBG_SUCCESS or DRBG_FAILURE */ static WARN_UNUSED_RESULT int Hash512_df(DRBG_SHA512_internal* drbg, byte* out, @@ -2431,11 +2456,7 @@ static WARN_UNUSED_RESULT int Hash512_df(DRBG_SHA512_internal* drbg, byte* out, ctr = 1; for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); if (ret != 0) break; #endif @@ -2624,11 +2645,7 @@ static WARN_UNUSED_RESULT int Hash512_gen(DRBG_SHA512_internal* drbg, #endif for (i = 0; i < len; i++) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); if (ret == 0) #endif ret = wc_Sha512Update(sha, data, DRBG_SHA512_SEED_LEN); @@ -2740,11 +2757,7 @@ static WARN_UNUSED_RESULT int Hash512_DRBG_Generate(DRBG_SHA512_internal* drbg, DYNAMIC_TYPE_TMP_BUFFER, ret = MEMORY_E); if (ret == 0) { thisV = shadowV; - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); } if (ret != 0) { @@ -2808,11 +2821,7 @@ static WARN_UNUSED_RESULT int Hash512_DRBG_Generate(DRBG_SHA512_internal* drbg, ret = Hash512_gen(drbg, out, outSz, thisV); if (ret == DRBG_SUCCESS) { #ifndef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(sha, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(sha); - #endif + ret = Hash512_DRBG_InitSha512(drbg, sha); if (ret == 0) #endif ret = wc_Sha512Update(sha, &type, sizeof(type)); @@ -2921,11 +2930,7 @@ static WARN_UNUSED_RESULT int Hash512_DRBG_Instantiate( #endif #ifdef WOLFSSL_SMALL_STACK_CACHE - #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB) - ret = wc_InitSha512_ex(&drbg->sha512, drbg->heap, drbg->devId); - #else - ret = wc_InitSha512(&drbg->sha512); - #endif + ret = Hash512_DRBG_InitSha512(drbg, &drbg->sha512); if (ret != 0) return ret; #endif diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index 9456e98efdc..bbbcb898094 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -3801,6 +3801,128 @@ static int RsaModulusBits(const RsaKey* key) } #endif +#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) && \ + !defined(WC_NO_RSA_OAEP) && !defined(WOLFSSL_NO_RSA_SW_PAD) +/* The SE050 implements RSAES-OAEP with SHA-1, MGF1-SHA1 and an empty label + * only. True when the requested OAEP parameters are exactly those. */ +#define SE050_RSA_OAEP_NATIVE(hash, mgf, labelSz) \ + (((hash) == WC_HASH_TYPE_SHA) && ((mgf) == WC_MGF1SHA1) && \ + ((labelSz) == 0)) + +#ifndef WOLFSSL_RSA_VERIFY_ONLY +/* RSAES-OAEP encryption with parameters the SE050 cannot apply itself: encode + * the message here and have the SE050 perform only the raw RSA public key + * operation, so the requested hash, MGF and label are used as asked. */ +static int Se050RsaOaepEncrypt(const byte* in, word32 inLen, byte* out, + word32 outLen, RsaKey* key, int sz, + enum wc_HashType hash, int mgf, byte* label, + word32 labelSz, WC_RNG* rng) +{ + int ret; + + /* As for decryption: the OAEP encoding works in RSA_MAX_SIZE buffers. */ + if (sz > RSA_MAX_SIZE / 8) { + return WC_KEY_SIZE_E; + } + + ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, RSA_BLOCK_TYPE_2, rng, + WC_RSA_OAEP_PAD, hash, mgf, label, labelSz, 0, + RsaModulusBits(key), key->heap); + if (ret == 0) { + /* The whole encoded message goes to the SE050 before the ciphertext + * comes back, so out can carry both. */ + ret = se050_rsa_public_encrypt(out, (word32)sz, out, outLen, key, + RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, + WC_RSA_NO_PAD, WC_HASH_TYPE_NONE, + WC_MGF1NONE, NULL, 0, sz); + } + if (ret < 0) { + /* SP 800-56Br2 7.2.2.3: destroy EM on an error exit. */ + ForceZero(out, (word32)sz); + } + + return ret; +} +#endif /* !WOLFSSL_RSA_VERIFY_ONLY */ + +#ifndef WOLFSSL_RSA_PUBLIC_ONLY +/* RSAES-OAEP decryption with parameters the SE050 cannot apply itself: the + * SE050 performs only the raw RSA private key operation and the encoded + * message is checked and decoded here. */ +static int Se050RsaOaepDecrypt(const byte* in, word32 inLen, byte* out, + word32 outLen, byte** outPtr, RsaKey* key, + enum wc_HashType hash, int mgf, byte* label, + word32 labelSz) +{ + int ret; + int sz; + word32 emSz; + byte* em; + byte* msg = NULL; + + sz = wc_RsaEncryptSize(key); + if (sz <= 0) { + return BAD_FUNC_ARG; + } + /* The SE050 can hold a key larger than this build's software limit, and + * the OAEP decoding below works in buffers sized for RSA_MAX_SIZE. */ + if (sz > RSA_MAX_SIZE / 8) { + return WC_KEY_SIZE_E; + } + emSz = (word32)sz; + + em = (byte*)XMALLOC(emSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (em == NULL) { + return MEMORY_E; + } + + ret = se050_rsa_private_decrypt(in, inLen, em, emSz, key, + RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, + WC_RSA_NO_PAD, WC_HASH_TYPE_NONE, + WC_MGF1NONE, NULL, 0); + if (ret > (int)emSz) { + ret = WC_HW_E; + } + else if (ret >= 0) { + /* The SE050 returns a raw RSA result at the full modulus length. If a + * shorter one ever came back, right-align it into the encoded message + * block; its length is already visible in the APDU response. */ + if ((word32)ret < emSz) { + XMEMMOVE(em + (emSz - (word32)ret), em, (size_t)ret); + XMEMSET(em, 0, emSz - (word32)ret); + } + ret = wc_RsaUnPad_ex(em, emSz, &msg, RSA_BLOCK_TYPE_2, + WC_RSA_OAEP_PAD, hash, mgf, label, labelSz, 0, + RsaModulusBits(key), key->heap); + if (ret >= 0) { + /* As on the software path: OAEP decoding reports an invalid + * encoding as a zero-length message, so that is an error unless + * empty messages are allowed, and the message must fit in out. */ + ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret, + WC_NO_ERR_TRACE(RSA_BUFFER_E)); + #ifndef WOLFSSL_RSA_DECRYPT_TO_0_LEN + ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, + WC_NO_ERR_TRACE(RSA_BUFFER_E)); + #endif + } + } + if (ret >= 0) { + if (ret > 0) { + XMEMCPY(out, msg, (size_t)ret); + } + if (outPtr != NULL) { + *outPtr = out; + } + } + + ForceZero(em, emSz); + XFREE(em, key->heap, DYNAMIC_TYPE_TMP_BUFFER); + + return ret; +} +#endif /* !WOLFSSL_RSA_PUBLIC_ONLY */ +#endif /* WOLFSSL_SE050 && !WC_NO_RSA_OAEP && !WOLFSSL_NO_RSA_SW_PAD */ + #ifndef WOLFSSL_RSA_VERIFY_ONLY /* Internal Wrappers */ /* Gives the option of choosing padding type @@ -3914,6 +4036,13 @@ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, #endif { if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) { + #if !defined(WC_NO_RSA_OAEP) && !defined(WOLFSSL_NO_RSA_SW_PAD) + if ((pad_type == WC_RSA_OAEP_PAD) && + !SE050_RSA_OAEP_NATIVE(hash, mgf, labelSz)) { + return Se050RsaOaepEncrypt(in, inLen, out, outLen, key, sz, + hash, mgf, label, labelSz, rng); + } + #endif return se050_rsa_public_encrypt(in, inLen, out, outLen, key, rsa_type, pad_value, pad_type, hash, mgf, label, labelSz, sz); @@ -4123,6 +4252,14 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out, #endif { if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) { + #if !defined(WC_NO_RSA_OAEP) && !defined(WOLFSSL_NO_RSA_SW_PAD) && \ + !defined(WOLFSSL_RSA_PUBLIC_ONLY) + if ((pad_type == WC_RSA_OAEP_PAD) && + !SE050_RSA_OAEP_NATIVE(hash, mgf, labelSz)) { + return Se050RsaOaepDecrypt(in, inLen, out, outLen, outPtr, + key, hash, mgf, label, labelSz); + } + #endif ret = se050_rsa_private_decrypt(in, inLen, out, outLen, key, rsa_type, pad_value, pad_type, hash, mgf, label, labelSz); diff --git a/wolfcrypt/src/sha.c b/wolfcrypt/src/sha.c index 4f8b0aa2cd4..7536a94e3c6 100644 --- a/wolfcrypt/src/sha.c +++ b/wolfcrypt/src/sha.c @@ -403,32 +403,56 @@ if (sha == NULL) { return BAD_FUNC_ARG; } - WC_SILABS_CLEAR_HASH_CTX(sha); + /* Only se050Ctx hashes, but Free and Copy read the other fields. */ + XMEMSET(sha, 0, sizeof(*sha)); + sha->heap = heap; + #ifdef WOLF_CRYPTO_CB + sha->devId = devId; + #else (void)devId; + #endif return se050_hash_init(&sha->se050Ctx, heap); } int wc_ShaUpdate(wc_Sha* sha, const byte* data, word32 len) { + if (sha == NULL) { + return BAD_FUNC_ARG; + } return se050_hash_update(&sha->se050Ctx, data, len); - } int wc_ShaFinal(wc_Sha* sha, byte* hash) { int ret = 0; + if (sha == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } ret = se050_hash_final(&sha->se050Ctx, hash, WC_SHA_DIGEST_SIZE, kAlgorithm_SSS_SHA1); return ret; } int wc_ShaFinalRaw(wc_Sha* sha, byte* hash) { - int ret = 0; - ret = se050_hash_final(&sha->se050Ctx, hash, WC_SHA_DIGEST_SIZE, - kAlgorithm_SSS_SHA1); - return ret; + if (sha == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + /* The SE05x hash only buffers the message: no state to read out. + * (settings.h defines WOLFSSL_NO_HASH_RAW, so nothing in wolfSSL + * calls this.) */ + return NOT_COMPILED_IN; } +#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL) + int wc_ShaTransform(wc_Sha* sha, const unsigned char* data) + { + if (sha == NULL || data == NULL) { + return BAD_FUNC_ARG; + } + /* The SE05x hash keeps no digest state to transform. */ + return NOT_COMPILED_IN; + } +#endif #elif defined(WOLFSSL_HAVE_PSA) && !defined(WOLFSSL_PSA_NO_HASH) /* implemented in wolfcrypt/src/port/psa/psa_hash.c */ diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 3811aa4b45d..cdc1073ee65 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -170,6 +170,18 @@ on the specific device platform. #endif #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) #include + + /* The software implementation stays compiled in: wc_Sha256Update() and + * wc_Sha256Final() send an object to the SE05x unless its useSWCrypt is + * set. Each software wc_InitSha256_ex() below starts the object on the + * SE05x with this. Call it AFTER the NULL check. */ + #define SHA256_SE050_INIT(sha256, heap) \ + do { \ + (sha256)->useSWCrypt = 0; \ + (void)se050_hash_init(&(sha256)->se050Ctx, (heap)); \ + } while (0) +#else + #define SHA256_SE050_INIT(sha256, heap) WC_DO_NOTHING #endif #if FIPS_VERSION3_GE(6,0,0) @@ -292,7 +304,7 @@ on the specific device platform. defined(NO_WOLFSSL_RENESAS_TSIP_CRYPT_HASH)) && \ !defined(PSOC6_HASH_SHA2) && !defined(WOLFSSL_IMXRT_DCP) && !defined(WOLFSSL_SILABS_SE_ACCEL) && \ !defined(WOLFSSL_NXP_HASHCRYPT_SHA) && \ - !defined(WOLFSSL_KCAPI_HASH) && !defined(WOLFSSL_SE050_HASH) && \ + !defined(WOLFSSL_KCAPI_HASH) && \ ((!defined(WOLFSSL_RENESAS_SCEPROTECT) && \ !defined(WOLFSSL_RENESAS_RSIP)) \ || defined(NO_WOLFSSL_RENESAS_FSPSM_HASH)) && \ @@ -375,8 +387,17 @@ int wc_Sha256Reset(wc_Sha256* sha256) { { void* heap = sha256->heap; int devId = sha256->devId; + int ret; + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Init_ex starts the object on the SE05x: keep where it hashes. */ + byte useSWCrypt = sha256->useSWCrypt; + #endif wc_Sha256Free(sha256); - return wc_InitSha256_ex(sha256, heap, devId); + ret = wc_InitSha256_ex(sha256, heap, devId); + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + sha256->useSWCrypt = useSWCrypt; + #endif + return ret; } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256) && \ @@ -387,6 +408,10 @@ int wc_Sha256Reset(wc_Sha256* sha256) { if (ret != 0) return ret; } +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Drop the message an SE05x object buffered; useSWCrypt stays. */ + se050_hash_free(&sha256->se050Ctx); #endif return InitSha256(sha256); } @@ -928,6 +953,7 @@ wc_static_assert(sizeof(Sha256TScratch) == WC_SHA256_TSCRATCH_SIZE); #endif WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); sha256->heap = heap; #ifdef WOLF_CRYPTO_CB sha256->devId = devId; @@ -1131,48 +1157,6 @@ wc_static_assert(sizeof(Sha256TScratch) == WC_SHA256_TSCRATCH_SIZE); !defined(WOLFSSL_QNX_CAAM) /* functions defined in wolfcrypt/src/port/caam/caam_sha256.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - - int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) - { - if (sha256 == NULL) { - return BAD_FUNC_ARG; - } - #ifdef WC_CTX_IS_ALIGNED - if (!WC_CTX_IS_ALIGNED(sha256, wc_Sha256)) { - return BAD_ALIGN_E; - } - #endif - WC_SILABS_CLEAR_HASH_CTX(sha256); - (void)devId; - - return se050_hash_init(&sha256->se050Ctx, heap); - } - - int wc_Sha256Update(wc_Sha256* sha256, const byte* data, word32 len) - { - if (sha256 == NULL) { - return BAD_FUNC_ARG; - } - if (data == NULL && len == 0) { - /* valid, but do nothing */ - return 0; - } - if (data == NULL) { - return BAD_FUNC_ARG; - } - - return se050_hash_update(&sha256->se050Ctx, data, len); - } - - int wc_Sha256Final(wc_Sha256* sha256, byte* hash) - { - int ret = 0; - ret = se050_hash_final(&sha256->se050Ctx, hash, WC_SHA256_DIGEST_SIZE, - kAlgorithm_SSS_SHA256); - return ret; - } - #elif defined(WOLFSSL_AFALG_HASH) /* implemented in wolfcrypt/src/port/af_alg/afalg_hash.c */ @@ -1387,6 +1371,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1552,6 +1537,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1704,6 +1690,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1770,6 +1757,7 @@ int wc_InitSha256_ex(wc_Sha256* sha256, void* heap, int devId) if (sha256 == NULL) return BAD_FUNC_ARG; WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -1849,6 +1837,7 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_ALIGN_E; #endif WC_SILABS_CLEAR_HASH_CTX(sha256); + SHA256_SE050_INIT(sha256, heap); ret = InitSha256(sha256); if (ret != 0) return ret; @@ -2299,6 +2288,11 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if (!sha256->useSWCrypt) { + return se050_hash_update(&sha256->se050Ctx, data, len); + } + #endif #ifdef WOLF_CRYPTO_CB #ifndef WOLF_CRYPTO_CB_FIND if (sha256->devId != INVALID_DEVID) @@ -2524,6 +2518,12 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, if (sha256 == NULL || hash == NULL) { return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE05x hash only buffers the message: no state to read out. */ + if (!sha256->useSWCrypt) { + return NOT_COMPILED_IN; + } + #endif #if defined(WOLFSSL_CHECK_MEM_ZERO) && defined(LITTLE_ENDIAN_ORDER) && \ !defined(WOLFSSL_WIDE_BYTE) wc_MemZero_Add("wc_Sha256FinalRaw digest", digest, sizeof(digest)); @@ -2558,6 +2558,15 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if (!sha256->useSWCrypt) { + /* Resets the context on success. On failure the buffered + * message stays for wc_Sha256Free() to wipe and release. */ + return se050_hash_final(&sha256->se050Ctx, hash, + WC_SHA256_DIGEST_SIZE, + kAlgorithm_SSS_SHA256); + } + #endif #ifdef WOLF_CRYPTO_CB #ifndef WOLF_CRYPTO_CB_FIND if (sha256->devId != INVALID_DEVID) @@ -2610,6 +2619,12 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, if (sha256 == NULL || data == NULL) { return BAD_FUNC_ARG; } + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE05x hash keeps no digest state to transform. */ + if (!sha256->useSWCrypt) { + return NOT_COMPILED_IN; + } + #endif #if defined(WOLFSSL_ARMASM) || defined(WOLFSSL_RISCV_ASM) || \ (defined(WOLFSSL_PPC64_ASM) && defined(LITTLE_ENDIAN_ORDER)) @@ -2877,23 +2892,46 @@ static WC_INLINE int Transform_Sha256_Len(wc_Sha256* sha256, const byte* data, return BAD_ALIGN_E; } #endif - WC_SILABS_CLEAR_HASH_CTX(sha224); + /* Only se050Ctx hashes, but Free and Copy read the other fields, + * such as the W scratch pointer. */ + XMEMSET(sha224, 0, sizeof(*sha224)); + sha224->heap = heap; + #ifdef WOLF_CRYPTO_CB + sha224->devId = devId; + #else (void)devId; + #endif return se050_hash_init(&sha224->se050Ctx, heap); } int wc_Sha224Update(wc_Sha224* sha224, const byte* data, word32 len) { + if (sha224 == NULL) { + return BAD_FUNC_ARG; + } + if (data == NULL && len == 0) { + /* valid, but do nothing */ + return 0; + } + if (data == NULL) { + return BAD_FUNC_ARG; + } + return se050_hash_update(&sha224->se050Ctx, data, len); } int wc_Sha224Final(wc_Sha224* sha224, byte* hash) { int ret = 0; + if (sha224 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } + /* se050_hash_final() resets the context on success. On failure the + * buffered message stays for wc_Sha224Free() to wipe and release; + * re-initializing here would drop it without either. */ ret = se050_hash_final(&sha224->se050Ctx, hash, WC_SHA224_DIGEST_SIZE, kAlgorithm_SSS_SHA224); - (void)wc_InitSha224(sha224); return ret; } @@ -3346,6 +3384,9 @@ int wc_Sha224Reset(wc_Sha224* sha224) { sha224->msg = NULL; } #endif + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&sha224->se050Ctx); + #endif #if defined(PSOC6_HASH_SHA2) wc_Psoc6_Sha_Free(); #endif @@ -3651,11 +3692,27 @@ int wc_Sha224Reset(wc_Sha224* sha224) { * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha224Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha224)); + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } + #endif #ifdef WOLFSSL_SMALL_STACK_CACHE dst->W = (word32*)XMALLOC(WC_SHA256_TSCRATCH_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha224)); return MEMORY_E; } @@ -3815,6 +3872,19 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha256Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha256)); +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } +#endif #ifdef WOLFSSL_MAXQ10XX_CRYPTO wc_MAXQ10XX_Sha256Copy(src); @@ -3825,6 +3895,9 @@ int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) dst->W = (word32*)XMALLOC(WC_SHA256_TSCRATCH_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha256)); return MEMORY_E; } diff --git a/wolfcrypt/src/sha512.c b/wolfcrypt/src/sha512.c index c66309eb8ce..b61fe23c867 100644 --- a/wolfcrypt/src/sha512.c +++ b/wolfcrypt/src/sha512.c @@ -292,82 +292,6 @@ wc_static_assert(sizeof(Sha512TScratch) == WC_SHA512_TSCRATCH_SIZE); #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - int wc_InitSha512(wc_Sha512* sha512) - { - int ret; - if (sha512 == NULL) - return BAD_FUNC_ARG; - ret = se050_hash_init(&sha512->se050Ctx, NULL); -#if defined(WOLFSSL_SHA512_HASHTYPE) - if (ret == 0) { - sha512->hashType = WC_HASH_TYPE_SHA512; - } -#endif - return ret; - } - int wc_InitSha512_ex(wc_Sha512* sha512, void* heap, int devId) - { - int ret; - if (sha512 == NULL) { - return BAD_FUNC_ARG; - } - (void)devId; - ret = se050_hash_init(&sha512->se050Ctx, heap); -#if defined(WOLFSSL_SHA512_HASHTYPE) - if (ret == 0) { - sha512->hashType = WC_HASH_TYPE_SHA512; - } -#endif - return ret; - } - int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) - { - if (sha512 == NULL) { - return BAD_FUNC_ARG; - } - if (data == NULL && len == 0) { - /* valid, but do nothing */ - return 0; - } - if (data == NULL) { - return BAD_FUNC_ARG; - } - - return se050_hash_update(&sha512->se050Ctx, data, len); - } - int wc_Sha512Final(wc_Sha512* sha512, byte* hash) - { - int ret = 0; - int devId = INVALID_DEVID; - if (sha512 == NULL) { - return BAD_FUNC_ARG; - } - #ifdef WOLF_CRYPTO_CB - devId = sha512->devId; - #endif - ret = se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, - kAlgorithm_SSS_SHA512); - return ret; - } - int wc_Sha512FinalRaw(wc_Sha512* sha512, byte* hash) - { - int ret = 0; - int devId = INVALID_DEVID; - if (sha512 == NULL) { - return BAD_FUNC_ARG; - } - #ifdef WOLF_CRYPTO_CB - devId = sha512->devId; - #endif - ret = se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, - kAlgorithm_SSS_SHA512); - return ret; - } - void wc_Sha512Free(wc_Sha512* sha512) - { - se050_hash_free(&sha512->se050Ctx); - } #elif defined(STM32_HASH_SHA512) /* Supports CubeMX HAL or Standard Peripheral Library */ @@ -1043,8 +967,17 @@ int wc_Sha512Reset(wc_Sha512* sha512) { { void* heap = sha512->heap; int devId = sha512->devId; + int ret; + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Init_ex starts the object on the SE05x: keep where it hashes. */ + byte useSWCrypt = sha512->useSWCrypt; + #endif wc_Sha512Free(sha512); - return wc_InitSha512_ex(sha512, heap, devId); + ret = wc_InitSha512_ex(sha512, heap, devId); + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + sha512->useSWCrypt = useSWCrypt; + #endif + return ret; } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA512) && \ @@ -1055,6 +988,10 @@ int wc_Sha512Reset(wc_Sha512* sha512) { if (ret != 0) return ret; } +#endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Drop the message an SE05x object buffered; useSWCrypt stays. */ + se050_hash_free(&sha512->se050Ctx); #endif return InitSha512(sha512); } @@ -1973,6 +1910,12 @@ static int InitSha512_Family(wc_Sha512* sha512, void* heap, int devId, XMEMSET(sha512, 0, sizeof(*sha512)); sha512->heap = heap; +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The software implementation stays compiled in: wc_Sha512Update() and + * wc_Sha512Final() send the object to the SE05x unless useSWCrypt (zero + * here) gets set. */ + (void)se050_hash_init(&sha512->se050Ctx, heap); +#endif #ifdef WOLFSSL_SMALL_STACK_CACHE /* This allocation combines the customary W buffer used by * _Transform_Sha512() with additional buffer space used by @@ -2440,6 +2383,11 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if (!sha512->useSWCrypt) { + return se050_hash_update(&sha512->se050Ctx, data, len); + } +#endif #ifdef WOLF_CRYPTO_CB #ifndef WOLF_CRYPTO_CB_FIND if (sha512->devId != INVALID_DEVID) @@ -2473,8 +2421,6 @@ int wc_Sha512Update(wc_Sha512* sha512, const byte* data, word32 len) #elif defined(WOLFSSL_RENESAS_RSIP) && \ !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/renesas/renesas_fspsm_sha.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - #elif defined(MAX3266X_SHA) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ #elif defined(STM32_HASH_SHA512) @@ -2700,8 +2646,6 @@ static WC_INLINE int Sha512Final(wc_Sha512* sha512) #if defined(WOLFSSL_KCAPI_HASH) /* functions defined in wolfcrypt/src/port/kcapi/kcapi_hash.c */ -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - #elif defined(WOLFSSL_RENESAS_RSIP) && \ !defined(NO_WOLFSSL_RENESAS_FSPSM_HASH) /* functions defined in wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c */ @@ -2747,6 +2691,12 @@ static int Sha512FinalRaw(wc_Sha512* sha512, byte* hash, word32 digestSz) int wc_Sha512FinalRaw(wc_Sha512* sha512, byte* hash) { +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE05x hash only buffers the message: no state to read out. */ + if ((sha512 != NULL) && (hash != NULL) && !sha512->useSWCrypt) { + return NOT_COMPILED_IN; + } +#endif return Sha512FinalRaw(sha512, hash, WC_SHA512_DIGEST_SIZE); } @@ -2796,6 +2746,14 @@ static int Sha512_Family_Final(wc_Sha512* sha512, byte* hash, size_t digestSz, #ifndef STM32_HASH_SHA512 int wc_Sha512Final(wc_Sha512* sha512, byte* hash) { +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + if ((sha512 != NULL) && (hash != NULL) && !sha512->useSWCrypt) { + /* Resets the context on success. On failure the buffered message + * stays for wc_Sha512Free() to wipe and release. */ + return se050_hash_final(&sha512->se050Ctx, hash, WC_SHA512_DIGEST_SIZE, + kAlgorithm_SSS_SHA512); + } +#endif return Sha512_Family_Final(sha512, hash, WC_SHA512_DIGEST_SIZE, InitSha512); } #endif @@ -2806,7 +2764,6 @@ int wc_Sha512Final(wc_Sha512* sha512, byte* hash) /* Functions defined in wolfcrypt/src/port/maxim/max3266x.c */ #else -#if !defined(WOLFSSL_SE050) || !defined(WOLFSSL_SE050_HASH) int wc_InitSha512(wc_Sha512* sha512) { int devId = INVALID_DEVID; @@ -2881,10 +2838,12 @@ void wc_Sha512Free(wc_Sha512* sha512) #if defined(PSOC6_HASH_SHA2) wc_Psoc6_Sha_Free(); #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&sha512->se050Ctx); +#endif ForceZero(sha512, sizeof(*sha512)); } -#endif #if (defined(OPENSSL_EXTRA) || defined(HAVE_CURL)) \ && !defined(WOLFSSL_KCAPI_HASH) @@ -2903,6 +2862,12 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) if (sha == NULL || data == NULL) { return BAD_FUNC_ARG; } +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE05x hash keeps no digest state to transform. */ + if (!sha->useSWCrypt) { + return NOT_COMPILED_IN; + } +#endif #if defined(WOLFSSL_SMALL_STACK_CACHE) @@ -2968,8 +2933,8 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) return ret; } #endif /* OPENSSL_EXTRA */ +#endif /* !MAX3266X_SHA */ #endif /* WOLFSSL_SHA512 */ -#endif /* !WOLFSSL_SE050 || !WOLFSSL_SE050_HASH */ /* -------------------------------------------------------------------------- */ @@ -2986,7 +2951,15 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) if (sha384 == NULL) { return BAD_FUNC_ARG; } + /* Only se050Ctx hashes, but Free and Copy read the other fields, + * such as the W scratch pointer. */ + XMEMSET(sha384, 0, sizeof(*sha384)); + sha384->heap = heap; + #ifdef WOLF_CRYPTO_CB + sha384->devId = devId; + #else (void)devId; + #endif return se050_hash_init(&sha384->se050Ctx, heap); } int wc_Sha384Update(wc_Sha384* sha384, const byte* data, word32 len) @@ -3008,6 +2981,9 @@ int wc_Sha512Transform(wc_Sha512* sha, const unsigned char* data) int wc_Sha384Final(wc_Sha384* sha384, byte* hash) { int ret = 0; + if (sha384 == NULL || hash == NULL) { + return BAD_FUNC_ARG; + } ret = se050_hash_final(&sha384->se050Ctx, hash, WC_SHA384_DIGEST_SIZE, kAlgorithm_SSS_SHA384); return ret; @@ -3495,6 +3471,19 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha512Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha512)); +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } +#endif #ifdef WOLFSSL_SMALL_STACK_CACHE /* This allocation combines the customary W buffer used by * _Transform_Sha512() with additional buffer space used by @@ -3503,6 +3492,9 @@ int wc_Sha512Copy(wc_Sha512* src, wc_Sha512* dst) dst->W = (word64 *)XMALLOC(sizeof(Sha512TScratch) + WC_SHA512_BLOCK_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha512)); return MEMORY_E; } @@ -3949,6 +3941,19 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) * buffer, W cache, hardware contexts). XMEMCPY overwrites dst. */ wc_Sha384Free(dst); XMEMCPY(dst, src, sizeof(wc_Sha384)); +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* The SE050 hash buffers the whole message: give the copy a buffer of + * its own instead of sharing the source's, which the first Final or Free + * of either object would release under the other. */ + #ifdef WOLFSSL_SMALL_STACK_CACHE + /* If the copy fails, dst must not keep the source's scratch buffer. */ + dst->W = NULL; + #endif + ret = se050_hash_copy(&src->se050Ctx, &dst->se050Ctx); + if (ret != 0) { + return ret; + } +#endif #ifdef WOLFSSL_SMALL_STACK_CACHE /* This allocation combines the customary W buffer used by @@ -3958,6 +3963,9 @@ int wc_Sha384Copy(wc_Sha384* src, wc_Sha384* dst) dst->W = (word64 *)XMALLOC(sizeof(Sha512TScratch) + WC_SHA384_BLOCK_SIZE, dst->heap, DYNAMIC_TYPE_DIGEST); if (dst->W == NULL) { + #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + se050_hash_free(&dst->se050Ctx); + #endif ForceZero(dst, sizeof(wc_Sha384)); return MEMORY_E; } diff --git a/wolfcrypt/test/test.c b/wolfcrypt/test/test.c index e824cfe5d38..cf9b95ed6f1 100644 --- a/wolfcrypt/test/test.c +++ b/wolfcrypt/test/test.c @@ -199,6 +199,18 @@ static const byte const_byte_array[] = "A+Gd\0\0\0"; #include #include #endif +/* fork() while another thread holds the SE05x port lock: needs threads, a + * process model and the port's pid check. */ +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_PTHREADS) && \ + !defined(SINGLE_THREADED) && defined(HAVE_GETPID) && \ + !defined(WOLFSSL_NO_GETPID) && !defined(__STRICT_ANSI__) && \ + (defined(__unix__) || defined(__linux__) || defined(__APPLE__)) + #define WC_TEST_SE050_FORK + #include + #include + #include + #include +#endif /* WOLF_CRYPTO_CB_SEED_ONLY_TEST: a NO_DEV_RANDOM crypto callback build * where the callback is the only seed source, so a missing devId fails. */ #ifdef WOLF_CRYPTO_CB_SEED_ONLY_TEST @@ -1039,6 +1051,9 @@ WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_test(void); #ifdef WC_TEST_RNG_AUTOLOCK WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_thread_test(void); #endif +#ifdef WC_TEST_SE050_FORK +WOLFSSL_TEST_SUBROUTINE wc_test_ret_t se050_fork_test(void); +#endif #ifdef HAVE_WC_RNG_BANK WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_bank_test(void); #endif @@ -2930,6 +2945,12 @@ options: [-s max_relative_stack_bytes] [-m max_relative_heap_memory_bytes]\n\ else TEST_PASS("RNGTHRD test passed!\n"); #endif +#ifdef WC_TEST_SE050_FORK + if ((ret = se050_fork_test()) != 0) + TEST_FAIL("SE05XFRK test failed!\n", ret); + else + TEST_PASS("SE05XFRK test passed!\n"); +#endif #ifdef HAVE_WC_RNG_BANK if ((ret = random_bank_test()) != 0) TEST_FAIL("RNGBANK test failed!\n", ret); @@ -33401,6 +33422,156 @@ WOLFSSL_TEST_SUBROUTINE wc_test_ret_t random_thread_test(void) #endif /* WC_TEST_RNG_AUTOLOCK */ +#ifdef WC_TEST_SE050_FORK +struct se050_fork_holder_args { + int heldFd; /* gets one byte once the lock is held */ + int goFd; /* the lock is let go at a byte or EOF here */ + int ret; +}; + +/* Holds the SE05x port lock until told to let go, as a thread in the middle + * of an SE05x transaction would. */ +static THREAD_RETURN WOLFSSL_THREAD se050_fork_test_holder(void* arg) +{ + struct se050_fork_holder_args* a = (struct se050_fork_holder_args*)arg; + byte b = 1; + + a->ret = wc_se050_lock(); + if (a->ret == 0) { + if (write(a->heldFd, &b, 1) == 1) { + if (read(a->goFd, &b, 1) < 0) + a->ret = WC_TEST_RET_ENC_NC; + } + wc_se050_unlock(); + } + close(a->heldFd); /* EOF if the lock was never held */ + WOLFSSL_RETURN_FROM_THREAD(0); +} + +/* fork() while another thread holds the SE05x port lock. The child must be + * refused the parent's session at once: waiting for a lock whose holder does + * not exist in the child would never end, and using the session would + * interleave its APDUs with the parent's. The parent's session must still + * work afterwards. */ +WOLFSSL_TEST_SUBROUTINE wc_test_ret_t se050_fork_test(void) +{ + struct se050_fork_holder_args h; + THREAD_TYPE holder = INVALID_THREAD_VAL; /* joined only if started */ + int started = 0; + int hfd[2] = { -1, -1 }; + int gfd[2] = { -1, -1 }; + int cfd[2] = { -1, -1 }; + pid_t pid = -1; + int status = 0; + int rc; + byte b = 0; + wc_test_ret_t ret = 0; +#if defined(WOLFSSL_SE050_HASH) && !defined(NO_SHA256) + static const byte abcHash[WC_SHA256_DIGEST_SIZE] = { + 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, + 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, + 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, + 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad + }; + byte digest[WC_SHA256_DIGEST_SIZE]; +#endif + + WOLFSSL_ENTER("se050_fork_test"); + + if (wc_se050_get_session() == NULL) + return 0; /* no session for a child to inherit */ + + if ((pipe(hfd) != 0) || (pipe(gfd) != 0) || (pipe(cfd) != 0)) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + + h.heldFd = hfd[1]; + h.goFd = gfd[0]; + h.ret = 0; + if (wolfSSL_NewThread(&holder, &se050_fork_test_holder, &h) != 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + started = 1; + hfd[1] = -1; /* the holder closes it */ + if (read(hfd[0], &b, 1) != 1) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + + pid = fork(); + if (pid == 0) { + /* The lock's holder is not in this process. The alarm turns a wait + * for it into a death, which the parent reads as EOF. */ + byte res = 1; + (void)alarm(10); + rc = wc_se050_lock(); + if (rc == 0) + wc_se050_unlock(); + else if (rc == WC_NO_ERR_TRACE(BAD_STATE_E)) + res = 0; +#if defined(WOLFSSL_SE050_HASH) && !defined(NO_SHA256) + /* a SHA-256 on the SE05x must be refused as well */ + if ((res == 0) && (wc_Sha256Hash((const byte*)"abc", 3, digest) == 0)) + res = 2; +#endif + if (write(cfd[1], &res, 1) != 1) + _exit(1); + _exit(0); + } + if (pid < 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + close(cfd[1]); + cfd[1] = -1; + if (read(cfd[0], &b, 1) != 1) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); /* the child hung and died */ + rc = (int)b; /* 1: not refused, 2: the hash reached the SE05x */ + if (rc != 0) + ERROR_OUT(WC_TEST_RET_ENC_I(rc), done); + if (waitpid(pid, &status, 0) != pid) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + pid = -1; + if ((! WIFEXITED(status)) || (WEXITSTATUS(status) != 0)) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + + /* let the holder go, then the parent's session must still serve */ + close(gfd[1]); + gfd[1] = -1; + started = 0; + if (wolfSSL_JoinThread(holder) != 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); + if (h.ret != 0) + ERROR_OUT(WC_TEST_RET_ENC_EC(h.ret), done); + rc = wc_se050_lock(); + if (rc != 0) + ERROR_OUT(WC_TEST_RET_ENC_EC(rc), done); + wc_se050_unlock(); +#if defined(WOLFSSL_SE050_HASH) && !defined(NO_SHA256) + rc = wc_Sha256Hash((const byte*)"abc", 3, digest); + if (rc != 0) + ERROR_OUT(WC_TEST_RET_ENC_EC(rc), done); + if (XMEMCMP(digest, abcHash, sizeof(abcHash)) != 0) + ERROR_OUT(WC_TEST_RET_ENC_NC, done); +#endif + +done: + if (pid > 0) { + (void)kill(pid, SIGKILL); + (void)waitpid(pid, NULL, 0); + } + if (gfd[1] >= 0) + close(gfd[1]); /* EOF lets the holder go */ + if (started) + (void)wolfSSL_JoinThread(holder); + if (hfd[0] >= 0) + close(hfd[0]); + if (hfd[1] >= 0) + close(hfd[1]); + if (gfd[0] >= 0) + close(gfd[0]); + if (cfd[0] >= 0) + close(cfd[0]); + if (cfd[1] >= 0) + close(cfd[1]); + return ret; +} +#endif /* WC_TEST_SE050_FORK */ + #ifdef WC_RNG_HAVE_RBGC /* Post-init credited reseeds relabel RBGCStratum unless * WC_RNG_RBGC_STRATUM_IMMUTABLE (required for FIPS), wherein the stratum is @@ -43708,6 +43879,25 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) #endif /* NO_SHA */ #endif +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_NO_RSA_SW) && \ + !defined(WC_RSA_PSS) + /* Hardware only with no software padding layer: the SE050 offers OAEP + * with SHA-1, MGF1-SHA1 and an empty label only, so other parameters + * must be refused rather than replaced. */ + #ifndef NO_SHA256 + ret = wc_RsaPublicEncrypt_ex(in, inLen, out, outSz, key, rng, + WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA256, WC_MGF1SHA256, NULL, 0); + if (ret != WC_NO_ERR_TRACE(BAD_FUNC_ARG)) + ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit_rsa); + #endif + #ifndef NO_SHA + ret = wc_RsaPublicEncrypt_ex(in, inLen, out, outSz, key, rng, + WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA, WC_MGF1SHA1, in, inLen); + if (ret != WC_NO_ERR_TRACE(BAD_FUNC_ARG)) + ERROR_OUT(WC_TEST_RET_ENC_EC(ret), exit_rsa); + #endif + ret = 0; +#else #ifndef NO_SHA256 XMEMSET(plain, 0, plainSz); WC_TEST_RSA_ASYNC_DO(&key->asyncDev, @@ -43756,14 +43946,17 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) TEST_SLEEP(); /* TODO: investigate why Cavium Nitrox doesn't detect decrypt error here */ -#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \ - !defined(WOLFSSL_SE050) - /* Label is unused in SE050 so it won't detect decrypt error. */ +#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) idx = (word32)ret; WC_TEST_RSA_ASYNC_DO(&key->asyncDev, wc_RsaPrivateDecrypt_ex(out, idx, plain, plainSz, key, WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA256, WC_MGF1SHA256, in, inLen)); - if (ret > 0) { /* in this case decrypt should fail */ + /* in this case decrypt should fail */ +#ifdef WOLFSSL_RSA_DECRYPT_TO_0_LEN + if (ret > 0) { +#else + if (ret >= 0) { +#endif ERROR_OUT(WC_TEST_RET_ENC_NC, exit_rsa); } ret = 0; @@ -43804,14 +43997,18 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) TEST_SLEEP(); /* TODO: investigate why Cavium Nitrox doesn't detect decrypt error here */ -#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \ - !defined(WOLFSSL_SE050) +#if !defined(HAVE_CAVIUM) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) idx = (word32)ret; WC_TEST_RSA_ASYNC_DO(&key->asyncDev, wc_RsaPrivateDecrypt_ex(out, idx, plain, plainSz, key, WC_RSA_OAEP_PAD, WC_HASH_TYPE_SHA256, WC_MGF1SHA256, in, inLen)); - if (ret > 0) { /* should fail */ + /* should fail */ + #ifdef WOLFSSL_RSA_DECRYPT_TO_0_LEN + if (ret > 0) { + #else + if (ret >= 0) { + #endif ERROR_OUT(WC_TEST_RET_ENC_NC, exit_rsa); } ret = 0; @@ -43849,6 +44046,7 @@ static wc_test_ret_t rsa_oaep_padding_test(RsaKey* key, WC_RNG* rng) #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ } #endif /* WOLFSSL_SHA512 */ +#endif /* WOLFSSL_SE050 && WOLFSSL_NO_RSA_SW && !WC_RSA_PSS */ /* check using pkcsv15 padding with _ex API */ XMEMSET(plain, 0, plainSz); diff --git a/wolfcrypt/test/test.h b/wolfcrypt/test/test.h index d6919564eae..3d2521b0a86 100644 --- a/wolfcrypt/test/test.h +++ b/wolfcrypt/test/test.h @@ -61,8 +61,16 @@ (defined(__unix__) || defined(__linux__) || defined(__APPLE__)) #define WC_TEST_RNG_HOLD #endif +/* The SE05x port refuses a fork() child the parent's session, so a child + * whose DRBG seeds on the SE05x cannot reseed and draw. The fork tests below + * need a child that can. (The DRBG hashes in software, also with + * WOLFSSL_SE050_HASH.) */ +#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_TRNG) + #define WC_TEST_RNG_NO_FORK_CHILD +#endif /* The fork test needs a real process model on top of the handlers. */ -#if defined(WC_TEST_RNG_HOLD) && defined(WC_RNG_LOCK_ATFORK) +#if defined(WC_TEST_RNG_HOLD) && defined(WC_RNG_LOCK_ATFORK) && \ + !defined(WC_TEST_RNG_NO_FORK_CHILD) #define WC_TEST_RNG_AUTOFORK #endif /* fork() across a held WC_RNG.lock word: needs the word, a pid to compare, @@ -70,7 +78,7 @@ * orphan. */ #if defined(WC_RNG_HAVE_LOCK) && defined(HAVE_HASHDRBG) && \ defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \ - !defined(__STRICT_ANSI__) && \ + !defined(__STRICT_ANSI__) && !defined(WC_TEST_RNG_NO_FORK_CHILD) && \ (defined(__unix__) || defined(__linux__) || defined(__APPLE__)) #define WC_TEST_RNG_LOCKFORK #endif diff --git a/wolfssl/wolfcrypt/aes.h b/wolfssl/wolfcrypt/aes.h index d9cd9e2a2bd..2ac5df6c2d5 100644 --- a/wolfssl/wolfcrypt/aes.h +++ b/wolfssl/wolfcrypt/aes.h @@ -375,8 +375,6 @@ struct Aes { #ifdef HAVE_AESGCM Gcm gcm; #ifdef WOLFSSL_SE050 - sss_symmetric_t aes_ctx; /* used as the function context */ - int ctxInitDone; word32 keyId; byte keyIdSet; byte useSWCrypt; /* Use SW crypt instead of SE050, before SCP03 auth */ diff --git a/wolfssl/wolfcrypt/port/nxp/se050_port.h b/wolfssl/wolfcrypt/port/nxp/se050_port.h index b2bb519b203..f4920cf6e44 100644 --- a/wolfssl/wolfcrypt/port/nxp/se050_port.h +++ b/wolfssl/wolfcrypt/port/nxp/se050_port.h @@ -173,7 +173,9 @@ WOLFSSL_API sss_session_t* wc_se050_get_session(void); /** Return the low-level SE05x session, or NULL when none is configured. */ WOLFSSL_API pSe05xSession_t wc_se050_get_se05x_session(void); /** Acquire/release the SE05x session/transport lock. This is separate from - * the wolfCrypt hardware accelerator lock (wolfSSL_CryptHwMutexLock). */ + * the wolfCrypt hardware accelerator lock (wolfSSL_CryptHwMutexLock). + * wc_se050_lock() returns BAD_STATE_E in a fork() child of the process that + * configured the session, which must not use it (see README_SE050.md). */ WOLFSSL_API int wc_se050_lock(void); WOLFSSL_API void wc_se050_unlock(void); #ifdef WOLFSSL_SE050_INIT diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index 3de85c3e59e..875c3c0ce92 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -5414,6 +5414,14 @@ blinding by defining WC_BLINDING_NO_RNG_ACKNOWLEDGE_WEAKNESS." #define WOLFSSL_NO_HASH_RAW #endif +/* The SE05x hash buffers the whole message and keeps no intermediate digest, + * so the raw accessors (wc_Sha*FinalRaw(), wc_Sha*Transform()) cannot serve + * it. TLS, LMS and XMSS then use the full hash calls instead. */ +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + #undef WOLFSSL_NO_HASH_RAW + #define WOLFSSL_NO_HASH_RAW +#endif + #if defined(HAVE_XCHACHA) && !defined(HAVE_CHACHA) /* XChacha requires ChaCha */ #undef HAVE_XCHACHA diff --git a/wolfssl/wolfcrypt/sha256.h b/wolfssl/wolfcrypt/sha256.h index c3190d32d07..89b33e38ea5 100644 --- a/wolfssl/wolfcrypt/sha256.h +++ b/wolfssl/wolfcrypt/sha256.h @@ -220,8 +220,6 @@ struct wc_Sha256 { #ifdef FREESCALE_LTC_SHA ltc_hash_ctx_t ctx; -#elif defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) - SE050_HASH_Context se050Ctx; #elif defined(STM32_HASH_SHA2) STM32_HASH_Context stmCtx; #elif defined(WOLFSSL_SILABS_SE_ACCEL) @@ -255,6 +253,13 @@ struct wc_Sha256 { #if defined(WOLFSSL_SILABS_CRYPTOCB) wc_silabs_sha_t silabsCtx; #endif /* WOLFSSL_SILABS_CRYPTOCB */ +#if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* Also alongside the software members: a SHA-256 object hashes on the + * SE05x unless useSWCrypt is set, which the Hash DRBG does to keep its + * state off the bus. SHA-224 always uses the SE05x. */ + SE050_HASH_Context se050Ctx; + byte useSWCrypt; /* Use SW hash instead of SE050 */ +#endif void* heap; #ifdef WOLFSSL_PIC32MZ_HASH hashUpdCache cache; /* cache for updates */ diff --git a/wolfssl/wolfcrypt/sha512.h b/wolfssl/wolfcrypt/sha512.h index ad7eef309ea..4225883e814 100644 --- a/wolfssl/wolfcrypt/sha512.h +++ b/wolfssl/wolfcrypt/sha512.h @@ -194,7 +194,11 @@ struct wc_Sha512 { wolfssl_KCAPI_Hash kcapi; #endif #if defined(WOLFSSL_SE050) && defined(WOLFSSL_SE050_HASH) + /* SHA-512 objects hash on the SE05x unless useSWCrypt is set, which the + * Hash DRBG does to keep its state off the bus. SHA-384 always uses the + * SE05x. */ SE050_HASH_Context se050Ctx; + byte useSWCrypt; /* Use SW hash instead of SE050 */ #endif #if defined(WOLFSSL_HASH_KEEP) byte* msg; diff --git a/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs b/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs index cd23cc34c7e..c7f54c25fd5 100644 --- a/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs +++ b/wrapper/rust/wolfssl-wolfcrypt/src/cmac.rs @@ -135,7 +135,10 @@ impl CMAC { /// ``` pub fn new_ex(key: &[u8], heap: Option<*mut core::ffi::c_void>, dev_id: Option) -> Result { let key_size = crate::buffer_len_to_u32(key.len())?; - let mut ws_cmac: MaybeUninit = MaybeUninit::uninit(); + // Zeroed rather than uninitialized: in SE050 builds wc_InitCmac_ex() + // reads the useSWCrypt backend selection from the object before it + // resets it, and zero selects the default (the SE050). + let mut ws_cmac: MaybeUninit = MaybeUninit::zeroed(); let typ = sys::CmacType_WC_CMAC_AES as i32; let heap = match heap { Some(heap) => heap,