[CDRIVER-2860] Client created after mongoc_cleanup sends garbage handshake metadata Created: 23/Oct/18  Updated: 23/Oct/18  Resolved: 23/Oct/18

Status: Closed
Project: C Driver
Component/s: libmongoc
Affects Version/s: 1.5.0
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: A. Jesse Jiryu Davis Assignee: A. Jesse Jiryu Davis
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
is related to CDRIVER-1325 Implement The MongoDB Handshake Protocol Closed

 Description   

It's well-documented that applications must call mongoc_init once at the beginning and mongoc_cleanup once at the end. If an application is written incorrectly, interesting things can happen:

/* allocates metadata values */
mongoc_init ();
/* frees metadata values */
mongoc_cleanup ();
/* no effect */
mongoc_init ();
/* involves allocations, maybe overwrites metadata values */
client = mongoc_client_new ("mongodb://user:pass@localhost");

The first call to mongoc_init allocates the handshake metadata values such as the driver name, and the first call to mongoc_cleanup frees these values. After that, subsequent calls to mongoc_init and mongoc_cleanup do nothing, by design.

However, creating a mongoc_client_t after mongoc_cleanup uses the metadata values, even though they were freed by mongoc_cleanup. Since they're freed, they may be overwritten by some future memory allocation. It's unpredictable what data will be written there and used as the metadata.

With code like the above, I produced a garbage handshake, including a scrap of the URI, since the driver allocates space for a copy of the URI after mongoc_cleanup, and the space previously occupied by the handshake metadata is reused for the URI copy.



 Comments   
Comment by A. Jesse Jiryu Davis [ 23/Oct/18 ]

The only solution I can think of is for mongoc_cleanup to set a global flag indicating that global data is now invalid, and check the flag before accessing global data. This isn't worth doing:

  • We must implement and test this flag-checking code for many dozens of functions, and it would be hard to maintain the list of functions that must check the flag
  • For technical reasons, we still can't protect users who access global data before mongoc_init, only those who access it after mongoc_cleanup
  • Checking the flag would add a lock to functions that are presently allowed to run in parallel
  • The rules for calling mongoc_init and mongoc_cleanup are very simple and well-documented
Generated at Wed Feb 07 21:16:33 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.