Contact Details
arjunaajalahla100@gmail.com
Version
main branch
Description
Found a memory leak in the Dilithium/ML-DSA implementation when the WC_DILITHIUM_CACHE_MATRIX_A compile option is enabled and WC_DILITHIUM_FIXED_ARRAY is disabled.
In the signing function around line 8321 of wolfcrypt/src/dilithium.c, there's this code:
if ((ret == 0) && (key->a == NULL)) {
a = (sword32*)XMALLOC(params->aSz, key->heap, DYNAMIC_TYPE_DILITHIUM); // Line 8321
if (a == NULL) {
ret = MEMORY_E;
}
}
#endif
if (ret == 0) {
a = key->a; // Line 8328 - overwrites the freshly allocated pointer
}
The problem is that it allocates memory into the local variable a instead of storing it in key->a. Then on line 8328, a gets overwritten with key->a (which is still NULL at this point), so the allocated memory is lost and never freed.
The correct pattern is used elsewhere in the same file (e.g., line 7765-7766 in dilithium_make_key):
if (key->a == NULL) {
key->a = (sword32*)XMALLOC(params->aSz, key->heap, DYNAMIC_TYPE_DILITHIUM);
if (key->a == NULL) {
ret = MEMORY_E;
}
}
Fix
Change line 8321 from:
a = (sword32*)XMALLOC(params->aSz, key->heap, DYNAMIC_TYPE_DILITHIUM);
To:
key->a = (sword32*)XMALLOC(params->aSz, key->heap, DYNAMIC_TYPE_DILITHIUM);
And remove line 8328 (a = key->a;) since it's no longer needed.
Reproduction steps
- Configure wolfSSL with
WC_DILITHIUM_CACHE_MATRIX_A defined and WC_DILITHIUM_FIXED_ARRAY undefined
- Build and run the Dilithium signing operation
- The memory leak will occur each time the signing function is called when
key->a is NULL
Relevant log output
Contact Details
arjunaajalahla100@gmail.com
Version
main branch
Description
Found a memory leak in the Dilithium/ML-DSA implementation when the
WC_DILITHIUM_CACHE_MATRIX_Acompile option is enabled andWC_DILITHIUM_FIXED_ARRAYis disabled.In the signing function around line 8321 of
wolfcrypt/src/dilithium.c, there's this code:The problem is that it allocates memory into the local variable
ainstead of storing it inkey->a. Then on line 8328,agets overwritten withkey->a(which is still NULL at this point), so the allocated memory is lost and never freed.The correct pattern is used elsewhere in the same file (e.g., line 7765-7766 in
dilithium_make_key):Fix
Change line 8321 from:
To:
And remove line 8328 (
a = key->a;) since it's no longer needed.Reproduction steps
WC_DILITHIUM_CACHE_MATRIX_Adefined andWC_DILITHIUM_FIXED_ARRAYundefinedkey->ais NULLRelevant log output