Skip to content

Commit

Permalink
wolfcrypt/src/dh.c: in wc_DhAgree_ct(), implement failsafe constant-t…
Browse files Browse the repository at this point in the history
…ime key size fixup, to work around sp-math constant-time key clamping.
  • Loading branch information
douzzer committed Sep 16, 2024
1 parent e6b466d commit db6c154
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion wolfcrypt/src/dh.c
Original file line number Diff line number Diff line change
Expand Up @@ -2296,13 +2296,59 @@ int wc_DhAgree(DhKey* key, byte* agree, word32* agreeSz, const byte* priv,
int wc_DhAgree_ct(DhKey* key, byte* agree, word32 *agreeSz, const byte* priv,
word32 privSz, const byte* otherPub, word32 pubSz)
{
int ret;
word32 requested_agreeSz;
#ifndef WOLFSSL_NO_MALLOC
byte *agree_buffer = NULL;
#else
byte agree_buffer[DH_MAX_SIZE / 8];
#endif

if (key == NULL || agree == NULL || agreeSz == NULL || priv == NULL ||
otherPub == NULL) {
return BAD_FUNC_ARG;
}

return wc_DhAgree_Sync(key, agree, agreeSz, priv, privSz, otherPub, pubSz,
requested_agreeSz = *agreeSz;

#ifndef WOLFSSL_NO_MALLOC
agree_buffer = (byte *)XMALLOC(requested_agreeSz, key->heap,
DYNAMIC_TYPE_DH);
if (agree_buffer == NULL)
return MEMORY_E;
#endif

XMEMSET(agree, 0, requested_agreeSz);
XMEMSET(agree_buffer, 0, requested_agreeSz);

ret = wc_DhAgree_Sync(key, agree, agreeSz, priv, privSz, otherPub, pubSz,
1);

if (ret == 0) {
/* Arrange for correct fixed-length, right-justified key, even if the
* crypto back end doesn't support it. This assures that the key is
* unconditionally agreed correctly. With some crypto back ends,
* e.g. heapmath, there are no provisions for actual constant time, but
* with others the key computation and clamping is constant time, and
* the unclamping here is also constant time.
*/
byte *agree_src = agree + *agreeSz - 1,
*agree_dst = agree_buffer + requested_agreeSz - 1;
while (agree_dst >= agree_buffer) {
word32 mask;
*agree_dst-- = *agree_src--;
mask = (agree_src >= agree) - 1U;
agree_src += (mask & requested_agreeSz);
}
XMEMCPY(agree, agree_buffer, requested_agreeSz);
*agreeSz = requested_agreeSz;
}

#ifndef WOLFSSL_NO_MALLOC
XFREE(agree_buffer, key->heap, DYNAMIC_TYPE_DH);
#endif

return ret;
}

#ifdef WOLFSSL_DH_EXTRA
Expand Down

0 comments on commit db6c154

Please sign in to comment.