[MONGOCRYPT-557] _finalize in mongocrypt-ctx-rewrap-many-datakey.c is double-initializing bson_t Created: 10/Mar/23  Updated: 27/Apr/23  Resolved: 27/Apr/23

Status: Closed
Project: Libmongocrypt
Component/s: None
Affects Version/s: None
Fix Version/s: 1.8.0

Type: Bug Priority: Unknown
Reporter: Zachary Espiritu Assignee: Kyle Kloberdanz
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Binding Changes: Not Needed

 Description   

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:

  1. Leave bson_t array uninitialized when it is declared on line 27
  2. 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 



 Comments   
Comment by Githook User [ 27/Apr/23 ]

Author:

{'name': 'Kyle Kloberdanz', 'email': 'kyle.kloberdanz@mongodb.com', 'username': 'kkloberdanz'}

Message: cleanup doc before exiting on error (#631)

MONGOCRYPT-557

Co-authored-by: Kevin Albertson <kevin.albertson@10gen.com>
Branch: master
https://github.com/mongodb/libmongocrypt/commit/b42a9984db589f7f61625314ab865706a34d89a9

Generated at Thu Feb 08 09:08:57 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.