Skip to content

[Bug]: Memory leak in Dilithium signing when WC_DILITHIUM_CACHE_MATRIX_A is enabled #10383

@zulfff

Description

@zulfff

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

  1. Configure wolfSSL with WC_DILITHIUM_CACHE_MATRIX_A defined and WC_DILITHIUM_FIXED_ARRAY undefined
  2. Build and run the Dilithium signing operation
  3. The memory leak will occur each time the signing function is called when key->a is NULL

Relevant log output

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions