Skip to content

Commit 56c46be

Browse files
committed
Use constant-time encryption key validation
F/2249
1 parent 78de4a7 commit 56c46be

1 file changed

Lines changed: 16 additions & 16 deletions

File tree

src/libwolfboot.c

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,20 @@ static uint8_t encrypt_iv_nonce[ENCRYPT_NONCE_SIZE] XALIGNED(4);
7070
static uint32_t encrypt_iv_offset = 0;
7171
static int fallback_iv_forced = 0;
7272

73+
static int encrypt_key_is_valid(const uint8_t *key, uint32_t len)
74+
{
75+
uint8_t has_one = 0;
76+
uint8_t has_zero = 0;
77+
uint32_t i;
78+
79+
for (i = 0; i < len; i++) {
80+
has_one |= key[i];
81+
has_zero |= (uint8_t)~key[i];
82+
}
83+
84+
return (has_one != 0) && (has_zero != 0);
85+
}
86+
7387
#define FALLBACK_IV_OFFSET 0x00100000U
7488
#if !defined(XMEMSET)
7589
#include <string.h>
@@ -1692,8 +1706,6 @@ int RAMFUNCTION chacha_init(void)
16921706
const uint8_t* stored_nonce;
16931707
uint8_t *key;
16941708
#endif
1695-
uint8_t ff[ENCRYPT_KEY_SIZE];
1696-
16971709
#ifdef CUSTOM_ENCRYPT_KEY
16981710
int ret = wolfBoot_get_encrypt_key(key, stored_nonce);
16991711
if (ret != 0)
@@ -1713,12 +1725,7 @@ int RAMFUNCTION chacha_init(void)
17131725

17141726
XMEMSET(&chacha, 0, sizeof(chacha));
17151727

1716-
/* Check against 'all 0xff' or 'all zero' cases */
1717-
XMEMSET(ff, 0xFF, ENCRYPT_KEY_SIZE);
1718-
if (XMEMCMP(key, ff, ENCRYPT_KEY_SIZE) == 0)
1719-
return -1;
1720-
XMEMSET(ff, 0x00, ENCRYPT_KEY_SIZE);
1721-
if (XMEMCMP(key, ff, ENCRYPT_KEY_SIZE) == 0)
1728+
if (!encrypt_key_is_valid(key, ENCRYPT_KEY_SIZE))
17221729
return -1;
17231730

17241731
XMEMCPY(encrypt_iv_nonce, stored_nonce, ENCRYPT_NONCE_SIZE);
@@ -1751,8 +1758,6 @@ int aes_init(void)
17511758
uint8_t *stored_nonce;
17521759
uint8_t *key;
17531760
#endif
1754-
uint8_t ff[ENCRYPT_KEY_SIZE];
1755-
17561761
#ifdef WOLFBOOT_RENESAS_TSIP
17571762
int ret;
17581763
wrap_enc_key_t* enc_key;
@@ -1781,12 +1786,7 @@ int aes_init(void)
17811786
wc_AesInit(&aes_enc, NULL, devId);
17821787
wc_AesInit(&aes_dec, NULL, devId);
17831788

1784-
/* Check against 'all 0xff' or 'all zero' cases */
1785-
XMEMSET(ff, 0xFF, ENCRYPT_KEY_SIZE);
1786-
if (XMEMCMP(key, ff, ENCRYPT_KEY_SIZE) == 0)
1787-
return -1;
1788-
XMEMSET(ff, 0x00, ENCRYPT_KEY_SIZE);
1789-
if (XMEMCMP(key, ff, ENCRYPT_KEY_SIZE) == 0)
1789+
if (!encrypt_key_is_valid(key, ENCRYPT_KEY_SIZE))
17901790
return -1;
17911791

17921792
#ifdef WOLFBOOT_RENESAS_TSIP

0 commit comments

Comments
 (0)