siv: return error if key is not set

Avoid encryption or decryption using uninitialized data, or causing a
crash, if a key was not set for the SIV instance.
This commit is contained in:
Miroslav Lichvar 2020-09-09 14:00:32 +02:00
parent 9820c22c1d
commit 2bb88b45c6
3 changed files with 27 additions and 0 deletions

View file

@ -204,6 +204,9 @@ SIV_Encrypt(SIV_Instance instance,
{
size_t clen = ciphertext_length;
if (!instance->cipher)
return 0;
if (nonce_length < 1 || assoc_length < 0 ||
plaintext_length < 0 || ciphertext_length < 0)
return 0;
@ -232,6 +235,9 @@ SIV_Decrypt(SIV_Instance instance,
{
size_t plen = plaintext_length;
if (!instance->cipher)
return 0;
if (nonce_length < 1 || assoc_length < 0 ||
plaintext_length < 0 || ciphertext_length < 0)
return 0;

View file

@ -39,6 +39,7 @@
struct SIV_Instance_Record {
struct siv_cmac_aes128_ctx siv;
int key_set;
};
/* ================================================== */
@ -52,6 +53,7 @@ SIV_CreateInstance(SIV_Algorithm algorithm)
return NULL;
instance = MallocNew(struct SIV_Instance_Record);
instance->key_set = 0;
return instance;
}
@ -86,6 +88,8 @@ SIV_SetKey(SIV_Instance instance, const unsigned char *key, int length)
siv_cmac_aes128_set_key(&instance->siv, key);
instance->key_set = 1;
return 1;
}
@ -108,6 +112,9 @@ SIV_Encrypt(SIV_Instance instance,
const void *plaintext, int plaintext_length,
unsigned char *ciphertext, int ciphertext_length)
{
if (!instance->key_set)
return 0;
if (nonce_length < SIV_MIN_NONCE_SIZE || assoc_length < 0 ||
plaintext_length < 0 || plaintext_length > ciphertext_length ||
plaintext_length + SIV_DIGEST_SIZE != ciphertext_length)
@ -130,6 +137,9 @@ SIV_Decrypt(SIV_Instance instance,
const unsigned char *ciphertext, int ciphertext_length,
void *plaintext, int plaintext_length)
{
if (!instance->key_set)
return 0;
if (nonce_length < SIV_MIN_NONCE_SIZE || assoc_length < 0 ||
plaintext_length < 0 || plaintext_length > ciphertext_length ||
plaintext_length + SIV_DIGEST_SIZE != ciphertext_length)

View file

@ -149,6 +149,17 @@ test_unit(void)
TEST_CHECK(SIV_GetKeyLength(tests[i].algorithm) == tests[i].key_length);
r = SIV_Encrypt(siv, tests[i].nonce, tests[i].nonce_length,
tests[i].assoc, tests[i].assoc_length,
tests[i].plaintext, tests[i].plaintext_length,
ciphertext, tests[i].ciphertext_length);
TEST_CHECK(!r);
r = SIV_Decrypt(siv, tests[i].nonce, tests[i].nonce_length,
tests[i].assoc, tests[i].assoc_length,
tests[i].ciphertext, tests[i].ciphertext_length,
plaintext, tests[i].plaintext_length);
TEST_CHECK(!r);
for (j = -1; j < 1024; j++) {
r = SIV_SetKey(siv, tests[i].key, j);
TEST_CHECK(r == (j == tests[i].key_length));