Skip to content

Commit bd59393

Browse files
committed
Handle setting null terminator for ASN1_STRING key in we_mac.c.
When OpenSSL is asked to set the MAC key with a 0 length key, it still allocates a single byte buffer with a single null terminmator. This commit makes wolfEngine do the same.
1 parent 9785464 commit bd59393

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

src/we_mac.c

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ static int we_mac_cache_key(EVP_PKEY_CTX *ctx, we_Mac *mac)
186186
/* Get key length and data. */
187187
mac->keySz = ASN1_STRING_length(key);
188188
data = ASN1_STRING_get0_data(key);
189-
if (data == NULL) {
189+
if (data == NULL || mac->keySz < 0) {
190190
ret = 0;
191191
}
192192
}
@@ -195,15 +195,16 @@ static int we_mac_cache_key(EVP_PKEY_CTX *ctx, we_Mac *mac)
195195
if (mac->key != NULL) {
196196
OPENSSL_clear_free(mac->key, mac->keySz);
197197
}
198-
/* Allocate memory to cache key. */
199-
mac->key = (unsigned char *)OPENSSL_zalloc(mac->keySz);
198+
/* Allocate memory to cache key, +1 for null terminator. */
199+
mac->key = (unsigned char *)OPENSSL_zalloc(mac->keySz + 1);
200200
if (mac->key == NULL) {
201201
ret = 0;
202202
}
203203
}
204204
if (ret == 1) {
205205
/* Copy key data into cache. */
206206
XMEMCPY(mac->key, data, mac->keySz);
207+
mac->key[mac->keySz] = '\0';
207208
}
208209

209210
WOLFENGINE_LEAVE(WE_LOG_MAC, "we_mac_cache_key", ret);
@@ -391,20 +392,21 @@ static int we_mac_pkey_ctrl(EVP_PKEY_CTX *ctx, int type, int num, void *ptr)
391392
* num [in] Length of key in bytes.
392393
*/
393394
WOLFENGINE_MSG(WE_LOG_MAC, "type: EVP_PKEY_CTRL_SET_MAC_KEY");
394-
if (ptr != NULL) {
395+
if (ptr != NULL && num >= 0) {
395396
/* Dispose of old key safely. */
396397
if (mac->key != NULL) {
397398
OPENSSL_clear_free(mac->key, mac->keySz);
398399
}
399-
/* Allocate memory for new key. */
400-
mac->key = (unsigned char *)OPENSSL_zalloc(num);
400+
/* Allocate memory for new key, +1 for null terminator. */
401+
mac->key = (unsigned char *)OPENSSL_zalloc(num + 1);
401402
if (mac->key == NULL) {
402403
ret = 0;
403404
}
404405
else {
405406
/* Copy in key data and store size. */
406407
XMEMCPY(mac->key, ptr, num);
407408
mac->keySz = num;
409+
mac->key[num] = '\0';
408410
}
409411
}
410412
else {
@@ -517,14 +519,15 @@ static int we_mac_dup(we_Mac *src, we_Mac **dst)
517519
mac->type = src->type;
518520
mac->keySz = src->keySz;
519521
/* Duplicate the key if set. */
520-
if (src->keySz > 0) {
521-
mac->key = (unsigned char *)OPENSSL_zalloc(src->keySz);
522+
if (src->keySz >= 0) {
523+
mac->key = (unsigned char *)OPENSSL_zalloc(src->keySz + 1);
522524
if (mac->key == NULL) {
523525
ret = 0;
524526
}
525527
else {
526528
/* Copy over key bytes. */
527529
XMEMCPY(mac->key, src->key, src->keySz);
530+
mac->key[mac->keySz] = '\0';
528531
}
529532
}
530533
else {

0 commit comments

Comments
 (0)