-
Type: Bug
-
Resolution: Done
-
Priority: Unknown
-
Affects Version/s: None
-
Component/s: None
-
None
-
Not Needed
In _finalize in mongocrypt-ctx-rewrap-many-datakey.c, a Valgrind memory leak can occur when the libbson BSON_MEMCHECK compile flag is set because:
- bson_t array is initialized on line 27 with BSON_INITIALIZER
- bson_t array is passed as the child argument to BSON_APPEND_ARRAY_BEGIN, which appears to require that the child is uninitialized as it overwrites any previously initialized information in the the child bson_t structure without destroying it (see line 522–543 from the libbson code)
Additionally, a potential memory leak can occur if the call to mongocrypt_ctx_finalize fails (on line 42 as of commit 2ec9c3) as the function can return without calling bson_append_array_end on array and bson_destroy on doc and elem.
Both of these can be fixed by:
- Leave bson_t array uninitialized when it is declared on line 27
- Clean up the bson_t structures in the error case on line 42 with:
if (!mongocrypt_ctx_finalize (iter->dkctx, &bin)) { bson_append_array_end (&doc, &array); bson_destroy (&doc); bson_destroy (&elem); return _mongocrypt_ctx_fail_w_msg ( ctx, "failed to encrypt datakey with new provider"); }
—
To reproduce the memory leak, use
mkdir cmake-build && cd cmake-build cmake ../ make valgrind --leak-check=full ./test-mongocrypt