Skip to content

Commit 9f6365d

Browse files
committed
CDRIVER-2595 buffer underflow in bson_snprintf
Calling bson_snprintf with size 0 would write one byte before the start of the destination string.
1 parent 8ed31cd commit 9f6365d

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/libbson/src/bson/bson-string.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -608,10 +608,11 @@ bson_vsnprintf (char *str, /* IN */
608608

609609
BSON_ASSERT (str);
610610

611-
if (size != 0) {
612-
r = _vsnprintf_s (str, size, _TRUNCATE, format, ap);
611+
if (size == 0) {
612+
return 0;
613613
}
614614

615+
r = _vsnprintf_s (str, size, _TRUNCATE, format, ap);
615616
if (r == -1) {
616617
r = _vscprintf (format, ap);
617618
}
@@ -622,6 +623,12 @@ bson_vsnprintf (char *str, /* IN */
622623
#else
623624
int r;
624625

626+
BSON_ASSERT (str);
627+
628+
if (size == 0) {
629+
return 0;
630+
}
631+
625632
r = vsnprintf (str, size, format, ap);
626633
str[size - 1] = '\0';
627634
return r;

src/libbson/tests/test-string.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,17 @@ test_bson_strncpy (void)
285285
}
286286

287287

288+
static void
289+
test_bson_snprintf (void)
290+
{
291+
char buf[] = "ab";
292+
293+
/* CDRIVER-2595 make sure snprintf with size 0 doesn't write to buf[-1] */
294+
ASSERT_CMPINT (bson_snprintf (buf + 1, 0, "%d", 1), ==, 0);
295+
ASSERT_CMPSTR (buf, "ab");
296+
}
297+
298+
288299
static void
289300
test_bson_strcasecmp (void)
290301
{
@@ -309,6 +320,7 @@ test_string_install (TestSuite *suite)
309320
TestSuite_Add (suite, "/bson/string/strndup", test_bson_strndup);
310321
TestSuite_Add (suite, "/bson/string/ascii_strtoll", test_bson_ascii_strtoll);
311322
TestSuite_Add (suite, "/bson/string/strncpy", test_bson_strncpy);
323+
TestSuite_Add (suite, "/bson/string/snprintf", test_bson_snprintf);
312324
TestSuite_Add (suite, "/bson/string/strnlen", test_bson_strnlen);
313325
TestSuite_Add (suite, "/bson/string/strcasecmp", test_bson_strcasecmp);
314326
}

0 commit comments

Comments
 (0)