diff --git a/wolfcrypt/src/port/Espressif/esp32_aes.c b/wolfcrypt/src/port/Espressif/esp32_aes.c index 6a7855e9d24..3ef01adac96 100644 --- a/wolfcrypt/src/port/Espressif/esp32_aes.c +++ b/wolfcrypt/src/port/Espressif/esp32_aes.c @@ -475,15 +475,17 @@ int wc_esp32AesDecrypt(Aes *aes, const byte* in, byte* out) ESP_LOGV(TAG, "enter wc_esp32AesDecrypt"); /* lock the hw engine */ - esp_aes_hw_InUse(); - /* load the key into the register */ - ret = esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_DECRYPT); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "wc_esp32AesDecrypt failed " - "during esp_aes_hw_Set_KeyMode"); - /* release hw */ - esp_aes_hw_Leave(); - ret = BAD_FUNC_ARG; + ret = esp_aes_hw_InUse(); + if (ret == ESP_OK) { + /* load the key into the register */ + ret = esp_aes_hw_Set_KeyMode(aes, ESP32_AES_UPDATEKEY_DECRYPT); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "wc_esp32AesDecrypt failed " + "during esp_aes_hw_Set_KeyMode"); + /* release hw */ + esp_aes_hw_Leave(); + ret = BAD_FUNC_ARG; + } } if (ret == ESP_OK) { @@ -606,9 +608,9 @@ int wc_esp32AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) offset += WC_AES_BLOCK_SIZE; } /* while (blocks--) */ - esp_aes_hw_Leave(); } /* if Set Mode was successful (ret == ESP_OK) */ + esp_aes_hw_Leave(); ESP_LOGV(TAG, "leave wc_esp32AesCbcDecrypt"); return ret; } /* wc_esp32AesCbcDecrypt */ diff --git a/wolfcrypt/src/port/Espressif/esp32_mp.c b/wolfcrypt/src/port/Espressif/esp32_mp.c index 93a4476bcf5..9ca4d90b3e9 100644 --- a/wolfcrypt/src/port/Espressif/esp32_mp.c +++ b/wolfcrypt/src/port/Espressif/esp32_mp.c @@ -2249,6 +2249,9 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) #ifdef WOLFSSL_DEBUG_ESP_HW_MOD_RSAMAX_BITS ESP_LOGW(TAG, "result exceeds max bit length"); #endif + if (mulmod_lock_called) { + esp_mp_hw_unlock(); + } return MP_HW_FALLBACK; /* Error: value is not able to be used. */ } WordsForOperand = bits2words(OperandBits); @@ -2343,7 +2346,7 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) OperandBits, ESP_HW_MOD_RSAMAX_BITS); #endif if (mulmod_lock_called) { - ret = esp_mp_hw_unlock(); + esp_mp_hw_unlock(); } return MP_HW_FALLBACK; /* Error: value is not able to be used. */ } @@ -2440,6 +2443,9 @@ int esp_mp_mulmod(MATH_INT_T* X, MATH_INT_T* Y, MATH_INT_T* M, MATH_INT_T* Z) ESP_LOGW(TAG, "mp_mulmod OperandBits %d exceeds max bit length %d.", OperandBits, ESP_HW_MOD_RSAMAX_BITS); #endif + if (mulmod_lock_called) { + esp_mp_hw_unlock(); + } return MP_HW_FALLBACK; /* Error: value is not able to be used. */ } WordsForOperand = bits2words(OperandBits); diff --git a/wolfcrypt/src/port/Espressif/esp32_util.c b/wolfcrypt/src/port/Espressif/esp32_util.c index 533f012930b..ed258b17e2e 100644 --- a/wolfcrypt/src/port/Espressif/esp32_util.c +++ b/wolfcrypt/src/port/Espressif/esp32_util.c @@ -1007,6 +1007,7 @@ int show_binary(byte* theVar, size_t dataSz) { return 0; } +/* Assume toVar is big enough. */ int hexToBinary(byte* toVar, const char* fromHexString, size_t szHexString ) { int ret = 0; /* Calculate the actual binary length of the hex string */ @@ -1018,6 +1019,7 @@ int hexToBinary(byte* toVar, const char* fromHexString, size_t szHexString ) { } if ((szHexString % 2 != 0)) { ESP_LOGE("ssh", "fromHexString length not even!"); + return -1; } ESP_LOGW(TAG, "Replacing %d bytes at %x", byteLen, (word32)toVar); diff --git a/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c b/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c index fb309689c03..cb6ffdf8fde 100644 --- a/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c +++ b/wolfcrypt/src/port/Espressif/esp_sdk_time_lib.c @@ -189,7 +189,7 @@ int set_fixed_default_time(void) struct tm timeinfo = { .tm_year = YEAR - 1900, /* years since 1900 */ .tm_mon = MONTH - 1, /* Month, where 0 = Jan */ - .tm_mday = DAY - 1, /* Numeric decimal day of the month */ + .tm_mday = DAY, /* Numeric decimal day of the month */ .tm_hour = 13, .tm_min = 1, .tm_sec = 5 @@ -276,7 +276,7 @@ int set_time_from_string(const char* time_buffer) char offset[28]; /* large arrays, just in case there's still bad data */ char day_str[28]; char month_str[28]; - const char *format = "%3s %3s %d %d:%d:%d %d %s"; + const char *format = "%3s %3s %d %d:%d:%d %d %27s"; struct tm this_timeinfo; struct timeval now; time_t interim_time; @@ -304,18 +304,23 @@ int set_time_from_string(const char* time_buffer) "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; - for (int i = 0; i < 12; i++) { + int i; + for (i = 0; i < 12; i++) { if (strcmp(month_str, months[i]) == 0) { this_timeinfo.tm_mon = i; break; } } + if (i == 12) { + return ESP_FAIL; + } this_timeinfo.tm_mday = day; this_timeinfo.tm_hour = hour; this_timeinfo.tm_min = minute; this_timeinfo.tm_sec = second; this_timeinfo.tm_year = year - 1900; /* Years since 1900 */ + this_timeinfo.tm_isdst = -1; interim_time = mktime(&this_timeinfo); now = (struct timeval){ .tv_sec = interim_time }; @@ -397,11 +402,11 @@ int set_time(void) } ESP_LOGI(TAG, "sntp_setservername:"); for (i = 0; i < CONFIG_LWIP_SNTP_MAX_SERVERS; i++) { - const char* thisServer = ntpServerList[i]; - if (strncmp(thisServer, "\x00", 1) == 0) { - /* just in case we run out of NTP servers */ - break; + const char* thisServer; + if (i >= NTP_SERVER_COUNT) { + break; } + thisServer = ntpServerList[i]; ESP_LOGI(TAG, "%s", thisServer); sntp_setservername(i, thisServer); ret = ESP_OK; diff --git a/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c b/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c index 2f8ef17779f..085ebe77a54 100644 --- a/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c +++ b/wolfcrypt/src/port/Espressif/esp_sdk_wifi_lib.c @@ -324,6 +324,7 @@ static EventGroupHandle_t s_wifi_event_group; static int s_retry_num = 0; +/* TODO: use event in wc_wifi_show_ip - logging the IP string causes a panic. */ ip_event_got_ip_t* event; diff --git a/wolfcrypt/src/port/Renesas/renesas_common.c b/wolfcrypt/src/port/Renesas/renesas_common.c index 9ba975cc5c6..346343ff362 100644 --- a/wolfcrypt/src/port/Renesas/renesas_common.c +++ b/wolfcrypt/src/port/Renesas/renesas_common.c @@ -440,12 +440,12 @@ int wc_CryptoCb_CryptInitRenesasCmn(struct WOLFSSL* ssl, void* ctx) if (cbInfo->internal == NULL) { return MEMORY_E; } + ForceZero(cbInfo->internal, internal_sz); #if defined(WOLFSSL_RENESAS_FSPSM_TLS) ||\ defined(WOLFSSL_RENESAS_TSIP_TLS) if (ssl) cbInfo->internal->heap = ssl->heap; #endif - ForceZero(cbInfo->internal, internal_sz); } /* need exclusive control because of static variable */ if ((cmn_hw_lock()) == 0) { diff --git a/wolfcrypt/src/port/Renesas/renesas_fspsm_rsa.c b/wolfcrypt/src/port/Renesas/renesas_fspsm_rsa.c index 3ae1bd73259..59d05e3edfb 100644 --- a/wolfcrypt/src/port/Renesas/renesas_fspsm_rsa.c +++ b/wolfcrypt/src/port/Renesas/renesas_fspsm_rsa.c @@ -248,7 +248,7 @@ WOLFSSL_LOCAL int wc_fspsm_RsaSign(const byte* in, word32 inLen, byte* out, message_hash.data_type = info->keyflgs_crypt.bits.message_type;/* message 0, hash 1 */ signature.pdata = out; - signature.data_length = (word32*)outLen; + signature.data_length = *outLen; #if defined(WOLFSSL_RENESAS_RSIP) message_hash.hash_type = signature.hash_type = diff --git a/wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c b/wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c index 04ab9992082..c543946a164 100644 --- a/wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c +++ b/wolfcrypt/src/port/Renesas/renesas_fspsm_sha.c @@ -785,7 +785,7 @@ int wc_Sha512_256Final(wc_Sha512* sha, byte* hash) } int wc_Sha512_256GetHash(wc_Sha512* sha, byte* hash) { - return FSPSM_HashGet(sha, hash, WC_SHA512_224_DIGEST_SIZE); + return FSPSM_HashGet(sha, hash, WC_SHA512_256_DIGEST_SIZE); } int wc_Sha512_256Copy(wc_Sha512* src, wc_Sha512* dst) diff --git a/wolfcrypt/src/port/Renesas/renesas_fspsm_util.c b/wolfcrypt/src/port/Renesas/renesas_fspsm_util.c index 12933cf7aae..72e99b9d435 100644 --- a/wolfcrypt/src/port/Renesas/renesas_fspsm_util.c +++ b/wolfcrypt/src/port/Renesas/renesas_fspsm_util.c @@ -195,7 +195,7 @@ int wc_fspsm_GenerateRandBlock(byte* output, word32 sz) uint32_t fspbuf[RANDGEN_WORDS]; while (sz > 0) { - word32 len = sizeof(buffer); + word32 len = sizeof(fspbuf); if (sz < len) { len = sz; diff --git a/wolfcrypt/src/port/Renesas/renesas_tsip_aes.c b/wolfcrypt/src/port/Renesas/renesas_tsip_aes.c index 33cefd63403..477fab7ffd3 100644 --- a/wolfcrypt/src/port/Renesas/renesas_tsip_aes.c +++ b/wolfcrypt/src/port/Renesas/renesas_tsip_aes.c @@ -261,8 +261,8 @@ WOLFSSL_LOCAL int tsip_Tls13AesDecrypt( WOLFSSL_ENTER("tsip_Tls13AesDecrypt"); - if ((ssl == NULL) || (input == NULL) || (output == NULL) || (sz == 0) || - (ssl->RenesasUserCtx == NULL)) { + if ((ssl == NULL) || (input == NULL) || (output == NULL) || + (sz < TSIP_AES_GCM_AUTH_TAG_SIZE) || (ssl->RenesasUserCtx == NULL)) { return BAD_FUNC_ARG; } diff --git a/wolfcrypt/src/port/Renesas/renesas_tsip_sha.c b/wolfcrypt/src/port/Renesas/renesas_tsip_sha.c index 36fd62ef7e2..0d59577449a 100644 --- a/wolfcrypt/src/port/Renesas/renesas_tsip_sha.c +++ b/wolfcrypt/src/port/Renesas/renesas_tsip_sha.c @@ -398,6 +398,7 @@ static int TSIPHashFinal(wolfssl_TSIP_Hash* hash, byte* out, word32 outSz) if (ret == TSIP_SUCCESS) { ret = Final(&handle, out, (uint32_t*)&sz); if (ret != TSIP_SUCCESS || sz != outSz) { + tsip_hw_unlock(); return ret; } } @@ -442,6 +443,7 @@ static int TSIPHashGet(wolfssl_TSIP_Hash* hash, byte* out, word32 outSz) if (ret == TSIP_SUCCESS) { ret = Final(&handle, out, &sz); if (ret != TSIP_SUCCESS || sz != outSz) { + tsip_hw_unlock(); return ret; } } diff --git a/wolfcrypt/src/port/af_alg/afalg_aes.c b/wolfcrypt/src/port/af_alg/afalg_aes.c index 8da25af3f36..0a3d8b6cc1f 100644 --- a/wolfcrypt/src/port/af_alg/afalg_aes.c +++ b/wolfcrypt/src/port/af_alg/afalg_aes.c @@ -50,7 +50,7 @@ static int wc_AesSetup(Aes* aes, const char* type, const char* name, int ivSz, i byte* key = (byte*)aes->key; #endif - if (aes->alFd <= 0) { + if (aes->alFd == WC_SOCK_NOTSET) { aes->alFd = wc_Afalg_Socket(); if (aes->alFd < 0) { WOLFSSL_MSG("Unable to open an AF_ALG socket"); @@ -133,11 +133,11 @@ int wc_AesSetKey(Aes* aes, const byte* userKey, word32 keylen, aes->left = 0; #endif - if (aes->rdFd > 0) { + if (aes->rdFd > WC_SOCK_NOTSET) { (void)close(aes->rdFd); } aes->rdFd = WC_SOCK_NOTSET; - if (aes->alFd <= 0) { + if (aes->alFd == WC_SOCK_NOTSET) { aes->alFd = wc_Afalg_Socket(); } @@ -527,11 +527,11 @@ int wc_AesGcmSetKey(Aes* aes, const byte* key, word32 len) aes->keylen = len; aes->rounds = len/4 + 6; - if (aes->rdFd > 0) { + if (aes->rdFd > WC_SOCK_NOTSET) { (void)close(aes->rdFd); } aes->rdFd = WC_SOCK_NOTSET; - if (aes->alFd <= 0) { + if (aes->alFd == WC_SOCK_NOTSET) { aes->alFd = wc_Afalg_Socket(); } @@ -594,7 +594,7 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, return BAD_FUNC_ARG; } - if (aes->alFd <= 0) { + if (aes->alFd == WC_SOCK_NOTSET) { WOLFSSL_MSG("AF_ALG GcmEncrypt called with alFd unset"); return BAD_FUNC_ARG; } @@ -726,14 +726,18 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, } { - byte* tmp = (byte*)XMALLOC(authInSz, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (tmp == NULL) { - return MEMORY_E; + byte* tmp = NULL; + + if (authInSz > 0) { + tmp = (byte*)XMALLOC(authInSz, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (tmp == NULL) { + return MEMORY_E; + } + /* first 16 bytes was all 0's */ + iov[0].iov_base = tmp; + (void)scratch; + iov[0].iov_len = authInSz; } - /* first 16 bytes was all 0's */ - iov[0].iov_base = tmp; - (void)scratch; - iov[0].iov_len = authInSz; iov[1].iov_base = out; iov[1].iov_len = sz; @@ -743,9 +747,9 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, ret = (int)readv(aes->rdFd, iov, 3); XFREE(tmp, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); - } - if (ret < 0) { - return WC_AFALG_SOCK_E; + if (ret < 0) { + return WC_AFALG_SOCK_E; + } } #endif @@ -758,7 +762,8 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, * * Warning: If using Xilinx hardware acceleration it is assumed that the in * buffer is large enough to hold both cipher text and tag. That is - * sz | 16 bytes + * sz | 16 bytes. The in buffer has tag appended even though it is + * const for this wolfSSL API. */ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, const byte* iv, word32 ivSz, @@ -851,9 +856,6 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, if (ret < 0) return ret; xorbuf(tag, scratch, WC_AES_BLOCK_SIZE); - if (ret != 0) { - return AES_GCM_AUTH_E; - } } /* it is assumed that in buffer size is large enough to hold TAG */ @@ -933,12 +935,16 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, } { - byte* tmp = (byte*)XMALLOC(authInSz, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (tmp == NULL) { - return MEMORY_E; + byte* tmp = NULL; + + if (authInSz > 0) { + tmp = (byte*)XMALLOC(authInSz, aes->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (tmp == NULL) { + return MEMORY_E; + } + iov[0].iov_base = tmp; + iov[0].iov_len = authInSz; } - iov[0].iov_base = tmp; - iov[0].iov_len = authInSz; iov[1].iov_base = out; iov[1].iov_len = sz; ret = (int)readv(aes->rdFd, iov, 2); diff --git a/wolfcrypt/src/port/af_alg/afalg_hash.c b/wolfcrypt/src/port/af_alg/afalg_hash.c index 49258c90b83..429bb7d04b4 100644 --- a/wolfcrypt/src/port/af_alg/afalg_hash.c +++ b/wolfcrypt/src/port/af_alg/afalg_hash.c @@ -36,13 +36,13 @@ static void AfalgHashFree(wolfssl_AFALG_Hash* hash) if (hash == NULL) return; - if (hash->alFd > 0) { + if (hash->alFd > WC_SOCK_NOTSET) { (void)close(hash->alFd); - hash->alFd = -1; /* avoid possible double close on socket */ + hash->alFd = WC_SOCK_NOTSET; /* avoid possible double close on socket */ } - if (hash->rdFd > 0) { + if (hash->rdFd > WC_SOCK_NOTSET) { (void)close(hash->rdFd); - hash->rdFd = -1; /* avoid possible double close on socket */ + hash->rdFd = WC_SOCK_NOTSET; /* avoid possible double close on socket */ } #if defined(WOLFSSL_AFALG_HASH_KEEP) @@ -67,8 +67,8 @@ static int AfalgHashInit(wolfssl_AFALG_Hash* hash, void* heap, int devId, hash->len = 0; hash->used = 0; hash->msg = NULL; - hash->alFd = -1; - hash->rdFd = -1; + hash->alFd = WC_SOCK_NOTSET; + hash->rdFd = WC_SOCK_NOTSET; hash->alFd = wc_Afalg_Socket(); if (hash->alFd < 0) { @@ -78,6 +78,7 @@ static int AfalgHashInit(wolfssl_AFALG_Hash* hash, void* heap, int devId, hash->rdFd = wc_Afalg_CreateRead(hash->alFd, WC_TYPE_HASH, type); if (hash->rdFd < 0) { (void)close(hash->alFd); + hash->alFd = WC_SOCK_NOTSET; return WC_AFALG_SOCK_E; } @@ -186,7 +187,7 @@ static int AfalgHashGet(wolfssl_AFALG_Hash* hash, byte* out, word32 outSz) } if ((ret = (int)read(hash->rdFd, out, outSz)) != (int)outSz) { - return ret; + return WC_AFALG_SOCK_E; } return 0; #else @@ -210,20 +211,24 @@ static int AfalgHashCopy(wolfssl_AFALG_Hash* src, wolfssl_AFALG_Hash* dst) XMEMCPY(dst, src, sizeof(wolfssl_AFALG_Hash)); #ifdef WOLFSSL_AFALG_HASH_KEEP - dst->msg = (byte*)XMALLOC(src->len, dst->heap, DYNAMIC_TYPE_TMP_BUFFER); - if (dst->msg == NULL) { - return MEMORY_E; - } - if (src->len > 0) + if (src->len > 0) { + dst->msg = (byte*)XMALLOC(src->len, dst->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (dst->msg == NULL) { + return MEMORY_E; + } XMEMCPY(dst->msg, src->msg, src->len); + } + else { + dst->msg = NULL; + } #endif dst->rdFd = accept(src->rdFd, NULL, 0); dst->alFd = accept(src->alFd, NULL, 0); - if (dst->rdFd == -1 || dst->alFd == -1) { + if (dst->rdFd == WC_SOCK_NOTSET || dst->alFd == WC_SOCK_NOTSET) { AfalgHashFree(dst); - return -1; + return WC_AFALG_SOCK_E; } return 0; diff --git a/wolfcrypt/src/port/atmel/atmel.c b/wolfcrypt/src/port/atmel/atmel.c index ad1dea73725..08bbc2f664a 100644 --- a/wolfcrypt/src/port/atmel/atmel.c +++ b/wolfcrypt/src/port/atmel/atmel.c @@ -106,7 +106,7 @@ int atmel_get_random_number(uint32_t count, uint8_t* rand_out) { int ret = 0; #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) - uint8_t i = 0; + uint32_t i = 0; uint32_t copy_count = 0; uint8_t rng_buffer[RANDOM_NUM_SIZE]; @@ -292,7 +292,12 @@ int atmel_ecc_alloc(int slotType) break; } } + if (slotId == ATECC_INVALID_SLOT) { + goto exit; + } break; + default: + goto exit; } /* is slot available */ @@ -686,13 +691,16 @@ int atcatls_create_pms_cb(WOLFSSL* ssl, ecc_key* otherKey, /* for client: create and export public key */ if (side == WOLFSSL_CLIENT_END) { int slotId = atmel_ecc_alloc(ATMEL_SLOT_ECDHE); - if (slotId == ATECC_INVALID_SLOT) - return WC_HW_WAIT_E; + if (slotId == ATECC_INVALID_SLOT) { + ret = WC_HW_WAIT_E; + goto exit; + } tmpKey.slot = slotId; /* generate new ephemeral key on device */ ret = atmel_ecc_create_key(slotId, peerKey); if (ret != ATCA_SUCCESS) { + atmel_ecc_free(slotId); goto exit; } @@ -885,6 +893,7 @@ int atcatls_verify_signature_cb(WOLFSSL* ssl, const byte* sig, ret = wc_EccPublicKeyDecode(key, &idx, &tmpKey, keySz); } if (ret != 0) { + wc_ecc_free(&tmpKey); goto exit; } @@ -920,6 +929,8 @@ int atcatls_verify_signature_cb(WOLFSSL* ssl, const byte* sig, #else ret = NOT_COMPILED_IN; #endif /* !WOLFSSL_ATECC508A_NOSOFTECC */ + wc_ecc_free(&tmpKey); + goto exit; } (void)rSz; @@ -1049,6 +1060,13 @@ static int atcatls_set_certificates(WOLFSSL_CTX *ctx) #endif return (int)status; } + else if (deviceCertSize > ATCATLS_DEVICE_CERT_MAX_SIZE) { + #ifdef WOLFSSL_ATECC_DEBUG + printf("Device cert buffer too small, need to increase at least" + " to %d\r\n", deviceCertSize); + #endif + return -1; + } #endif /* Prepare the full buffer adding the signer certificate */ diff --git a/wolfcrypt/src/port/autosar/crypto.c b/wolfcrypt/src/port/autosar/crypto.c index c91c58d9a5d..bda8153384d 100644 --- a/wolfcrypt/src/port/autosar/crypto.c +++ b/wolfcrypt/src/port/autosar/crypto.c @@ -101,7 +101,7 @@ static int GetKey(Crypto_JobType* job, uint32 eId, uint8 **key, uint32 *keySz) } /* @TODO sanity checks on setup... uint8 redirectionConfig; */ - switch (eid) { + switch (eId) { case job->jobRedirectionInfoRef->inputKeyElementId: if (job->jobRedirectionInfoRef->inputKeyId >= MAX_KEYSTORE) { WOLFSSL_MSG("Bogus input key ID redirection (too large)"); @@ -148,6 +148,7 @@ static int GetKey(Crypto_JobType* job, uint32 eId, uint8 **key, uint32 *keySz) /* found matching key available, use it */ *key = keyStore[i].key; *keySz = keyStore[i].keyLen; + break; } } #endif @@ -193,6 +194,8 @@ static Aes* NewAesStruct(Crypto_JobType* job) ret = wc_AesInit(&activeJobs[i].aes, NULL, INVALID_DEVID); if (ret != 0) { WOLFSSL_MSG("Error initializing AES structure"); + activeJobs[i].inUse = 0; + activeJobs[i].jobId = 0; return NULL; } return &activeJobs[i].aes; @@ -262,10 +265,10 @@ Std_ReturnType wolfSSL_Crypto_CBC(Crypto_JobType* job) } if (wc_AesSetKey(aes, key, keySz, iv, encrypt) != 0) { + FreeAesStruct(job); WOLFSSL_MSG("Crypto error setting up AES key"); return E_NOT_OK; } - ForceZero(key, keySz); } if ((job->jobPrimitiveInputOutput.mode & CRYPTO_OPERATIONMODE_UPDATE) @@ -348,24 +351,12 @@ Std_ReturnType wolfSSL_Crypto_RNG(Crypto_JobType* job) return E_NOT_OK; } - if (rngInit == 1) { - if (wc_LockMutex(&rngMutex) != 0) { - WOLFSSL_MSG("Error locking RNG mutex"); - return E_NOT_OK; - } + if (wc_LockMutex(&rngMutex) != 0) { + WOLFSSL_MSG("Error locking RNG mutex"); + return E_NOT_OK; } if (rngInit == 0) { - if (wc_InitMutex(&rngMutex) != 0) { - WOLFSSL_MSG("Error initializing RNG mutex"); - return E_NOT_OK; - } - - if (wc_LockMutex(&rngMutex) != 0) { - WOLFSSL_MSG("Error locking RNG mutex"); - return E_NOT_OK; - } - ret = wc_InitRng_ex(&rng, NULL, 0); if (ret != 0) { WOLFSSL_MSG("Error initializing RNG"); @@ -449,6 +440,10 @@ void Crypto_Init(const Crypto_ConfigType* config) if (wc_InitMutex(&crypto_mutex) != 0) { WOLFSSL_MSG("Issues setting up crypto mutex"); } + if (wc_InitMutex(&rngMutex) != 0) { + WOLFSSL_MSG("Error initializing RNG mutex"); + } + XMEMSET(&keyStore, 0, MAX_KEYSTORE * sizeof(Keys)); XMEMSET(&activeJobs, 0, MAX_JOBS * sizeof(Jobs)); (void)config; diff --git a/wolfcrypt/src/port/autosar/test.c b/wolfcrypt/src/port/autosar/test.c index dbe923057ee..c22e4389318 100644 --- a/wolfcrypt/src/port/autosar/test.c +++ b/wolfcrypt/src/port/autosar/test.c @@ -271,6 +271,8 @@ static int random_test(void) #ifndef MAX_KEYSTORE /* default max key slots from crypto.c */ #define MAX_KEYSTORE 15 +#elif MAX_KEYSTORE > 255 + #error "Too many entries" #endif static int key_test(void) { diff --git a/wolfcrypt/src/port/devcrypto/devcrypto_ecdsa.c b/wolfcrypt/src/port/devcrypto/devcrypto_ecdsa.c index 4f3c70ee236..4ae7de01e62 100644 --- a/wolfcrypt/src/port/devcrypto/devcrypto_ecdsa.c +++ b/wolfcrypt/src/port/devcrypto/devcrypto_ecdsa.c @@ -228,6 +228,7 @@ int wc_DevCryptoEccVerify(int curveId, byte* pub, word32 pubSz, ret = wc_DevCryptoCreate(&ctx, CRYPTO_ASYM_ECDSA_VERIFY, NULL, 0); } if (ret == 0) { + XMEMSET(&kop, 0, sizeof(kop)); kop.crk_op = CRK_ECDSA_VERIFY; kop.ses = ctx.sess.ses; kop.crk_flags = CurveIDToFlag(curveId); diff --git a/wolfcrypt/src/port/devcrypto/devcrypto_hmac.c b/wolfcrypt/src/port/devcrypto/devcrypto_hmac.c index 7f5ad92243b..7032181a982 100644 --- a/wolfcrypt/src/port/devcrypto/devcrypto_hmac.c +++ b/wolfcrypt/src/port/devcrypto/devcrypto_hmac.c @@ -66,14 +66,15 @@ int wc_DevCrypto_HmacUpdate(Hmac* hmac, const byte* input, word32 inputSz) WC_CRYPTODEV* dev; struct crypt_op crt; + if (hmac == NULL) { + return BAD_FUNC_ARG; + } + if (inputSz == 0) { return 0; } - if ((dev = &hmac->ctx) == NULL) { - WOLFSSL_MSG("Unsupported hash type"); - return BAD_FUNC_ARG; - } + dev = &hmac->ctx; wc_SetupCrypt(&crt, dev, (byte*)input, inputSz, NULL, NULL, COP_FLAG_UPDATE, COP_ENCRYPT); @@ -91,11 +92,12 @@ int wc_DevCrypto_HmacFinal(Hmac* hmac, byte* out) WC_CRYPTODEV* dev; struct crypt_op crt; - if ((dev = &hmac->ctx) == NULL) { - WOLFSSL_MSG("Unsupported hash type"); + if (hmac == NULL || out == NULL) { return BAD_FUNC_ARG; } + dev = &hmac->ctx; + wc_SetupCrypt(&crt, dev, NULL, 0, NULL, out, COP_FLAG_FINAL, COP_ENCRYPT); if (ioctl(dev->cfd, CIOCCRYPT, &crt)) { WOLFSSL_MSG("Error with call to ioctl"); diff --git a/wolfcrypt/src/port/iotsafe/iotsafe.c b/wolfcrypt/src/port/iotsafe/iotsafe.c index c8e598f35df..16ebc4ee683 100644 --- a/wolfcrypt/src/port/iotsafe/iotsafe.c +++ b/wolfcrypt/src/port/iotsafe/iotsafe.c @@ -198,7 +198,7 @@ static char *search_tlv(const char *haystack, int size, uint8_t tag) int i = 0; uint8_t t; uint8_t l; - while (i < size) { + while (i <= size - 4) { if (hex_to_bytes(&haystack[i], &t, 1) < 0) return NULL; if (hex_to_bytes(&haystack[i + 2], &l, 1) < 0) @@ -277,6 +277,9 @@ static int iotsafe_cmd_add_tlv_ex(char *cmd, byte tag, uint16_t len, return BAD_FUNC_ARG; } + if ((int)cur_lc + 1 + taglen_size + len > 0xFF) { + return BAD_FUNC_ARG; + } /* Increase Lc and CSIM length according to the TLV len */ cur_lc += 1 + taglen_size + len; cur_csim_len += 2 + (2 * taglen_size) + 2*len; @@ -457,7 +460,7 @@ static int iotsafe_readfile(uint8_t *file_id, uint16_t file_id_sz, return ret; } - filesz_s = search_tlv(resp + 4, ret, 0x20); + filesz_s = search_tlv(resp + 4, ret - 4, 0x20); if ((filesz_s) && (XSTRLEN(filesz_s)) >= 8) { uint8_t fs_msb, fs_lsb; if (hex_to_bytes(filesz_s + 4, &fs_msb, 1) < 0) @@ -486,7 +489,7 @@ static int iotsafe_readfile(uint8_t *file_id, uint16_t file_id_sz, iotsafe_cmd_add_tlv(csim_cmd, IOTSAFE_TAG_FILE_ID, file_id_sz, file_id); iotsafe_cmd_complete(csim_cmd); ret = expect_csim_response(csim_cmd, (word32)XSTRLEN(csim_cmd), &resp); - if (ret > 0) { + if (ret >= 2) { if (ret > 2 * (file_sz - off)) ret = 2 * (file_sz - off); if (hex_to_bytes(resp, content + off, (ret / 2)) < 0) { @@ -494,7 +497,7 @@ static int iotsafe_readfile(uint8_t *file_id, uint16_t file_id_sz, } off += ret/2; #ifdef IOTSAFE_NO_GETDATA - if (XSTRNCMP(&resp[ret-4], "0000", 4) == 0) { + if (ret >= 4 && XSTRNCMP(&resp[ret-4], "0000", 4) == 0) { /* Strip trailing zeros */ int idx = 0; for (idx = 0; idx < off-1; idx+=2) { @@ -525,7 +528,8 @@ static int iotsafe_getrandom(unsigned char* output, unsigned long sz) int ret; int i; byte len = (byte)sz; - if (sz == 0) { + + if (sz == 0 || sz > 255) { return BAD_FUNC_ARG; } if (!wolfIoT_initialized) { @@ -553,9 +557,7 @@ static int iotsafe_getrandom(unsigned char* output, unsigned long sz) /* Send an empty command until the applet is responsive again */ for (i = 0; i < IOTSAFE_MAX_RETRIES; i++) { - if (expect_tok(NULL, 0, NULL, NULL) < 0) { - ret = WC_HW_E; - } + (void)expect_tok(NULL, 0, NULL, NULL); } return ret; } @@ -597,6 +599,11 @@ static int iotsafe_parse_public_key(char* resp, int len, ecc_key *key) WOLFSSL_MSG("Cannot initialize ecc key to store IoTSafe public key"); return -1; } + if ((int)(payload_str - resp) + 6 + (int)(IOTSAFE_ECC_KSIZE * 4) > len) { + WOLFSSL_MSG("IoT safe: response too short for key data"); + wc_ecc_free(key); + return BAD_STATE_E; + } XSTRNCPY(Qx, payload_str + 6, IOTSAFE_ECC_KSIZE * 2); XSTRNCPY(Qy, payload_str + 6 + IOTSAFE_ECC_KSIZE * 2, IOTSAFE_ECC_KSIZE * 2); @@ -878,19 +885,27 @@ static int iotsafe_sign_hash(byte *privkey_idx, uint16_t id_size, #ifdef IOTSAFE_SIG_8BIT_LENGTH else if ((sig_hdr[0] == IOTSAFE_TAG_SIGNATURE_FIELD) && (sig_hdr[1] == 2 * IOTSAFE_ECC_KSIZE)) { - XSTRNCPY(R, resp + 4, IOTSAFE_ECC_KSIZE * 2); - XSTRNCPY(S, resp + 4 + IOTSAFE_ECC_KSIZE * 2, - IOTSAFE_ECC_KSIZE * 2); - ret = wc_ecc_rs_to_sig(R, S, signature, sigLen); + if (ret < 4 + (int)(IOTSAFE_ECC_KSIZE * 4)) { + ret = WC_HW_E; + } else { + XSTRNCPY(R, resp + 4, IOTSAFE_ECC_KSIZE * 2); + XSTRNCPY(S, resp + 4 + IOTSAFE_ECC_KSIZE * 2, + IOTSAFE_ECC_KSIZE * 2); + ret = wc_ecc_rs_to_sig(R, S, signature, sigLen); + } } #endif else if ((sig_hdr[0] == IOTSAFE_TAG_SIGNATURE_FIELD) && (sig_hdr[1] == 0) && (sig_hdr[2] == 2 * IOTSAFE_ECC_KSIZE)) { - XSTRNCPY(R, resp + 6, IOTSAFE_ECC_KSIZE * 2); - XSTRNCPY(S, resp + 6 + IOTSAFE_ECC_KSIZE * 2, - IOTSAFE_ECC_KSIZE * 2); - ret = wc_ecc_rs_to_sig(R, S, signature, sigLen); + if (ret < 6 + (int)(IOTSAFE_ECC_KSIZE * 4)) { + ret = WC_HW_E; + } else { + XSTRNCPY(R, resp + 6, IOTSAFE_ECC_KSIZE * 2); + XSTRNCPY(S, resp + 6 + IOTSAFE_ECC_KSIZE * 2, + IOTSAFE_ECC_KSIZE * 2); + ret = wc_ecc_rs_to_sig(R, S, signature, sigLen); + } } else { ret = WC_HW_E; WOLFSSL_MSG("Invalid response from EC sign update"); @@ -1068,6 +1083,7 @@ static int wolfIoT_ecc_keygen(WOLFSSL* ssl, struct ecc_key* key, } #ifdef HAVE_HKDF +/* ikm will not be NULL. */ static int wolfIoT_hkdf_extract(byte* prk, const byte* salt, word32 saltLen, byte* ikm, word32 ikmLen, int digest, void* ctx) { @@ -1351,6 +1367,8 @@ static int wolfIoT_ecc_shared_secret(WOLFSSL* ssl, struct ecc_key* otherKey, if (ret <= 0) { WOLFSSL_MSG("Unexpected reply in ECDH command"); ret = WC_HW_E; + } else if ((word32)(ret / 2) > *outlen) { + ret = BUFFER_E; } else { int out_len = hex_to_bytes(resp, out, ret / 2); if (out_len < 0) { diff --git a/wolfcrypt/src/port/kcapi/kcapi_aes.c b/wolfcrypt/src/port/kcapi/kcapi_aes.c index 3b5f2f47197..5003d52e679 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_aes.c +++ b/wolfcrypt/src/port/kcapi/kcapi_aes.c @@ -57,7 +57,8 @@ int ret = 0; struct iovec iov; - if (aes == NULL || out == NULL || in == NULL) { + if (aes == NULL || out == NULL || in == NULL || + sz % WC_AES_BLOCK_SIZE != 0) { ret = BAD_FUNC_ARG; } @@ -270,13 +271,13 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, } #else ret = posix_memalign((void*)&data, pageSz, dataSz); - if (ret < 0) { + if (ret != 0) { ret = MEMORY_E; } #endif } - if (ret >= 0) { + if (ret == 0) { ret = kcapi_aead_setkey(aes->handle, (byte*)aes->devKey, aes->keylen); if (ret != 0) { WOLFSSL_MSG("GcmEncrypt set key failed"); @@ -292,8 +293,10 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, const byte* in, word32 sz, if (ret == 0) { kcapi_aead_setassoclen(aes->handle, authInSz); - XMEMCPY(data, authIn, authInSz); - XMEMCPY(data + authInSz, in, sz); + if (authInSz > 0) + XMEMCPY(data, authIn, authInSz); + if (sz > 0) + XMEMCPY(data + authInSz, in, sz); ret = (int)kcapi_aead_encrypt(aes->handle, data, inbuflen, iv, data, outbuflen, KCAPI_ACCESS_HEURISTIC); @@ -383,13 +386,13 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, } #else ret = posix_memalign((void*)&data, pageSz, dataSz); - if (ret < 0) { + if (ret != 0) { ret = MEMORY_E; } #endif } - if (ret >= 0) { + if (ret == 0) { ret = kcapi_aead_setkey(aes->handle, (byte*)aes->devKey, aes->keylen); if (ret != 0) { WOLFSSL_MSG("GcmDecrypt set key failed"); @@ -402,8 +405,10 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, if (ret == 0) { kcapi_aead_setassoclen(aes->handle, authInSz); - XMEMCPY(data, authIn, authInSz); - XMEMCPY(data + authInSz, in, sz); + if (authInSz > 0) + XMEMCPY(data, authIn, authInSz); + if (sz > 0) + XMEMCPY(data + authInSz, in, sz); XMEMCPY(data + authInSz + sz, authTag, authTagSz); ret = (int)kcapi_aead_decrypt(aes->handle, data, inbuflen, iv, data, diff --git a/wolfcrypt/src/port/kcapi/kcapi_dh.c b/wolfcrypt/src/port/kcapi/kcapi_dh.c index 40eab60f03a..83c4d81bea9 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_dh.c +++ b/wolfcrypt/src/port/kcapi/kcapi_dh.c @@ -94,6 +94,10 @@ int KcapiDh_MakeKey(DhKey* key, byte* pub, word32* pubSz) if (ret == 0) { ret = (int)kcapi_kpp_keygen(key->handle, pub, *pubSz, KCAPI_ACCESS_HEURISTIC); + if (ret >= 0) { + *pubSz = ret; + ret = 0; + } } return ret; @@ -103,7 +107,7 @@ int KcapiDh_MakeKey(DhKey* key, byte* pub, word32* pubSz) static int KcapiDh_SetPrivKey(DhKey* key) { int ret; - unsigned char* priv; + unsigned char* priv = NULL; int len; len = ret = mp_unsigned_bin_size(&key->priv); @@ -123,6 +127,7 @@ static int KcapiDh_SetPrivKey(DhKey* key) } } + XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } #endif @@ -143,7 +148,7 @@ int KcapiDh_SharedSecret(DhKey* private_key, const byte* pub, word32 pubSz, } #ifdef WOLFSSL_DH_EXTRA - if (!mp_iszero(&private_key->priv)) { + if (ret == 0 && !mp_iszero(&private_key->priv)) { ret = KcapiDh_SetPrivKey(private_key); } #endif diff --git a/wolfcrypt/src/port/kcapi/kcapi_ecc.c b/wolfcrypt/src/port/kcapi/kcapi_ecc.c index dfa82e05532..cae76c977fe 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_ecc.c +++ b/wolfcrypt/src/port/kcapi/kcapi_ecc.c @@ -166,7 +166,7 @@ int KcapiEcc_MakeKey(ecc_key* key, int keysize, int curve_id) /* check arguments */ if (key == NULL || key->dp == NULL) { - ret = BAD_FUNC_ARG; + return BAD_FUNC_ARG; } ret = KcapiEcc_LoadKey(key, key->pubkey_raw, &pubkey_sz, 0); @@ -389,7 +389,7 @@ int KcapiEcc_Sign(ecc_key* key, const byte* hash, word32 hashLen, byte* sig, } if (handleInit) { - kcapi_kpp_destroy(key->handle); + kcapi_akcipher_destroy(key->handle); key->handle = NULL; } @@ -489,7 +489,7 @@ int KcapiEcc_Verify(ecc_key* key, const byte* hash, word32 hashLen, byte* sig, } if (handleInit) { - kcapi_kpp_destroy(key->handle); + kcapi_akcipher_destroy(key->handle); key->handle = NULL; } return ret; diff --git a/wolfcrypt/src/port/kcapi/kcapi_hash.c b/wolfcrypt/src/port/kcapi/kcapi_hash.c index c241b1b75b7..45a678531a1 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_hash.c +++ b/wolfcrypt/src/port/kcapi/kcapi_hash.c @@ -92,7 +92,10 @@ static int KcapiHashUpdate(wolfssl_KCAPI_Hash* hash, const byte* in, word32 sz) #ifdef WOLFSSL_KCAPI_HASH_KEEP if (ret == 0) { /* keep full message to hash at end instead of incremental updates */ - if (hash->len < hash->used + sz) { + if (hash->used + sz < sz) { + ret = MEMORY_E; + } + else if (hash->len < hash->used + sz) { if (hash->msg == NULL) { hash->msg = (byte*)XMALLOC(hash->used + sz, hash->heap, DYNAMIC_TYPE_TMP_BUFFER); @@ -156,7 +159,12 @@ static int KcapiHashFinal(wolfssl_KCAPI_Hash* hash, byte* out, word32 outSz, heap = hash->heap; /* keep because KcapiHashInit clears the pointer */ #ifdef WOLFSSL_KCAPI_HASH_KEEP /* keep full message to out at end instead of incremental updates */ - ret = (int)kcapi_md_update(hash->handle, hash->msg, hash->used); + if (hash->used > 0) { + ret = (int)kcapi_md_update(hash->handle, hash->msg, hash->used); + if (ret > 0) { + ret = 0; + } + } XFREE(hash->msg, heap, DYNAMIC_TYPE_TMP_BUFFER); hash->msg = NULL; if (ret == 0) @@ -190,8 +198,13 @@ static int KcapiHashGet(wolfssl_KCAPI_Hash* hash, byte* out, word32 outSz) ret = kcapi_md_init(&hash->handle, hash->type, 0); } if (ret == 0) { - ret = (int)kcapi_md_update(hash->handle, hash->msg, hash->used); - if (ret >= 0) { + if (hash->used > 0) { + ret = (int)kcapi_md_update(hash->handle, hash->msg, hash->used); + if (ret > 0) { + ret = 0; + } + } + if (ret == 0) { ret = (int)kcapi_md_final(hash->handle, out, outSz); if (ret >= 0) { ret = 0; diff --git a/wolfcrypt/src/port/kcapi/kcapi_hmac.c b/wolfcrypt/src/port/kcapi/kcapi_hmac.c index f5834253322..a5c39cf0aad 100644 --- a/wolfcrypt/src/port/kcapi/kcapi_hmac.c +++ b/wolfcrypt/src/port/kcapi/kcapi_hmac.c @@ -158,18 +158,24 @@ int wc_HmacSetKey(Hmac* hmac, int type, const byte* key, word32 length) ret = BAD_FUNC_ARG; break; } - hmac->macType = type; } - if (hmac->handle != NULL) { - kcapi_md_destroy(hmac->handle); - hmac->handle = NULL; - } if (ret == 0) { + if (hmac->handle != NULL) { + kcapi_md_destroy(hmac->handle); + hmac->handle = NULL; + } ret = kcapi_md_init(&hmac->handle, ciphername, 0); } if (ret == 0) { ret = kcapi_md_setkey(hmac->handle, key, length); + if (ret != 0) { + kcapi_md_destroy(hmac->handle); + hmac->handle = NULL; + } + } + if (ret == 0) { + hmac->macType = type; } return ret; diff --git a/wolfcrypt/src/port/maxim/max3266x.c b/wolfcrypt/src/port/maxim/max3266x.c index 5a708421235..c05c2781b04 100644 --- a/wolfcrypt/src/port/maxim/max3266x.c +++ b/wolfcrypt/src/port/maxim/max3266x.c @@ -562,7 +562,7 @@ int wc_MxcCb_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) if (status == 0) { XMEMCPY(iv, out + sz - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); } - return (status == 0) ? 0 : -1; + return status; } #endif /* HAVE_AES_CBC */ #endif /* WOLF_CRYPTO_CB */ @@ -682,7 +682,7 @@ int wc_MxcCb_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) if (status == 0) { XMEMCPY(iv, temp_block, WC_AES_BLOCK_SIZE); } - return (status == 0) ? 0 : -1; + return status; } #endif /* HAVE_AES_CBC */ #endif /* WOLF_CRYPTO_CB */ @@ -815,6 +815,8 @@ int wc_MXC_TPU_SHA_Copy(void* src, void* dst, word32 ctxSz, return BAD_FUNC_ARG; } + srcBuf = *dstMsg; + /* Free existing dst msg buffer using dst's original heap */ wc_MXC_TPU_SHA_Free(dstMsg, dstUsed, dstLen, dstHeap); @@ -822,8 +824,7 @@ int wc_MXC_TPU_SHA_Copy(void* src, void* dst, word32 ctxSz, XMEMCPY(dst, src, ctxSz); /* Deep copy src msg buffer if present, allocate using src's heap */ - if (*dstMsg != NULL) { - srcBuf = *dstMsg; + if (srcBuf != NULL) { *dstMsg = (byte*)XMALLOC(*dstLen, srcHeap, DYNAMIC_TYPE_TMP_BUFFER); if (*dstMsg == NULL) { return MEMORY_E; @@ -1361,9 +1362,6 @@ int wc_MXC_MAA_zeroPad(mp_int* multiplier, mp_int* multiplicand, ForceZero(result->dp, sizeof(int)*(length)); result->used = length; } - else if (result == NULL) { - return BAD_FUNC_ARG; /* Cannot be null */ - } return 0; } @@ -1426,7 +1424,8 @@ int wc_MXC_MAA_math(mp_int* multiplier, mp_int* multiplicand, mp_int* exp, MAX3266X_MSG("Starting Computation in MAA"); ret = MXC_TPU_MAA_Compute(clc, (char *)(multiplier->dp), (char *)(multiplicand->dp), - (char *)(exp->dp), (char *)(mod->dp), + (char *)((exp == NULL) ? NULL: exp->dp), + (char *)(mod->dp), (int *)(result_tmp_ptr->dp), (length*sizeof(mp_digit))); MAX3266X_MSG("MAA Finished Computation"); @@ -1448,7 +1447,7 @@ int wc_MXC_MAA_math(mp_int* multiplier, mp_int* multiplicand, mp_int* exp, if ((multiplier == result) || (multiplicand == result) || (exp == result) || (mod == result)) { mp_copy(result_tmp_ptr, result); - ForceZero(result_tmp_ptr, sizeof(result_tmp_ptr)); /* force zero */ + ForceZero(result_tmp_ptr, sizeof(mp_int)); /* force zero */ } result->used = wc_MXC_MAA_adjustUsed(result->dp, length); diff --git a/wolfcrypt/src/port/maxim/maxq10xx.c b/wolfcrypt/src/port/maxim/maxq10xx.c index d1ab0a5c183..dc18db7fd83 100644 --- a/wolfcrypt/src/port/maxim/maxq10xx.c +++ b/wolfcrypt/src/port/maxim/maxq10xx.c @@ -945,13 +945,13 @@ static int ecc_establish(ecc_key* key, ecc_key* peer, byte *ss, word32 *ss_len) mxq_length output_len = ESTABLISH_OUT_MAX; byte output[ESTABLISH_OUT_MAX]; - word32 peerKeySz = peer->dp->size; + word32 peerKeySz; uint8_t peerKeyBuf[MAX_EC_KEY_SIZE]; uint8_t* peerKey = peerKeyBuf; - uint8_t* qx = peerKey; - uint8_t* qy = &peerKey[peerKeySz]; - word32 qxLen = peerKeySz; - word32 qyLen = peerKeySz; + uint8_t* qx; + uint8_t* qy; + word32 qxLen; + word32 qyLen; /* ECC P256 shared secret is 32 bytes. */ if (*ss_len != 32) { @@ -966,6 +966,12 @@ static int ecc_establish(ecc_key* key, ecc_key* peer, byte *ss, word32 *ss_len) return BAD_FUNC_ARG; } + peerKeySz = peer->dp->size; + qx = peerKey; + qy = &peerKey[peerKeySz]; + qxLen = peerKeySz; + qyLen = peerKeySz; + if (key->maxq_ctx.hw_ecc != 1) { /* The key was not generated. Lets import it. */ if (key->maxq_ctx.hw_ecc == 0) { @@ -990,7 +996,7 @@ static int ecc_establish(ecc_key* key, ecc_key* peer, byte *ss, word32 *ss_len) return WC_HW_E; } - wc_ecc_export_public_raw(peer, qx, &qxLen, qy, &qyLen); + rc = wc_ecc_export_public_raw(peer, qx, &qxLen, qy, &qyLen); if (rc != 0) { return rc; } @@ -2589,8 +2595,10 @@ static int wc_MAXQ10XX_HmacSetKey(int type) } if (tls13_server_finish_obj_id != -1) { - free_temp_key_id(*tls13_server_key_id); - *tls13_server_key_id = -1; + if (tls13_server_key_id != NULL) { + free_temp_key_id(*tls13_server_key_id); + *tls13_server_key_id = -1; + } mac_key_obj_id = &tls13_server_finish_obj_id; } else if (tls13_client_finish_obj_id != -1) { @@ -2666,9 +2674,11 @@ static int wc_MAXQ10XX_HmacFinal(byte* hash) rc = WC_HW_E; } - free_temp_key_id(*mac_key_obj_id); - *mac_key_obj_id = -1; - mac_key_obj_id = NULL; + if (mac_key_obj_id != NULL) { + free_temp_key_id(*mac_key_obj_id); + *mac_key_obj_id = -1; + mac_key_obj_id = NULL; + } mac_comp_active = 0; return rc; @@ -2886,6 +2896,9 @@ static int maxq10xx_tls13_ecc_shared_secret(WOLFSSL* ssl, ecc_key* otherKey, WOLFSSL_ENTER("maxq10xx_ecc_shared_secret"); rc = wc_ecc_export_public_raw(otherKey, qx, &qxLen, qy, &qyLen); + if (rc != 0) { + return rc; + } if (tls13_ecc_obj_id == -1) { WOLFSSL_ERROR_MSG("MAXQ: ECDHE key is not created before"); @@ -3488,14 +3501,14 @@ static int maxq10xx_HkdfExpand(int digest, const byte* inKey, word32 inKeySz, int tls13_client_iv_obj_id = -1; if (is_hs_key) { if (tls13_client_hs_key_obj_id == -1) { - WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed"); + WOLFSSL_ERROR_MSG("MAXQ: client hs key not set"); return NOT_COMPILED_IN; } tls13_client_iv_obj_id = tls13_client_hs_key_obj_id; } else { if (tls13_client_app_key_obj_id == -1) { - WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed"); + WOLFSSL_ERROR_MSG("MAXQ: client app key not set"); return NOT_COMPILED_IN; } tls13_client_iv_obj_id = tls13_client_app_key_obj_id; @@ -3514,14 +3527,14 @@ static int maxq10xx_HkdfExpand(int digest, const byte* inKey, word32 inKeySz, int tls13_server_iv_obj_id = -1; if (is_hs_key) { if (tls13_server_hs_key_obj_id == -1) { - WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed"); + WOLFSSL_ERROR_MSG("MAXQ: server hs key not set"); return NOT_COMPILED_IN; } tls13_server_iv_obj_id = tls13_server_hs_key_obj_id; } else { if (tls13_server_app_key_obj_id == -1) { - WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed"); + WOLFSSL_ERROR_MSG("MAXQ: server app key not set"); return NOT_COMPILED_IN; } tls13_server_iv_obj_id = tls13_server_app_key_obj_id; @@ -3636,8 +3649,10 @@ static int maxq10xx_HkdfExpand(int digest, const byte* inKey, word32 inKeySz, ret_kid = tls13_res_master_obj_id; ret_keytype = MXQ_KEYTYPE_IKM; ret_isiv = 0; - free_temp_key_id(*tls13_client_key_id); - *tls13_client_key_id = -1; + if (tls13_client_key_id != NULL) { + free_temp_key_id(*tls13_client_key_id); + *tls13_client_key_id = -1; + } } else if (strstr_with_size((char *)info, appTrafUpdLabel, infoSz) != NULL) { if (side == WOLFSSL_CLIENT_END) { @@ -3656,7 +3671,7 @@ static int maxq10xx_HkdfExpand(int digest, const byte* inKey, word32 inKeySz, /* updated_server_secret = HKDF-Expand-Label(key: server_secret, * label: "traffic upd", ctx: "") */ if (tls13_server_app_key_obj_id == -1) { - WOLFSSL_ERROR_MSG("MAXQ: Client Application Key was not set"); + WOLFSSL_ERROR_MSG("MAXQ: Server Application Key was not set"); return NOT_COMPILED_IN; } prk_kid = tls13_server_secret_obj_id; diff --git a/wolfcrypt/src/port/mynewt/mynewt_port.c b/wolfcrypt/src/port/mynewt/mynewt_port.c index 8ff424b3f48..9a070cadb28 100644 --- a/wolfcrypt/src/port/mynewt/mynewt_port.c +++ b/wolfcrypt/src/port/mynewt/mynewt_port.c @@ -35,39 +35,34 @@ FILE* mynewt_fopen(const char * restrict path, const char * restrict mode) FILE *file; uint8_t access_flags = 0; const char *p = mode; - while(*p != '\0') { + + while (*p != '\0') { switch(*p) { case 'r': - { access_flags |= FS_ACCESS_READ; if(*(p+1) == '+') { access_flags |= FS_ACCESS_WRITE; } - } - break; + break; case 'w': - { access_flags |= (FS_ACCESS_WRITE | FS_ACCESS_TRUNCATE); if(*(p+1) == '+') { access_flags |= FS_ACCESS_READ; } - } - break; + break; case 'a': - { access_flags |= (FS_ACCESS_WRITE | FS_ACCESS_APPEND); if(*(p+1) == '+') { access_flags |= FS_ACCESS_READ; } - } - break; + break; } p++; } - /* Open the file for reading. */ + /* Open the file for reading/writing/appending. */ int rc = fs_open(path, access_flags, &file); if (rc != 0) { return NULL; @@ -78,40 +73,50 @@ FILE* mynewt_fopen(const char * restrict path, const char * restrict mode) int mynewt_fseek(FILE *stream, long offset, int whence) { uint32_t fs_offset; + long signed_pos; - switch(whence) { + switch (whence) { case 0: /* SEEK_SET */ - { - fs_offset += offset; - } - break; + if (offset < 0) + return -1; + fs_offset = (uint32_t)offset; + break; case 1: /* SEEK_CUR */ - { fs_offset = fs_getpos(stream); - fs_offset += offset; - } - break; + if ((int32_t)fs_offset < 0) { + return -1; + } + signed_pos = (long)fs_offset + offset; + if (signed_pos < 0) + return -1; + fs_offset = (uint32_t)signed_pos; + break; case 2: /* SEEK_END */ - { - fs_filelen(stream, &fs_offset); - fs_offset += offset; - } - break; + if (fs_filelen(stream, &fs_offset) != 0) { + return -1; + } + signed_pos = (long)fs_offset + offset; + if (signed_pos < 0) + return -1; + fs_offset = (uint32_t)signed_pos; + break; + + default: + return -1; } - fs_seek(stream, fs_offset); + if (fs_seek(stream, fs_offset) != 0) { + return -1; + } return 0; } long mynewt_ftell(FILE *stream) { - uint32_t fs_offset; - fs_filelen(stream, &fs_offset); - fs_seek(stream, fs_offset); - return (long)fs_offset; + return (long)fs_getpos(stream); } void mynewt_rewind(FILE *stream) @@ -119,32 +124,48 @@ void mynewt_rewind(FILE *stream) fs_seek(stream, 0); } -size_t mynewt_fread(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream) +size_t mynewt_fread(void *restrict ptr, size_t size, size_t nitems, + FILE *restrict stream) { - size_t to_read = size * nitems; + size_t to_read; uint32_t read_size; - int rc = fs_read(stream, to_read, ptr, &read_size); - if(rc != 0) { + int rc; + + if (size == 0 || nitems == 0 || nitems > SIZE_MAX / size) + return 0; + + to_read = size * nitems; + rc = fs_read(stream, to_read, ptr, &read_size); + if (rc != 0) { return 0; } - return (size_t)read_size; + return (size_t)(read_size / size); } -size_t mynewt_fwrite(const void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream) +size_t mynewt_fwrite(const void *restrict ptr, size_t size, size_t nitems, + FILE *restrict stream) { - size_t to_write = size * nitems; - int rc = fs_write(stream, ptr, to_write); - if(rc != 0) { + size_t to_write; + int rc; + + if (size == 0 || nitems == 0 || nitems > SIZE_MAX / size) + return 0; + + to_write = size * nitems; + rc = fs_write(stream, ptr, to_write); + if (rc != 0) { return 0; } - return to_write; + return nitems; } int mynewt_fclose(FILE *stream) { - fs_close(stream); + if (fs_close(stream) != 0) { + return EOF; + } return 0; } diff --git a/wolfcrypt/src/port/nrf51.c b/wolfcrypt/src/port/nrf51.c index 90a70a33082..785b6f25e56 100644 --- a/wolfcrypt/src/port/nrf51.c +++ b/wolfcrypt/src/port/nrf51.c @@ -45,26 +45,28 @@ /* RTC */ #ifndef NO_CRYPT_BENCHMARK -static byte mRtcInitDone = 0; -static int mRtcSec = 0; +static volatile byte mRtcInitDone = 0; +static volatile int mRtcSec = 0; const nrf_drv_rtc_t rtc = NRF_DRV_RTC_INSTANCE(0); /**< Declaring an instance of nrf_drv_rtc for RTC0. */ #endif /* !NO_CRYPT_BENCHMARK */ /* AES */ #if !defined(NO_AES) && defined(WOLFSSL_NRF51_AES) && !defined(SOFTDEVICE_PRESENT) - static byte mAesInitDone = 0; + static volatile byte mAesInitDone = 0; #endif /** @brief Function for getting vector of random numbers. * - * @param[out] p_buff Pointer to unit8_t buffer for storing the bytes. - * @param[in] length Number of bytes to take from pool and place in p_buff. + * @param[out] p_buff Pointer to uint8_t buffer for storing the bytes. + * @param[in] size Number of bytes to take from pool and place in p_buff. * * @retval 0 = Success, else error */ int nrf51_random_generate(byte* output, word32 size) { - int remaining = size, length, pos = 0; + word32 remaining = size; + word32 pos = 0; + uint8_t length; uint8_t available; uint32_t err_code; @@ -73,18 +75,23 @@ int nrf51_random_generate(byte* output, word32 size) if (err_code != NRF_SUCCESS && err_code != NRF_ERROR_INVALID_STATE) { return -1; } + err_code = NRF_SUCCESS; while (remaining > 0) { available = 0; nrf_drv_rng_bytes_available(&available); /* is void */ - length = (remaining < available) ? remaining : available; + length = (remaining < (word32)available) ? (uint8_t)remaining : + available; if (length > 0) { err_code = nrf_drv_rng_rand(&output[pos], length); + if (err_code != NRF_SUCCESS) { + break; + } remaining -= length; pos += length; } - if (err_code != NRF_SUCCESS) { - break; + else { + nrf_delay_us(100); } } @@ -110,15 +117,17 @@ int nrf51_aes_set_key(const byte* key) return 0; } - +/* returns 0 on success and -1 on failure. */ int nrf51_aes_encrypt(const byte* in, const byte* key, word32 rounds, byte* out) { int ret; - uint32_t err_code = 0; #ifdef SOFTDEVICE_PRESENT + uint32_t err_code = 0; nrf_ecb_hal_data_t ecb_hal_data; #endif + (void)rounds; + /* Set key */ ret = nrf51_aes_set_key(key); if (ret != 0) { @@ -140,11 +149,14 @@ int nrf51_aes_encrypt(const byte* in, const byte* key, word32 rounds, byte* out) /* Grab result */ XMEMCPY(out, ecb_hal_data.ciphertext, SOC_ECB_CIPHERTEXT_LENGTH); #else - err_code = nrf_ecb_crypt(out, in); - err_code = err_code ? 0 : -1; + /* Returns true or false depending on operation success. */ + if (nrf_ecb_crypt(out, in)) + ret = 0; + else + ret = -1; #endif - return err_code; + return ret; } #endif /* !NO_AES && WOLFSSL_NRF51_AES */ @@ -153,8 +165,7 @@ int nrf51_aes_encrypt(const byte* in, const byte* key, word32 rounds, byte* out) #ifndef NO_CRYPT_BENCHMARK static void rtc_handler(nrf_drv_rtc_int_type_t int_type) { - if (int_type == NRF_DRV_RTC_INT_COMPARE0) - { + if (int_type == NRF_DRV_RTC_INT_COMPARE0) { mRtcSec++; nrf_drv_rtc_counter_clear(&rtc); nrf_drv_rtc_int_enable(&rtc, RTC_CHANNEL_INT_MASK(0)); @@ -202,24 +213,30 @@ static void rtc_config(void) static int rtc_get_ms(void) { /* Prescaler is 12-bit for COUNTER: frequency = (32768/(PRESCALER+1)) */ - int frequency = (32768 / (rtc_prescaler_get(rtc.p_reg) + 1)); - int counter = nrf_drv_rtc_counter_get(&rtc); + uint32_t frequency = (32768 / (rtc_prescaler_get(rtc.p_reg) + 1)); + /* Only 24-bits returned by call. */ + uint32_t counter = nrf_drv_rtc_counter_get(&rtc); /* Convert with rounding frequency to milliseconds */ - return ((counter * 1000) + (frequency / 2) ) / frequency; + return (int)((((uint64_t)counter * 1000) + (frequency / 2)) / frequency); } double current_time(int reset) { double time; + int sec; + + (void)reset; if (!mRtcInitDone) { rtc_config(); mRtcInitDone = 1; } - time = mRtcSec; - time += (double)rtc_get_ms() / 1000; + do { + sec = mRtcSec; + time = sec + ((double)rtc_get_ms() / 1000); + } while (sec != mRtcSec); return time; } diff --git a/wolfcrypt/src/port/nxp/dcp_port.c b/wolfcrypt/src/port/nxp/dcp_port.c index e582ab9ede4..2f709538500 100644 --- a/wolfcrypt/src/port/nxp/dcp_port.c +++ b/wolfcrypt/src/port/nxp/dcp_port.c @@ -366,7 +366,7 @@ int wc_Sha256GetHash(wc_Sha256* sha256, byte* hash) else XMEMCPY(&sha256->ctx, &saved_ctx, sizeof(dcp_hash_ctx_t)); dcp_unlock(); - return 0; + return ret; } int wc_Sha256Final(wc_Sha256* sha256, byte* hash) @@ -379,7 +379,7 @@ int wc_Sha256Final(wc_Sha256* sha256, byte* hash) ret = WC_HW_E; else { ret = DCP_HASH_Init(DCP, &sha256->handle, &sha256->ctx, kDCP_Sha256); - if (ret < 0) + if (ret != kStatus_Success) ret = WC_HW_E; } dcp_unlock(); @@ -478,7 +478,7 @@ int wc_ShaGetHash(wc_Sha* sha, byte* hash) else XMEMCPY(&sha->ctx, &saved_ctx, sizeof(dcp_hash_ctx_t)); dcp_unlock(); - return 0; + return ret; } int wc_ShaFinal(wc_Sha* sha, byte* hash) @@ -491,7 +491,7 @@ int wc_ShaFinal(wc_Sha* sha, byte* hash) ret = WC_HW_E; } else { ret = DCP_HASH_Init(DCP, &sha->handle, &sha->ctx, kDCP_Sha1); - if (ret < 0) + if (ret != kStatus_Success) ret = WC_HW_E; } dcp_unlock(); diff --git a/wolfcrypt/src/port/nxp/ksdk_port.c b/wolfcrypt/src/port/nxp/ksdk_port.c index 1d134c56a2f..d8fe888cd18 100644 --- a/wolfcrypt/src/port/nxp/ksdk_port.c +++ b/wolfcrypt/src/port/nxp/ksdk_port.c @@ -185,6 +185,9 @@ int mp_mul(mp_int *A, mp_int *B, mp_int *C) } } } + else { + res = MP_MEM; + } XFREE(ptrA, NULL, DYNAMIC_TYPE_BIGINT); XFREE(ptrB, NULL, DYNAMIC_TYPE_BIGINT); @@ -547,7 +550,7 @@ int ltc_mp_exptmod(mp_int *G, mp_int *X, mp_int *P, mp_int *Y, int useConstTime) res = LTC_PKHA_ModExp(LTC_BASE, ptrG, sizeG, /* integer input */ ptrP, sizeP, /* modulus */ - ptrX, sizeX, /* expenoent */ + ptrX, sizeX, /* exponent */ ptrY, &sizeY, /* out */ kLTC_PKHA_IntegerArith, kLTC_PKHA_NormalValue, useConstTime ? kLTC_PKHA_TimingEqualized : diff --git a/wolfcrypt/src/port/nxp/se050_port.c b/wolfcrypt/src/port/nxp/se050_port.c index e244ea35a95..5835c1304af 100644 --- a/wolfcrypt/src/port/nxp/se050_port.c +++ b/wolfcrypt/src/port/nxp/se050_port.c @@ -72,7 +72,7 @@ /* Global variables */ static sss_session_t *cfg_se050_i2c_pi; static sss_key_store_t *gHostKeyStore; -static sss_key_store_t *gHeyStore; +static sss_key_store_t *gKeyStore; int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, sss_key_store_t *pKeyStore) @@ -81,7 +81,7 @@ int wc_se050_set_config(sss_session_t *pSession, sss_key_store_t *pHostKeyStore, cfg_se050_i2c_pi = pSession; gHostKeyStore = pHostKeyStore; - gHeyStore = pKeyStore; + gKeyStore = pKeyStore; return 0; } @@ -294,9 +294,6 @@ int se050_hash_update(SE050_HASH_Context* se050Ctx, const byte* data, word32 len XFREE(se050Ctx->msg, se050Ctx->heap, DYNAMIC_TYPE_TMP_BUFFER); se050Ctx->msg = tmp; } - if (se050Ctx->msg == NULL) { - return MEMORY_E; - } se050Ctx->len = usedSz; } @@ -395,6 +392,7 @@ int se050_aes_set_key(Aes* aes, const byte* key, word32 keylen, /* free existing key in slot first before storing new one */ ret = wc_se050_erase_object(aes->keyId); if (ret != 0) { + wolfSSL_CryptHwMutexUnLock(); return ret; } aes->keyIdSet = 0; @@ -1177,6 +1175,7 @@ int se050_rsa_sign(const byte* in, word32 inLen, byte* out, algorithm = se050_get_rsa_signature_type(pad_type, hash, mgf); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); + wolfSSL_CryptHwMutexUnLock(); return BAD_FUNC_ARG; } @@ -1229,7 +1228,7 @@ int se050_rsa_sign(const byte* in, word32 inLen, byte* out, derSz, (keySz * 8), NULL, 0); } - XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } else { status = sss_key_object_get_handle(&newKey, keyId); @@ -1332,6 +1331,7 @@ int se050_rsa_verify(const byte* in, word32 inLen, byte* out, word32 outLen, algorithm = se050_get_rsa_signature_type(pad_type, hash, mgf); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); + wolfSSL_CryptHwMutexUnLock(); return BAD_FUNC_ARG; } @@ -1391,7 +1391,7 @@ int se050_rsa_verify(const byte* in, word32 inLen, byte* out, word32 outLen, derSz, (keySz * 8), NULL, 0); } - XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } else { status = sss_key_object_get_handle(&newKey, keyId); @@ -1520,6 +1520,7 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, algorithm = se050_get_rsa_encrypt_type(pad_type, hash); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); + wolfSSL_CryptHwMutexUnLock(); return BAD_FUNC_ARG; } @@ -1576,7 +1577,7 @@ int se050_rsa_public_encrypt(const byte* in, word32 inLen, byte* out, status = sss_key_object_get_handle(&newKey, keyId); } - XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (status == kStatus_SSS_Success) { @@ -1678,6 +1679,7 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, algorithm = se050_get_rsa_encrypt_type(pad_type, hash); if (algorithm == kAlgorithm_None) { WOLFSSL_MSG("Unsupported padding/hash/mgf combination for SE050"); + wolfSSL_CryptHwMutexUnLock(); return BAD_FUNC_ARG; } @@ -1741,7 +1743,7 @@ int se050_rsa_private_decrypt(const byte* in, word32 inLen, byte* out, status = sss_key_object_get_handle(&newKey, keyId); } - XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER); } if (status == kStatus_SSS_Success) { diff --git a/wolfcrypt/src/port/pic32/pic32mz-crypt.c b/wolfcrypt/src/port/pic32/pic32mz-crypt.c index ba764f6cd0e..75be92b306e 100644 --- a/wolfcrypt/src/port/pic32/pic32mz-crypt.c +++ b/wolfcrypt/src/port/pic32/pic32mz-crypt.c @@ -245,22 +245,26 @@ static int Pic32Crypto(const byte* pIn, int inLen, word32* pOut, int outLen, wolfSSL_CryptHwMutexUnLock(); - /* copy result to output */ - #if PIC32_NO_OUT_SWAP - /* swap bytes */ - ByteReverseWords(out, (word32*)out_p, outLen); - #elif defined(_SYS_DEVCON_LOCAL_H) - /* sync cache */ - SYS_DEVCON_DataCacheInvalidate((word32)out, outLen); - #else - XMEMCPY(out, out_p, outLen); - #endif + if (ret == 0) { + /* copy result to output */ + #if PIC32_NO_OUT_SWAP + /* swap bytes */ + ByteReverseWords(out, (word32*)out_p, outLen); + #elif defined(_SYS_DEVCON_LOCAL_H) + /* sync cache */ + SYS_DEVCON_DataCacheInvalidate((word32)out, outLen); + #else + XMEMCPY(out, out_p, outLen); + #endif + } } /* handle unaligned */ if (isDynamic) { - /* return result */ - XMEMCPY(pOut, out, outLen); + if (ret == 0) { + /* return result */ + XMEMCPY(pOut, out, outLen); + } /* free dynamic buffers */ XFREE(in, NULL, DYNAMIC_TYPE_AES_BUFFER); @@ -308,11 +312,14 @@ typedef struct { static pic32mz_desc gLHDesc __attribute__((coherent)); static uint8_t gLHDataBuf[PIC32MZ_MAX_BD][PIC32_BLOCK_SIZE] __attribute__((aligned (4), coherent)); -static void reset_engine(int algo) +static int reset_engine(int algo) { int i; + int ret; - wolfSSL_CryptHwMutexLock(); + ret = wolfSSL_CryptHwMutexLock(); + if (ret != 0) + return ret; /* Software reset */ CECON = 1 << 6; @@ -360,11 +367,16 @@ static void reset_engine(int algo) #else CECON = 0xa7; #endif + + return 0; } -static void update_engine(const byte *input, word32 len, word32 *hash) +#define ENGINE_MAX_CHECKS 0xffffff + +static int update_engine(const byte *input, word32 len, word32 *hash) { int total; + int checks; gLHDesc.bd[gLHDesc.currBd].UPDPTR = KVA_TO_PA(hash); @@ -386,7 +398,11 @@ static void update_engine(const byte *input, word32 len, word32 *hash) if (gLHDesc.currBd >= PIC32MZ_MAX_BD) gLHDesc.currBd = 0; /* Wait until the engine has processed the new BD. */ - while (gLHDesc.bd[gLHDesc.currBd].BD_CTRL.DESC_EN); + checks = 0; + while (gLHDesc.bd[gLHDesc.currBd].BD_CTRL.DESC_EN && + ++checks < ENGINE_MAX_CHECKS) ; + if (checks == ENGINE_MAX_CHECKS) + return -1; gLHDesc.bd[gLHDesc.currBd].UPDPTR = KVA_TO_PA(hash); gLHDesc.dbPtr = 0; } @@ -416,6 +432,8 @@ static void update_engine(const byte *input, word32 len, word32 *hash) } } } + + return 0; } static void start_engine(void) @@ -435,27 +453,34 @@ static void start_engine(void) gLHDesc.bd[gLHDesc.currBd].BD_CTRL.DESC_EN = 1; } -void wait_engine(char *hash, int hash_sz) +static int wait_engine(word32 *hash, word32 hash_sz) { int i; unsigned int engineRunning; + int checks = 0; do { engineRunning = 0; for (i = 0; i < PIC32MZ_MAX_BD; i++) { engineRunning = engineRunning || gLHDesc.bd[i].BD_CTRL.DESC_EN; } - } while (engineRunning); + } while (engineRunning && (++checks < ENGINE_MAX_CHECKS)); -#if PIC32_NO_OUT_SWAP - /* swap bytes */ - ByteReverseWords(hash, KVA0_TO_KVA1(hash), hash_sz); -#else - /* copy output - hardware already swapped */ - XMEMCPY(hash, KVA0_TO_KVA1(hash), hash_sz); -#endif + if (!engineRunning) { + #if PIC32_NO_OUT_SWAP + /* swap bytes */ + ByteReverseWords(hash, KVA0_TO_KVA1(hash), hash_sz); + #else + /* copy output - hardware already swapped */ + XMEMCPY(hash, KVA0_TO_KVA1(hash), hash_sz); + #endif + } wolfSSL_CryptHwMutexUnLock(); + + if (engineRunning) + return -1; + return 0; } #endif /* WOLFSSL_PIC32MZ_LARGE_HASH */ @@ -487,10 +512,15 @@ static int wc_Pic32HashUpdate(hashUpdCache* cache, byte* stdBuf, int stdBufLen, /* if final length is set then pass straight to hardware */ if (cache->finalLen) { if (cache->bufLen == 0) { - reset_engine(algo); + ret = reset_engine(algo); + if (ret != 0) + return ret; gLHDesc.msgSize = cache->finalLen; } - update_engine(data, len, digest); + if (update_engine(data, len, digest) != 0) { + wolfSSL_CryptHwMutexUnLock(); + return ASYNC_OP_E; + } cache->bufLen += len; /* track progress for blockType */ return 0; } @@ -498,7 +528,9 @@ static int wc_Pic32HashUpdate(hashUpdCache* cache, byte* stdBuf, int stdBufLen, /* cache updates */ /* calculate new len */ - newLenUpd = cache->updLen + len; + newLenUpd = (word32)cache->updLen + (word32)len; + if (newLenUpd < (word32)cache->updLen) + return MEMORY_E; /* calculate padded len - pad buffer at 64-bytes for hardware */ newLenPad = newLenUpd; @@ -561,7 +593,13 @@ static int wc_Pic32HashFinal(hashUpdCache* cache, byte* stdBuf, /* Only submit to hardware if update data provided matches expected */ if (cache->bufLen == cache->finalLen) { start_engine(); - wait_engine((char*)digest, digestSz); + if (wait_engine(digest, (word32)digestSz) != 0) { + if (cache->buf && cache->buf != stdBuf && !cache->isCopy) { + XFREE(cache->buf, heap, DYNAMIC_TYPE_HASH_TMP); + cache->buf = NULL; + } + return ASYNC_OP_E; + } XMEMCPY(hash, digest, digestSz); } else { diff --git a/wolfcrypt/src/port/psa/psa.c b/wolfcrypt/src/port/psa/psa.c index 72e74bbae72..2537bd68a68 100644 --- a/wolfcrypt/src/port/psa/psa.c +++ b/wolfcrypt/src/port/psa/psa.c @@ -58,7 +58,11 @@ int wc_psa_init() psa_status_t s; #if defined(WOLFSSL_PSA_GLOBAL_LOCK) - wc_InitMutex(&psa_global_mutex); + int ret; + + ret = wc_InitMutex(&psa_global_mutex); + if (ret != 0) + return ret; #endif PSA_LOCK(); diff --git a/wolfcrypt/src/port/psa/psa_aes.c b/wolfcrypt/src/port/psa/psa_aes.c index 50f4a981d50..b789d0860fe 100644 --- a/wolfcrypt/src/port/psa/psa_aes.c +++ b/wolfcrypt/src/port/psa/psa_aes.c @@ -48,7 +48,7 @@ static int wc_psa_aes_import_key(Aes *aes, const uint8_t *key, psa_status_t s; XMEMSET(&key_attr, 0, sizeof(key_attr)); - aes->key_id = 0; + aes->key_id = PSA_KEY_ID_NULL; aes->ctx_initialized = 0; psa_set_key_type(&key_attr, PSA_KEY_TYPE_AES); @@ -76,7 +76,7 @@ static int wc_psa_aes_import_key(Aes *aes, const uint8_t *key, */ int wc_psa_aes_init(Aes *aes) { - aes->key_id = 0; + aes->key_id = PSA_KEY_ID_NULL; aes->ctx_initialized = 0; aes->key_need_importing = 0; XMEMSET(&aes->psa_ctx, 0, sizeof(aes->psa_ctx)); @@ -167,9 +167,7 @@ int wc_psa_aes_set_key(Aes *aes, const uint8_t *key, size_t key_length, XMEMCPY(aes->key, key, key_length); aes->key_need_importing = 1; } else { - PSA_LOCK(); ret = wc_psa_aes_import_key(aes, key, key_length, alg, dir); - PSA_UNLOCK(); if (ret != 0) return ret; } @@ -227,11 +225,10 @@ int wc_psa_aes_encrypt_decrypt(Aes *aes, const uint8_t *input, PSA_UNLOCK(); } + aes->ctx_initialized = 1; /* mark before error check so err: path aborts it */ if (s != PSA_SUCCESS) goto err; - aes->ctx_initialized = 1; - /* ECB doesn't use IV */ if (alg != PSA_ALG_ECB_NO_PADDING) { @@ -284,7 +281,6 @@ int wc_psa_aes_free(Aes *aes) aes->ctx_initialized = 0; } - aes->ctx_initialized = 0; aes->key_need_importing = 0; return 0; diff --git a/wolfcrypt/src/port/psa/psa_hash.c b/wolfcrypt/src/port/psa/psa_hash.c index f9e13a5f3df..d072a40870b 100644 --- a/wolfcrypt/src/port/psa/psa_hash.c +++ b/wolfcrypt/src/port/psa/psa_hash.c @@ -127,9 +127,12 @@ static int wc_psa_hash_clone(const psa_hash_operation_t *src, return BAD_FUNC_ARG; PSA_LOCK(); - psa_hash_abort(dst); + s = psa_hash_abort(dst); PSA_UNLOCK(); + if (s != PSA_SUCCESS) + return WC_HW_E; + PSA_LOCK(); s = psa_hash_clone(src, dst); PSA_UNLOCK(); @@ -173,7 +176,9 @@ static int wc_psa_get_hash(psa_hash_operation_t *ctx, s = psa_hash_clone(ctx, &tmp); PSA_UNLOCK(); if (s != PSA_SUCCESS) { + PSA_LOCK(); psa_hash_abort(&tmp); + PSA_UNLOCK(); return WC_HW_E; } diff --git a/wolfcrypt/src/port/psa/psa_pkcbs.c b/wolfcrypt/src/port/psa/psa_pkcbs.c index 9a0f2037f9b..2a155e9dae5 100644 --- a/wolfcrypt/src/port/psa/psa_pkcbs.c +++ b/wolfcrypt/src/port/psa/psa_pkcbs.c @@ -138,7 +138,7 @@ static int psa_ecc_keygen_cb(WOLFSSL* ssl, struct ecc_key* key, ret = psa_ecc_keygen(ecc_curve, key_size, &psa_key_id); if (ret != 0) - return WC_HW_E; + return ret; ret = psa_ecc_export_to_wc_key(key, psa_key_id, ecc_curve); if (ret != 0) { @@ -148,6 +148,11 @@ static int psa_ecc_keygen_cb(WOLFSSL* ssl, struct ecc_key* key, return WC_HW_E; } + if (psa_ctx->dh_key != PSA_KEY_ID_NULL) { + PSA_LOCK(); + psa_destroy_key(psa_ctx->dh_key); + PSA_UNLOCK(); + } psa_ctx->dh_key = psa_key_id; return 0; @@ -239,6 +244,12 @@ static int psa_ecc_shared_secret_cb(WOLFSSL* ssl, struct ecc_key* other_key, &output_length); PSA_UNLOCK(); + PSA_LOCK(); + psa_destroy_key(psa_ctx->dh_key); + PSA_UNLOCK(); + + psa_ctx->dh_key = PSA_KEY_ID_NULL; + if (status != PSA_SUCCESS) { WOLFSSL_MSG("PSA: error raw_key_agreement"); return WC_HW_E; @@ -246,12 +257,6 @@ static int psa_ecc_shared_secret_cb(WOLFSSL* ssl, struct ecc_key* other_key, *output_size = (word32)output_length; - PSA_LOCK(); - psa_destroy_key(psa_ctx->dh_key); - PSA_UNLOCK(); - - psa_ctx->dh_key = PSA_KEY_ID_NULL; - return 0; } @@ -305,11 +310,15 @@ static int psa_ecc_sign_cb(WOLFSSL* ssl, const unsigned char* input, /* Get correct hash algorithm that matches input hash length */ hash_algo = psa_map_hash_alg(input_length); + if (hash_algo == PSA_ALG_NONE) + return BAD_FUNC_ARG; + PSA_LOCK(); status = psa_sign_hash(psa_ctx->private_key, PSA_ALG_ECDSA(hash_algo), input, input_length, rs, sizeof(rs), &rs_length); + PSA_UNLOCK(); if (status != PSA_SUCCESS) return WC_HW_E; @@ -317,7 +326,7 @@ static int psa_ecc_sign_cb(WOLFSSL* ssl, const unsigned char* input, ret = wc_ecc_rs_raw_to_sig(rs, point_len, rs + point_len, point_len, signature, signature_size); if (ret != 0) - return -1; + return ret; return 0; } @@ -391,8 +400,12 @@ static int psa_ecc_verify_cb(WOLFSSL* ssl, const byte* sig, word32 sig_length, (void)ctx; WOLFSSL_ENTER("psa_ecc_verify_cb"); + *result = 0; + /* Get correct hash algorithm that matches input hash length */ hash_algo = psa_map_hash_alg(hash_length); + if (hash_algo == PSA_ALG_NONE) + return BAD_FUNC_ARG; ret = psa_ecc_decode_public_key(key, key_length, &tmp_key, hash_algo); if (ret != 0) @@ -406,7 +419,7 @@ static int psa_ecc_verify_cb(WOLFSSL* ssl, const byte* sig, word32 sig_length, goto exit; /* coalescence of r and s in the buffer */ - XMEMCPY(raw_signature + r_len, s, s_len); + XMEMMOVE(raw_signature + r_len, s, s_len); PSA_LOCK(); status = psa_verify_hash(tmp_key, PSA_ALG_ECDSA(hash_algo), hash, @@ -416,8 +429,6 @@ static int psa_ecc_verify_cb(WOLFSSL* ssl, const byte* sig, word32 sig_length, if (status == PSA_SUCCESS) { *result = 1; } else { - *result = 0; - if (status != PSA_ERROR_INVALID_SIGNATURE) { WOLFSSL_MSG("psa_ecc_verify_cb: can't verify hash"); ret = WC_HW_E; @@ -436,6 +447,7 @@ static int psa_ecc_verify_cb(WOLFSSL* ssl, const byte* sig, word32 sig_length, #endif /* HAVE_ECC */ #ifdef HAVE_HKDF +/* ikm will always be not NULL. */ static int psa_hkdf_extract_cb(byte* prk, const byte* salt, word32 salt_length, byte* ikm, word32 ikm_length, int digest, @@ -532,7 +544,7 @@ int wolfSSL_psa_set_private_key_id(struct psa_ssl_ctx *ctx, psa_key_id_t id) void wolfSSL_free_psa_ctx(struct psa_ssl_ctx *ctx) { - if (ctx->dh_key != PSA_KEY_ID_NULL) { + if (ctx != NULL && ctx->dh_key != PSA_KEY_ID_NULL) { PSA_LOCK(); psa_destroy_key(ctx->dh_key); PSA_UNLOCK(); diff --git a/wolfcrypt/src/port/rpi_pico/pico.c b/wolfcrypt/src/port/rpi_pico/pico.c index 1b7a61e6878..adf3b94b7b7 100644 --- a/wolfcrypt/src/port/rpi_pico/pico.c +++ b/wolfcrypt/src/port/rpi_pico/pico.c @@ -41,6 +41,9 @@ int wc_pico_rng_gen_block(unsigned char *output, unsigned int sz) { uint32_t i = 0; + if (output == NULL || sz == 0) + return BAD_FUNC_ARG; + while (i < sz) { uint64_t rnd = get_rand_64(); @@ -52,6 +55,7 @@ int wc_pico_rng_gen_block(unsigned char *output, unsigned int sz) XMEMCPY(output + i, &rnd, sz - i); i = sz; } + rnd = 0; } return 0; diff --git a/wolfcrypt/src/port/silabs/silabs_aes.c b/wolfcrypt/src/port/silabs/silabs_aes.c index 47d5172d730..04cceb554ce 100644 --- a/wolfcrypt/src/port/silabs/silabs_aes.c +++ b/wolfcrypt/src/port/silabs/silabs_aes.c @@ -43,18 +43,20 @@ int wc_AesSetKey(Aes* aes, const byte* userKey, word32 keylen, int ret = 0; (void)dir; - ret = sl_se_init(); - if (ret != SL_STATUS_OK) { - return BUFFER_E; + if (aes == NULL || userKey == NULL || keylen > sizeof(aes->key)) { + return BAD_FUNC_ARG; } - if (aes == NULL || keylen > sizeof(aes->key)) { - return BAD_FUNC_ARG; + ret = sl_se_init(); + if (ret != SL_STATUS_OK) { + return WC_HW_E; } XMEMSET(aes, 0, sizeof(*aes)); ret = wc_AesSetIV(aes, iv); + if (ret != 0) + return ret; aes->rounds = keylen/4 + 6; aes->ctx.cmd_ctx = cc; @@ -80,11 +82,12 @@ int wc_AesSetKey(Aes* aes, const byte* userKey, word32 keylen, break; } - - XMEMCPY(aes->key, userKey, keylen); - aes->ctx.key.storage.location.buffer.pointer = (void*)aes->key; - aes->ctx.key.storage.location.buffer.size = keylen; - aes->ctx.key.size = keylen; + if (ret == 0) { + XMEMCPY(aes->key, userKey, keylen); + aes->ctx.key.storage.location.buffer.pointer = (void*)aes->key; + aes->ctx.key.storage.location.buffer.size = keylen; + aes->ctx.key.size = keylen; + } return ret; } @@ -134,7 +137,12 @@ int wc_AesEcbDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) #ifdef WOLFSSL_AES_DIRECT int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock) { - sl_status_t status = sl_se_aes_crypt_ecb( + sl_status_t status; + if ((inBlock == NULL) || (outBlock == NULL) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_aes_crypt_ecb( &(aes->ctx.cmd_ctx), &(aes->ctx.key), SL_SE_ENCRYPT, @@ -146,7 +154,12 @@ int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock) int wc_AesDecrypt(Aes* aes, const byte* inBlock, byte* outBlock) { - sl_status_t status = sl_se_aes_crypt_ecb( + sl_status_t status; + if ((inBlock == NULL) || (outBlock == NULL) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_aes_crypt_ecb( &(aes->ctx.cmd_ctx), &(aes->ctx.key), SL_SE_DECRYPT, @@ -159,7 +172,12 @@ int wc_AesDecrypt(Aes* aes, const byte* inBlock, byte* outBlock) int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - sl_status_t status = sl_se_aes_crypt_cbc( + sl_status_t status; + if ((in == NULL) || (out == NULL) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_aes_crypt_cbc( &(aes->ctx.cmd_ctx), &(aes->ctx.key), SL_SE_ENCRYPT, @@ -172,7 +190,12 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) int wc_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz) { - sl_status_t status = sl_se_aes_crypt_cbc( + sl_status_t status; + if ((in == NULL) || (out == NULL) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_aes_crypt_cbc( &(aes->ctx.cmd_ctx), &(aes->ctx.key), SL_SE_DECRYPT, @@ -189,7 +212,13 @@ int wc_AesGcmEncrypt_silabs (Aes* aes, byte* out, const byte* in, word32 sz, byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - sl_status_t status = sl_se_gcm_crypt_and_tag( + sl_status_t status; + if ((in == NULL) || (out == NULL) || (iv == NULL) || (authTag == NULL) || + (authIn == NULL && authInSz != 0) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_gcm_crypt_and_tag( &(aes->ctx.cmd_ctx), &(aes->ctx.key), SL_SE_ENCRYPT, @@ -211,7 +240,13 @@ int wc_AesGcmDecrypt_silabs (Aes* aes, byte* out, const byte* in, word32 sz, const byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - sl_status_t status = sl_se_gcm_auth_decrypt( + sl_status_t status; + if ((in == NULL) || (out == NULL) || (iv == NULL) || (authTag == NULL) || + (authIn == NULL && authInSz != 0) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_gcm_auth_decrypt( &(aes->ctx.cmd_ctx), &(aes->ctx.key), sz, @@ -236,7 +271,13 @@ int wc_AesCcmEncrypt_silabs (Aes* aes, byte* out, const byte* in, word32 sz, byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - sl_status_t status = sl_se_ccm_encrypt_and_tag( + sl_status_t status; + if ((in == NULL) || (out == NULL) || (iv == NULL) || (authTag == NULL) || + (authIn == NULL && authInSz != 0) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_ccm_encrypt_and_tag( &(aes->ctx.cmd_ctx), &(aes->ctx.key), sz, @@ -258,7 +299,13 @@ int wc_AesCcmDecrypt_silabs (Aes* aes, byte* out, const byte* in, word32 sz, const byte* authTag, word32 authTagSz, const byte* authIn, word32 authInSz) { - sl_status_t status = sl_se_ccm_auth_decrypt( + sl_status_t status; + if ((in == NULL) || (out == NULL) || (iv == NULL) || (authTag == NULL) || + (authIn == NULL && authInSz != 0) || (aes == NULL)) { + return BAD_FUNC_ARG; + } + + status = sl_se_ccm_auth_decrypt( &(aes->ctx.cmd_ctx), &(aes->ctx.key), sz, @@ -274,6 +321,6 @@ int wc_AesCcmDecrypt_silabs (Aes* aes, byte* out, const byte* in, word32 sz, return (status != SL_STATUS_OK) ? AES_GCM_AUTH_E : 0; } -#endif /* HAVE_AESGCM */ +#endif /* HAVE_AESCCM */ #endif /* WOLFSSL_SILABS_SE_ACCEL */ diff --git a/wolfcrypt/src/port/silabs/silabs_ecc.c b/wolfcrypt/src/port/silabs/silabs_ecc.c index 6b61ccecaa1..f96e098133e 100644 --- a/wolfcrypt/src/port/silabs/silabs_ecc.c +++ b/wolfcrypt/src/port/silabs/silabs_ecc.c @@ -100,8 +100,15 @@ int silabs_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, ecc_key* key) { sl_status_t sl_stat; - sl_se_key_descriptor_t* slkey = &key->key; - word32 siglen = *outlen; + sl_se_key_descriptor_t* slkey; + word32 siglen; + + if (in == NULL || out == NULL || outlen == NULL || key == NULL || + key->dp == NULL) + return BAD_FUNC_ARG; + + slkey = &key->key; + siglen = *outlen; if ((int)siglen >= key->dp->size * 2) { siglen = key->dp->size * 2; @@ -140,7 +147,12 @@ int silabs_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, word32 hashlen, int* stat, ecc_key* key) { - sl_status_t sl_stat = sl_se_init_command_context(&key->cmd_ctx); + sl_status_t sl_stat; + + if (sig == NULL || hash == NULL || stat == NULL || key == NULL) + return BAD_FUNC_ARG; + + sl_stat = sl_se_init_command_context(&key->cmd_ctx); if (sl_stat == SL_STATUS_OK) { sl_stat = sl_se_ecc_verify( &key->cmd_ctx, @@ -167,6 +179,9 @@ int silabs_ecc_make_key(ecc_key* key, int keysize) { sl_status_t sl_stat; + if (key == NULL || key->dp == NULL) + return BAD_FUNC_ARG; + key->key.type = silabs_map_key_type(key->dp->id); if (key->key.type == SILABS_UNSUPPORTED_KEY_TYPE) return WC_HW_E; @@ -177,12 +192,14 @@ int silabs_ecc_make_key(ecc_key* key, int keysize) SL_SE_KEY_FLAG_ASYMMETRIC_BUFFER_HAS_PUBLIC_KEY | SL_SE_KEY_FLAG_ASYMMETRIC_SIGNING_ONLY); - sl_stat = sl_se_get_storage_size(&key->key, - &key->key.storage.location.buffer.size); + sl_stat = sl_se_init_command_context(&key->cmd_ctx); + if (sl_stat == SL_STATUS_OK) { + sl_stat = sl_se_get_storage_size(&key->key, + &key->key.storage.location.buffer.size); + } if (sl_stat == SL_STATUS_OK) { key->key.storage.location.buffer.pointer = key->key_raw; - sl_stat = sl_se_generate_key(&key->cmd_ctx, - &key->key); + sl_stat = sl_se_generate_key(&key->cmd_ctx, &key->key); } if (sl_stat == SL_STATUS_OK) { key->type = ECC_PRIVATEKEY; @@ -205,6 +222,9 @@ int silabs_ecc_import(ecc_key* key, word32 keysize, int pub, int priv) int err = MP_OKAY; word32 used; + if (key == NULL || key->dp == NULL) + return BAD_FUNC_ARG; + key->key.type = silabs_map_key_type(key->dp->id); if (key->key.type == SILABS_UNSUPPORTED_KEY_TYPE || keysize == 0) return WC_HW_E; @@ -260,6 +280,11 @@ int silabs_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, uint32_t pub_sz = 0; sl_status_t sl_stat; + if ((private_key == NULL) || (public_key == NULL) || (out == NULL) || + (outlen == NULL)) { + return BAD_FUNC_ARG; + } + /* `sl_se_ecdh_compute_shared_secret` returns the full coordinate * point, but `wc_ecc_shared_secret` should only return the x * coordinate. This buffer is used to hold the output of the @@ -284,17 +309,20 @@ int silabs_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, key_out.size = pub_sz; key_out.storage.location.buffer.size = pub_sz; - sl_stat = sl_se_ecdh_compute_shared_secret( - &cmd, - &private_key->key, - &pub_key, - &key_out); - + sl_stat = sl_se_init_command_context(&cmd); + if (sl_stat == SL_STATUS_OK) { + sl_stat = sl_se_ecdh_compute_shared_secret( + &cmd, + &private_key->key, + &pub_key, + &key_out); + } if (sl_stat == SL_STATUS_OK) { *outlen = pub_key.size; XMEMCPY(out, fullpoint, *outlen); } + ForceZero(fullpoint, sizeof(fullpoint)); return (sl_stat == SL_STATUS_OK) ? 0 : WC_HW_E; } @@ -304,7 +332,7 @@ int silabs_ecc_export_public(ecc_key* key, sl_se_key_descriptor_t* seKey) sl_status_t sl_stat; sl_se_command_context_t cmd; - if (key == NULL || seKey == NULL) + if (key == NULL || key->dp == NULL || seKey == NULL) return BAD_FUNC_ARG; if (seKey->type == SL_SE_KEY_TYPE_ECC_P192) @@ -324,16 +352,19 @@ int silabs_ecc_export_public(ecc_key* key, sl_se_key_descriptor_t* seKey) if (ret != 0) return ret; - key->type = ECC_PUBLICKEY; - key->key.type = seKey->type; - key->key.size = key->dp->size; - key->key.storage.method = SL_SE_KEY_STORAGE_EXTERNAL_PLAINTEXT; - key->key.flags = (SL_SE_KEY_FLAG_ASYMMETRIC_BUFFER_HAS_PUBLIC_KEY | - SL_SE_KEY_FLAG_ASYMMETRIC_SIGNING_ONLY); - - sl_stat = sl_se_get_storage_size(&key->key, - &key->key.storage.location.buffer.size); - key->key.storage.location.buffer.pointer = key->key_raw; + sl_stat = sl_se_init_command_context(&cmd); + if (sl_stat == SL_STATUS_OK) { + key->type = ECC_PUBLICKEY; + key->key.type = seKey->type; + key->key.size = key->dp->size; + key->key.storage.method = SL_SE_KEY_STORAGE_EXTERNAL_PLAINTEXT; + key->key.flags = (SL_SE_KEY_FLAG_ASYMMETRIC_BUFFER_HAS_PUBLIC_KEY | + SL_SE_KEY_FLAG_ASYMMETRIC_SIGNING_ONLY); + + sl_stat = sl_se_get_storage_size(&key->key, + &key->key.storage.location.buffer.size); + key->key.storage.location.buffer.pointer = key->key_raw; + } if (sl_stat == SL_STATUS_OK) { sl_stat = sl_se_export_public_key(&cmd, seKey, &key->key); } diff --git a/wolfcrypt/src/port/silabs/silabs_random.c b/wolfcrypt/src/port/silabs/silabs_random.c index f2c39017d6f..d0fa63df868 100644 --- a/wolfcrypt/src/port/silabs/silabs_random.c +++ b/wolfcrypt/src/port/silabs/silabs_random.c @@ -37,12 +37,16 @@ int silabs_GenerateRand(byte* output, word32 sz) { sl_se_command_context_t cmd_ctx = SL_SE_COMMAND_CONTEXT_INIT; - sl_status_t status = sl_se_init(); + sl_status_t status; + if (output == NULL) + return BAD_FUNC_ARG; + + status = sl_se_init(); if (status == SL_STATUS_OK) status = sl_se_get_random(&cmd_ctx, output, sz); - return (status != SL_STATUS_OK); + return (status != SL_STATUS_OK) ? WC_HW_E : 0; } #endif /* WOLFSSL_SILABS_SE_ACCEL */ diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 429c256a6fe..644b85634f7 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -518,6 +518,7 @@ static void wc_Stm32_Hmac_FeedKey(const byte* key, word32 keySz) keySz % STM32_HASH_REG_SIZE); HASH->DIN = tmp; } + ForceZero(&tmp, sizeof(tmp)); #ifdef DEBUG_STM32_HASH printf("STM HMAC FeedKey %d bytes\n", (int)keySz); @@ -692,6 +693,7 @@ int wc_Stm32_Aes_Wrap(struct Aes* aes, const byte* in, word32 inSz, byte* out, ret = HAL_CRYPEx_WrapKey(&hcryp, (uint32_t*)key, (uint32_t*)out, 100); HAL_CRYP_DeInit(&hcryp); } + ForceZero(key, sizeof(key)); ByteReverseWords((word32*)out, (word32*)out, inSz); *outSz = inSz; @@ -1095,8 +1097,10 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, } } #endif - if (res != MP_OKAY) + if (res != MP_OKAY) { + ForceZero(kbin, sizeof(kbin)); return res; + } pka_mul.modulusSize = szModulus; pka_mul.coefSign = coefA_sign; @@ -1113,12 +1117,14 @@ int wc_ecc_mulmod_ex2(const mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, status = HAL_PKA_ECCMul(&hpka, &pka_mul, HAL_MAX_DELAY); if (status != HAL_OK) { + ForceZero(kbin, sizeof(kbin)); HAL_PKA_RAMReset(&hpka); return WC_HW_E; } pka_mul_res.ptX = Gxbin; pka_mul_res.ptY = Gybin; HAL_PKA_ECCMul_GetResult(&hpka, &pka_mul_res); + ForceZero(kbin, sizeof(kbin)); res = mp_read_unsigned_bin(R->x, Gxbin, szModulus); if (res == MP_OKAY) { res = mp_read_unsigned_bin(R->y, Gybin, szModulus); @@ -1309,13 +1315,18 @@ int stm32_ecc_sign_hash_ex(const byte* hash, word32 hashlen, WC_RNG* rng, status = stm32_get_from_mp_int(Intbin, &gen_k, size); mp_clear(&gen_k); mp_clear(&order_mp); - if (status != MP_OKAY) + if (status != MP_OKAY) { + ForceZero(Intbin, sizeof(Intbin)); return status; + } /* get private part of "k" */ status = stm32_get_from_mp_int(Keybin, wc_ecc_key_get_priv(key), size); - if (status != MP_OKAY) + if (status != MP_OKAY) { + ForceZero(Keybin, sizeof(Keybin)); + ForceZero(Intbin, sizeof(Intbin)); return status; + } pka_ecc.primeOrderSize = size; pka_ecc.modulusSize = size; @@ -1331,6 +1342,8 @@ int stm32_ecc_sign_hash_ex(const byte* hash, word32 hashlen, WC_RNG* rng, XMEMSET(Hashbin, 0, STM32_MAX_ECC_SIZE); if (hashlen > STM32_MAX_ECC_SIZE) { + ForceZero(Keybin, sizeof(Keybin)); + ForceZero(Intbin, sizeof(Intbin)); return ECC_BAD_ARG_E; } else if ((int)hashlen > size) { @@ -1353,10 +1366,14 @@ int stm32_ecc_sign_hash_ex(const byte* hash, word32 hashlen, WC_RNG* rng, status = HAL_PKA_ECDSASign(&hpka, &pka_ecc, HAL_MAX_DELAY); if (status != HAL_OK) { + ForceZero(Keybin, sizeof(Keybin)); + ForceZero(Intbin, sizeof(Intbin)); HAL_PKA_RAMReset(&hpka); return WC_HW_E; } HAL_PKA_ECDSASign_GetResult(&hpka, &pka_ecc_out, NULL); + ForceZero(Keybin, sizeof(Keybin)); + ForceZero(Intbin, sizeof(Intbin)); status = mp_read_unsigned_bin(r, pka_ecc_out.RSign, size); if (status == MP_OKAY) status = mp_read_unsigned_bin(s, pka_ecc_out.SSign, size); diff --git a/wolfcrypt/src/port/st/stsafe.c b/wolfcrypt/src/port/st/stsafe.c index 72f85d3b507..0d6d3cd470b 100644 --- a/wolfcrypt/src/port/st/stsafe.c +++ b/wolfcrypt/src/port/st/stsafe.c @@ -279,6 +279,9 @@ int stsafe_interface_init(void) * Note: For ECDH operations on persistent slots, the key must be generated * with appropriate usage settings. Per ST FAE: slot 0xFF with usage_limit=1 * is recommended for ephemeral ECDH (key establishment mode). + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_create_key(stsafe_slot_t slot, stsafe_curve_id_t curve_id, uint8_t* pPubKeyRaw) @@ -316,6 +319,9 @@ static int stsafe_create_key(stsafe_slot_t slot, stsafe_curve_id_t curve_id, * Per ST FAE recommendation: slot 0xFF must be used with mode of * operation = key establishment and usage limit = 1 for ECDH operations. * Public key is returned in X||Y format. + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_create_ecdhe_key(stsafe_curve_id_t curve_id, uint8_t* pPubKeyRaw) @@ -344,6 +350,9 @@ static int stsafe_create_ecdhe_key(stsafe_curve_id_t curve_id, /** * \brief ECDSA sign using STSAFE-A120 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_sign(stsafe_slot_t slot, stsafe_curve_id_t curve_id, uint8_t* pHash, uint8_t* pSigRS) @@ -369,6 +378,9 @@ static int stsafe_sign(stsafe_slot_t slot, stsafe_curve_id_t curve_id, /** * \brief ECDSA verify using STSAFE-A120 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_verify(stsafe_curve_id_t curve_id, uint8_t* pHash, uint8_t* pSigRS, uint8_t* pPubKeyX, uint8_t* pPubKeyY, @@ -412,6 +424,9 @@ static int stsafe_verify(stsafe_curve_id_t curve_id, uint8_t* pHash, /** * \brief ECDH shared secret using STSAFE-A120 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_shared_secret(stsafe_slot_t slot, stsafe_curve_id_t curve_id, uint8_t* pPubKeyX, uint8_t* pPubKeyY, @@ -470,6 +485,9 @@ static int stsafe_shared_secret(stsafe_slot_t slot, stsafe_curve_id_t curve_id, /** * \brief Read device certificate from STSAFE-A120 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_read_certificate(uint8_t** ppCert, uint32_t* pCertLen) { @@ -588,6 +606,9 @@ static int stsafe_check_host_keys(void* handle) /** * \brief Initialize STSAFE-A100/A110 device + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ int stsafe_interface_init(void) { @@ -641,6 +662,9 @@ int stsafe_interface_init(void) /** * \brief Generate ECC key pair on STSAFE-A100/A110 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_create_key(stsafe_slot_t* pSlot, stsafe_curve_id_t curve_id, uint8_t* pPubKeyRaw) @@ -663,7 +687,8 @@ static int stsafe_create_key(stsafe_slot_t* pSlot, stsafe_curve_id_t curve_id, curve_id, &pointRepId, &pubX, &pubY, STSAFE_A_HOST_C_MAC); if (status_code == STSAFE_A_OK && pointRepId != NULL && - *pointRepId == STSAFE_A_POINT_REPRESENTATION_ID) { + *pointRepId == STSAFE_A_POINT_REPRESENTATION_ID && + pubX != NULL && pubY != NULL) { XMEMCPY(pPubKeyRaw, pubX->Data, pubX->Length); XMEMCPY(pPubKeyRaw + key_sz, pubY->Data, pubY->Length); rc = STSAFE_A_OK; @@ -685,6 +710,9 @@ static int stsafe_create_key(stsafe_slot_t* pSlot, stsafe_curve_id_t curve_id, /** * \brief ECDSA sign using STSAFE-A100/A110 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_sign(stsafe_slot_t slot, stsafe_curve_id_t curve_id, uint8_t* pHash, uint8_t* pSigRS) @@ -743,6 +771,9 @@ static int stsafe_sign(stsafe_slot_t slot, stsafe_curve_id_t curve_id, /** * \brief ECDSA verify using STSAFE-A100/A110 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_verify(stsafe_curve_id_t curve_id, uint8_t* pHash, uint8_t* pSigRS, uint8_t* pPubKeyX, uint8_t* pPubKeyY, @@ -836,6 +867,9 @@ static int stsafe_verify(stsafe_curve_id_t curve_id, uint8_t* pHash, /** * \brief ECDH shared secret using STSAFE-A100/A110 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_shared_secret(stsafe_slot_t slot, stsafe_curve_id_t curve_id, uint8_t* pPubKeyX, uint8_t* pPubKeyY, @@ -901,6 +935,9 @@ static int stsafe_shared_secret(stsafe_slot_t slot, stsafe_curve_id_t curve_id, /** * \brief Read device certificate from STSAFE-A100/A110 + * + * \return STSAFE_A_OK on success. + * \return Other value on failure. */ static int stsafe_read_certificate(uint8_t** ppCert, uint32_t* pCertLen) { @@ -923,7 +960,7 @@ static int stsafe_read_certificate(uint8_t** ppCert, uint32_t* pCertLen) status_code = StSafeA_Read(g_stsafe_handle, 0, 0, STSAFE_A_ALWAYS, 0, 0, 4, &readBuf, STSAFE_A_NO_MAC); - if (status_code == STSAFE_A_OK && readBuf->Length == 4) { + if (status_code == STSAFE_A_OK && readBuf != NULL && readBuf->Length == 4) { /* Parse ASN.1 DER certificate header */ /* 0x30 = ASN_SEQUENCE | ASN_CONSTRUCTED (certificate is a SEQUENCE) */ if (readBuf->Data[0] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) { @@ -962,7 +999,7 @@ static int stsafe_read_certificate(uint8_t** ppCert, uint32_t* pCertLen) if (rc == STSAFE_A_OK && *pCertLen > 0) { *ppCert = (uint8_t*)XMALLOC(*pCertLen, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (*ppCert == NULL) { - rc = (int)(uint8_t)-1; + rc = MEMORY_E; } } diff --git a/wolfcrypt/src/port/ti/ti-aes.c b/wolfcrypt/src/port/ti/ti-aes.c index ac3ceaebfac..738e380619c 100644 --- a/wolfcrypt/src/port/ti/ti-aes.c +++ b/wolfcrypt/src/port/ti/ti-aes.c @@ -73,7 +73,7 @@ static int AesSetIV(Aes* aes, const byte* iv) int wc_AesSetKey(Aes* aes, const byte* key, word32 len, const byte* iv, int dir) { if (!wolfSSL_TI_CCMInit()) - return 1; + return WC_HW_E; if ((aes == NULL) || (key == NULL)) return BAD_FUNC_ARG; if (!((dir == AES_ENCRYPTION) || (dir == AES_DECRYPTION))) @@ -231,6 +231,9 @@ int wc_AesCtrEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) char *tmp; /* (char *)aes->tmp, for short */ int ret; + if ((aes == NULL) || (out == NULL) || (in == NULL)) + return BAD_FUNC_ARG; + tmp = (char *)aes->tmp; if (aes->left) { if ((aes->left + sz) >= WC_AES_BLOCK_SIZE) { @@ -350,7 +353,7 @@ static int AesAuthArgCheck(Aes* aes, byte* out, const byte* in, word32 inSz, case 16: *M = AES_CFG_CCM_M_16; break; default: - return 1; + return BAD_FUNC_ARG; } switch (nonceSz) { @@ -371,7 +374,7 @@ static int AesAuthArgCheck(Aes* aes, byte* out, const byte* in, word32 inSz, case 14: *L = AES_CFG_CCM_L_1; break; default: - return 1; + return BAD_FUNC_ARG; } return 0; } @@ -469,6 +472,9 @@ static int AesAuthEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz, if (ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG)) { return ret; } + if ((authIn == NULL) && (authInSz > 0)) { + return BAD_FUNC_ARG; + } AesAuthSetIv(aes, nonce, nonceSz, L, mode); @@ -569,6 +575,9 @@ static int AesAuthDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz, if (ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG)) { return ret; } + if ((authIn == NULL) && (authInSz > 0)) { + return BAD_FUNC_ARG; + } AesAuthSetIv(aes, nonce, nonceSz, L, mode); @@ -685,6 +694,9 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, const byte* in, word32 sz, int wc_GmacSetKey(Gmac* gmac, const byte* key, word32 len) { + if (gmac == NULL) { + return BAD_FUNC_ARG; + } return AesAuthSetKey(&gmac->aes, key, len); } @@ -692,6 +704,9 @@ int wc_GmacUpdate(Gmac* gmac, const byte* iv, word32 ivSz, const byte* authIn, word32 authInSz, byte* authTag, word32 authTagSz) { + if (gmac == NULL) { + return BAD_FUNC_ARG; + } return AesAuthEncrypt(&gmac->aes, NULL, NULL, 0, iv, ivSz, authTag, authTagSz, authIn, authInSz, AES_CFG_MODE_GCM_HY0CALC); } diff --git a/wolfcrypt/src/port/ti/ti-ccm.c b/wolfcrypt/src/port/ti/ti-ccm.c index 80097d6a845..4fb6dc4c87a 100644 --- a/wolfcrypt/src/port/ti/ti-ccm.c +++ b/wolfcrypt/src/port/ti/ti-ccm.c @@ -44,7 +44,7 @@ #endif /* TI_DUMMY_BUILD */ #define TIMEOUT 500000 -#define WAIT(stat) { volatile int i; for(i=0; iused = 0; hash->msg = 0; hash->len = 0; @@ -100,6 +100,11 @@ static int hashUpdate(wolfssl_TI_Hash *hash, const byte* data, word32 len) static int hashGetHash(wolfssl_TI_Hash *hash, byte* result, word32 algo, word32 hsize) { uint32_t h[16]; + + if (hash == NULL || result == NULL) { + return BAD_FUNC_ARG; + } + #ifndef TI_DUMMY_BUILD wolfSSL_TI_lockCCM(); ROM_SHAMD5Reset(SHAMD5_BASE); @@ -113,9 +118,6 @@ static int hashGetHash(wolfssl_TI_Hash *hash, byte* result, word32 algo, word32 XMEMSET(h, 0, sizeof(h)); #endif - if (result == NULL) { - return BAD_FUNC_ARG; - } XMEMCPY(result, h, hsize); return 0; @@ -123,6 +125,8 @@ static int hashGetHash(wolfssl_TI_Hash *hash, byte* result, word32 algo, word32 static int hashCopy(wolfssl_TI_Hash *src, wolfssl_TI_Hash *dst) { + if (src == NULL || dst == NULL) + return BAD_FUNC_ARG; /* only copy hash, zero the rest of the struct to avoid double-free */ dst->msg = NULL; dst->used = 0; @@ -133,10 +137,17 @@ static int hashCopy(wolfssl_TI_Hash *src, wolfssl_TI_Hash *dst) static int hashFinal(wolfssl_TI_Hash *hash, byte* result, word32 algo, word32 hsize) { - hashGetHash(hash, result, algo, hsize); + int ret; + + if (hash == NULL || result == NULL) { + return BAD_FUNC_ARG; + } + + ret = hashGetHash(hash, result, algo, hsize); XFREE(hash->msg, NULL, DYNAMIC_TYPE_TMP_BUFFER); hashInit(hash); - return 0; + + return ret; } static int hashHash(const byte* data, word32 len, byte* hash, word32 algo, word32 hsize) @@ -151,8 +162,10 @@ static int hashHash(const byte* data, word32 len, byte* hash, word32 algo, word3 WOLFSSL_MSG("Hash Init failed"); } else { - hashUpdate(hash_desc, data, len); - hashFinal(hash_desc, hash, algo, hsize); + ret = hashUpdate(hash_desc, data, len); + if (ret == 0) { + ret = hashFinal(hash_desc, hash, algo, hsize); + } } WC_FREE_VAR_EX(hash_desc, NULL, DYNAMIC_TYPE_TMP_BUFFER); @@ -162,6 +175,8 @@ static int hashHash(const byte* data, word32 len, byte* hash, word32 algo, word3 static int hashFree(wolfssl_TI_Hash *hash) { + if (hash == NULL) + return BAD_FUNC_ARG; XFREE(hash->msg, NULL, DYNAMIC_TYPE_TMP_BUFFER); hashInit(hash); return 0; @@ -171,7 +186,7 @@ static int hashFree(wolfssl_TI_Hash *hash) WOLFSSL_API int wc_InitMd5_ex(Md5* md5, void* heap, int devId) { if (md5 == NULL) - return 1; + return BAD_FUNC_ARG; (void)heap; (void)devId; return hashInit((wolfssl_TI_Hash *)md5); @@ -217,7 +232,7 @@ WOLFSSL_API void wc_Md5Free(Md5* md5) WOLFSSL_API int wc_InitSha_ex(Md5* sha, void* heap, int devId) { if (sha == NULL) - return 1; + return BAD_FUNC_ARG; (void)heap; (void)devId; return hashInit((wolfssl_TI_Hash *)sha); @@ -263,7 +278,7 @@ WOLFSSL_API void wc_ShaFree(Sha* sha) WOLFSSL_API int wc_InitSha224_ex(Sha224* sha224, void* heap, int devId) { if (sha224 == NULL) - return 1; + return BAD_FUNC_ARG; (void)heap; (void)devId; return hashInit((wolfssl_TI_Hash *)sha224); @@ -309,7 +324,7 @@ WOLFSSL_API void wc_Sha224Free(Sha224* sha224) WOLFSSL_API int wc_InitSha256_ex(Sha256* sha256, void* heap, int devId) { if (sha256 == NULL) - return 1; + return BAD_FUNC_ARG; (void)heap; (void)devId; return hashInit((wolfssl_TI_Hash *)sha256); diff --git a/wolfcrypt/src/port/tropicsquare/tropic01.c b/wolfcrypt/src/port/tropicsquare/tropic01.c index ce37f8f6575..0ba5dbd3f66 100644 --- a/wolfcrypt/src/port/tropicsquare/tropic01.c +++ b/wolfcrypt/src/port/tropicsquare/tropic01.c @@ -163,8 +163,8 @@ static int Tropic01_GetKeyECC(byte* ecckey, int keySlot, word32 keySz) return BAD_FUNC_ARG; - /* Check key size */ - if (keySz != 16 && keySz != 24 && keySz != 32) { + /* Check key size: 256-bit */ + if (keySz != 32) { WOLFSSL_MSG_EX( "TROPIC01: Get ECC Key: Unsupported key size %u", keySz @@ -244,6 +244,7 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to get ED25519 PRIVkey,ret=%d", ret); + ForceZero(info->pk.ed25519sign.key->k, ED25519_PRV_KEY_SIZE); return ret; } ret = Tropic01_GetKeyECC( @@ -254,6 +255,7 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to get ED25519 PUBkey,ret=%d", ret); + ForceZero(info->pk.ed25519sign.key->k, ED25519_PRV_KEY_SIZE); return ret; } /* set devId to invalid, so software is used */ @@ -264,6 +266,7 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) info->pk.ed25519sign.in, info->pk.ed25519sign.inLen, info->pk.ed25519sign.out, info->pk.ed25519sign.outLen, info->pk.ed25519sign.key); + ForceZero(info->pk.ed25519sign.key->k, ED25519_PRV_KEY_SIZE); /* reset devId */ info->pk.ed25519sign.key->devId = devId; @@ -312,6 +315,7 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to get AES key,ret=%d", ret); + ForceZero(lt_key, sizeof(lt_key)); return ret; } ret = Tropic01_GetKeyAES( @@ -322,12 +326,16 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to get AES IV, ret=%d", ret); + ForceZero(lt_key, sizeof(lt_key)); + ForceZero(lt_iv, sizeof(lt_iv)); return ret; } if (info->cipher.enc) { ret = wc_AesSetKey(info->cipher.aesgcm_enc.aes, lt_key, WC_AES_BLOCK_SIZE, lt_iv, AES_ENCRYPTION); - if (ret != 0) { + ForceZero(lt_key, sizeof(lt_key)); + ForceZero(lt_iv, sizeof(lt_iv)); + if (ret != 0) { WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to set AES key, ret=%d", ret); @@ -351,9 +359,10 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) info->cipher.aesgcm_enc.aes->devId = devId; } else { - ret = wc_AesSetKey(info->cipher.aesgcm_dec.aes, lt_key, WC_AES_BLOCK_SIZE, lt_iv, AES_DECRYPTION); + ForceZero(lt_key, sizeof(lt_key)); + ForceZero(lt_iv, sizeof(lt_iv)); if (ret != 0) { WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to set AES key, ret=%d", @@ -388,6 +397,7 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) if (ret != 0) { WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to get AES key,ret=%d", ret); + ForceZero(lt_key, sizeof(lt_key)); return ret; } ret = Tropic01_GetKeyAES( @@ -397,11 +407,15 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) if (ret != 0) { WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to get AES IV, ret=%d", ret); - return ret; - } + ForceZero(lt_key, sizeof(lt_key)); + ForceZero(lt_iv, sizeof(lt_iv)); + return ret; + } if (info->cipher.enc) { ret = wc_AesSetKey(info->cipher.aescbc.aes, lt_key, WC_AES_BLOCK_SIZE, lt_iv, AES_ENCRYPTION); + ForceZero(lt_key, sizeof(lt_key)); + ForceZero(lt_iv, sizeof(lt_iv)); if (ret != 0) { WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to set AES key, ret=%d", @@ -423,6 +437,8 @@ int Tropic01_CryptoCb(int devId, wc_CryptoInfo* info, void* ctx) ret = wc_AesSetKey(info->cipher.aescbc.aes, lt_key, WC_AES_BLOCK_SIZE, lt_iv, AES_DECRYPTION); + ForceZero(lt_key, sizeof(lt_key)); + ForceZero(lt_iv, sizeof(lt_iv)); if (ret != 0) { WOLFSSL_MSG_EX( "TROPIC01: CryptoCB: Failed to set AES key, ret=%d", @@ -466,19 +482,21 @@ int Tropic01_SetPairingKeys(int kIndex, const byte* kPub, const byte* kPriv) "TROPIC01: SetPairingKeys: Setting pairing key in slot %d", kIndex); + pk_index = kIndex; for (i = 0; i < TROPIC01_PAIRING_KEY_SIZE; i++) { - sh0priv[i] = kPriv[i]; sh0pub[i] = kPub[i]; } WOLFSSL_MSG("TROPIC01: SetPairingKeys: Pairing key set successfully"); +#if 0 WOLFSSL_MSG_EX( "TROPIC01: sh0priv: %02X %02X %02X %02X ...", kPriv[0], kPriv[1], kPriv[2], kPriv[3]); WOLFSSL_MSG_EX( "TROPIC01: sh0pub: %02X %02X %02X %02X ...", kPub[0], kPub[1], kPub[2], kPub[3]); +#endif return 0; } @@ -486,20 +504,23 @@ int Tropic01_Init(void) { lt_ret_t ret; - g_ctx.initialized = 0; - ret = lt_init(&g_h); - if (ret != LT_OK) { - WOLFSSL_MSG_EX("TROPIC01: lt_init failed with a code %d", ret); - return WC_HW_E; - } - ret = verify_chip_and_start_secure_session(&g_h, sh0priv, sh0pub, pk_index); - if (ret != LT_OK) { - WOLFSSL_MSG_EX("TROPIC01: secure session failed with a code %d", ret); - lt_deinit(&g_h); - return WC_HW_E; + if (g_ctx.initialized == 0) { + ret = lt_init(&g_h); + if (ret != LT_OK) { + WOLFSSL_MSG_EX("TROPIC01: lt_init failed with a code %d", ret); + return WC_HW_E; + } + ret = verify_chip_and_start_secure_session(&g_h, sh0priv, sh0pub, + pk_index); + if (ret != LT_OK) { + WOLFSSL_MSG_EX("TROPIC01: secure session failed with a code %d", + ret); + lt_deinit(&g_h); + return WC_HW_E; + } + g_ctx.initialized = 1; + WOLFSSL_MSG("TROPIC01: Crypto device initialized successfully"); } - g_ctx.initialized = 1; - WOLFSSL_MSG("TROPIC01: Crypto device initialized successfully"); return 0; } diff --git a/wolfcrypt/src/port/xilinx/xil-aesgcm.c b/wolfcrypt/src/port/xilinx/xil-aesgcm.c index edc66e6e48a..d07020f6bbf 100644 --- a/wolfcrypt/src/port/xilinx/xil-aesgcm.c +++ b/wolfcrypt/src/port/xilinx/xil-aesgcm.c @@ -199,8 +199,7 @@ static WC_INLINE int setup(Aes* aes, WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)aad, authInSz); - if (XSecure_AesUpdateAad(&(aes->xSec.cinst), XIL_CAST_U64(authIn), - authInSz)) { + if (XSecure_AesUpdateAad(&(aes->xSec.cinst), XIL_CAST_U64(aad), authInSz)) { WOLFSSL_XIL_MSG("Failed to set AAD"); err = 1; } else { @@ -272,7 +271,7 @@ int wc_AesGcmEncrypt( Aes* aes, byte* out, if (ret) { WOLFSSL_MSG( "Failed to alloc memory for AESGCM Encrypt alignment (in)"); - return 1; + return ret; } XMEMCPY(in_aligned, in, sz); } @@ -290,7 +289,7 @@ int wc_AesGcmEncrypt( Aes* aes, byte* out, aligned_xfree(in_buf, aes->heap); WOLFSSL_MSG( "Failed to alloc memory for AESGCM Encrypt alignment (out)"); - return 1; + return ret; } XMEMCPY(out_aligned, out, sz); } @@ -387,7 +386,7 @@ int wc_AesGcmDecrypt( Aes* aes, byte* out, if (ret) { WOLFSSL_MSG( "Failed to alloc memory for AESGCM Decrypt alignment (in)"); - return 1; + return ret; } XMEMCPY(in_aligned, in, sz); } @@ -405,7 +404,7 @@ int wc_AesGcmDecrypt( Aes* aes, byte* out, aligned_xfree(in_buf, aes->heap); WOLFSSL_MSG( "Failed to alloc memory for AESGCM Decrypt alignment (out)"); - return 1; + return ret; } XMEMCPY(out_aligned, out, sz); } @@ -528,8 +527,8 @@ int wc_AesGcmEncrypt(Aes* aes, byte* out, byte initalCounter[WC_AES_BLOCK_SIZE]; int ret; - if ((in == NULL && sz > 0) || iv == NULL || authTag == NULL || - authTagSz > AES_GCM_AUTH_SZ) { + if (aes == NULL || (in == NULL && sz > 0) || (out == NULL) || iv == NULL || + authTag == NULL || authTagSz > AES_GCM_AUTH_SZ) { return BAD_FUNC_ARG; } @@ -598,8 +597,8 @@ int wc_AesGcmDecrypt(Aes* aes, byte* out, byte initalCounter[WC_AES_BLOCK_SIZE]; int ret; - if (in == NULL || iv == NULL || authTag == NULL || - authTagSz < AES_GCM_AUTH_SZ) { + if (aes == NULL || in == NULL || out == NULL || iv == NULL || + authTag == NULL || authTagSz < AES_GCM_AUTH_SZ) { return BAD_FUNC_ARG; } diff --git a/wolfcrypt/src/port/xilinx/xil-sha3.c b/wolfcrypt/src/port/xilinx/xil-sha3.c index d41822d187d..1f17066f1cd 100644 --- a/wolfcrypt/src/port/xilinx/xil-sha3.c +++ b/wolfcrypt/src/port/xilinx/xil-sha3.c @@ -239,7 +239,7 @@ int wc_Sha3_384_Copy(wc_Sha3* src, wc_Sha3* dst) return 0; #else WOLFSSL_MSG("Copy of SHA3 struct not supported with this build"); - return -1; + return NOT_COMPILED_IN; #endif } #endif diff --git a/wolfcrypt/src/port/xilinx/xil-versal-trng.c b/wolfcrypt/src/port/xilinx/xil-versal-trng.c index adcb9399314..ccf5cbc82bd 100644 --- a/wolfcrypt/src/port/xilinx/xil-versal-trng.c +++ b/wolfcrypt/src/port/xilinx/xil-versal-trng.c @@ -197,7 +197,7 @@ int wc_VersalTrngReset(void) */ int wc_VersalTrngSelftest(void) { - return versal_trng_selftest() == XTRNGPSV_SUCCESS ? 0 : -1; + return versal_trng_selftest() == XTRNGPSV_SUCCESS ? 0 : WC_HW_E; } /** @@ -213,6 +213,10 @@ int wc_VersalTrngGenerate(byte* output, word32 sz) /* The TRNG always generates exactly 32bytes of output */ byte buf[XTRNGPSV_SEC_STRENGTH_BYTES]; word32 bytes_generated = 0; + + if (output == NULL) + return BAD_FUNC_ARG; + do { word32 bytes_left = sz - bytes_generated; word32 bytes_required = @@ -223,11 +227,13 @@ int wc_VersalTrngGenerate(byte* output, word32 sz) XTRNGPSV_FALSE); if (xret) { WOLFSSL_MSG_EX("XTrngpsv_Generate() returned 0x%08x", xret); + ForceZero(buf, sizeof(buf)); return WC_HW_E; } XMEMCPY(&output[bytes_generated], buf, bytes_required); bytes_generated += bytes_required; } while (bytes_generated < sz); + ForceZero(buf, sizeof(buf)); return 0; }