Skip to content

Commit 52813c4

Browse files
committed
Fix ARM alignment crash in HMAC code.
1 parent af3679c commit 52813c4

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/we_mac.c

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1048,6 +1048,57 @@ static int we_hmac_pkey_update(EVP_MD_CTX *ctx, const void *data, size_t dataSz)
10481048
}
10491049
}
10501050

1051+
#ifdef WE_ALIGNMENT_SAFETY
1052+
const word32 ALIGNMENT_REQ = 8;
1053+
word32 add = 0;
1054+
word32 internalBuffLen = 0;
1055+
byte* tmp = NULL;
1056+
if (ret == 1 && (mac->state.hmac.macType == WC_HASH_TYPE_SHA384 ||
1057+
mac->state.hmac.macType == WC_HASH_TYPE_SHA512)) {
1058+
internalBuffLen = mac->state.hmac.hash.sha512.buffLen;
1059+
add = dataSz > (WC_SHA512_BLOCK_SIZE - internalBuffLen) ?
1060+
(WC_SHA512_BLOCK_SIZE - internalBuffLen) : dataSz;
1061+
}
1062+
/* If the conditions below are satisfied, just calling wc_HmacUpdate with
1063+
* the passed in buffer and length can cause a memory alignment crash on
1064+
* certain platforms. The alternate algorithm used below (2 calls to
1065+
* wc_HmacUpdate) avoids this crash. */
1066+
if (dataSz > 0 && add > 0 && ((dataSz - add) >= WC_SHA512_BLOCK_SIZE) &&
1067+
(((unsigned long)data + add) % ALIGNMENT_REQ != 0)) {
1068+
/* Update the hash with "add" bytes of data, which will result in
1069+
* an update with a full WC_SHA512_BLOCK_SIZE number of bytes with no
1070+
* leftovers. */
1071+
rc = wc_HmacUpdate(&mac->state.hmac, (const byte*)data, add);
1072+
if (rc != 0) {
1073+
WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_HmacUpdate", rc);
1074+
ret = 0;
1075+
}
1076+
if (ret == 1) {
1077+
/* Allocate new, aligned buffer. */
1078+
tmp = (byte*)XMALLOC(dataSz - add, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1079+
if (tmp == NULL) {
1080+
WOLFENGINE_ERROR_FUNC_NULL(WE_LOG_MAC, "XMALLOC", tmp);
1081+
ret = 0;
1082+
}
1083+
}
1084+
if (ret == 1) {
1085+
/* Copy remaining data from the unaligned buffer to the aligned one
1086+
* and update the hash. */
1087+
XMEMCPY(tmp, (byte*)data + add, dataSz - add);
1088+
rc = wc_HmacUpdate(&mac->state.hmac, (const byte*)tmp,
1089+
dataSz - add);
1090+
if (rc != 0) {
1091+
WOLFENGINE_ERROR_FUNC(WE_LOG_MAC, "wc_HmacUpdate", rc);
1092+
ret = 0;
1093+
}
1094+
}
1095+
1096+
if (tmp != NULL) {
1097+
XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1098+
}
1099+
}
1100+
else
1101+
#endif
10511102
if (ret == 1) {
10521103
/* Update the wolfCrypt HMAC object with more data. */
10531104
rc = wc_HmacUpdate(&mac->state.hmac, (const byte*)data, (word32)dataSz);

0 commit comments

Comments
 (0)