Skip to content

Commit

Permalink
fix: memory leak
Browse files Browse the repository at this point in the history
Fix a memory leak due to out of bounds access at _jsonb_escape()

Closes #3
Co-authored-by: Aníbal Portero Hermida <[email protected]>
  • Loading branch information
lcsmuller committed Sep 3, 2022
1 parent 9079145 commit 1f05cf0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
9 changes: 6 additions & 3 deletions json-build.h
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,10 @@ _jsonb_escape(
}
}

if (*pos + len + extra_bytes > bufsize) return JSONB_ERROR_NOMEM;
if (*pos + len + extra_bytes > bufsize) {
*buf = '\0';
return JSONB_ERROR_NOMEM;
}

if (esc_buf) {
*pos += len + extra_bytes;
Expand Down Expand Up @@ -400,7 +403,7 @@ jsonb_key(jsonb *b, char buf[], size_t bufsize, const char key[], size_t len)
case JSONB_OBJECT_KEY_OR_CLOSE: {
enum jsonbcode ret;
BUFFER_COPY_CHAR(b, '"', pos, buf, bufsize);
ret = _jsonb_escape(&pos, buf + b->pos, bufsize, key, len);
ret = _jsonb_escape(&pos, buf + b->pos, bufsize - b->pos, key, len);
if (ret != JSONB_OK) return ret;
BUFFER_COPY(b, "\":", 2, pos, buf, bufsize);
STACK_HEAD(b, JSONB_OBJECT_VALUE);
Expand Down Expand Up @@ -551,7 +554,7 @@ jsonb_string(
return JSONB_ERROR_INPUT;
}
BUFFER_COPY_CHAR(b, '"', pos, buf, bufsize);
ret = _jsonb_escape(&pos, buf + b->pos, bufsize, str, len);
ret = _jsonb_escape(&pos, buf + b->pos, bufsize - b->pos, str, len);
if (ret != JSONB_OK) return ret;
BUFFER_COPY_CHAR(b, '"', pos, buf, bufsize);
STACK_HEAD(b, next_state);
Expand Down
22 changes: 22 additions & 0 deletions test/test.c
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,27 @@ check_string_escaping(void)
PASS();
}

TEST
check_string_escaping_bounds(void)
{
const char str[] = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
char buf[(sizeof("{}") - 1)
+ 4 * ((sizeof("\"\"") - 1) + (sizeof(str) - 1))];
jsonb b;

jsonb_init(&b);
jsonb_object(&b, buf, sizeof(buf));
ASSERT_EQm(buf, JSONB_OK,
jsonb_key(&b, buf, sizeof(buf), str, sizeof(str) - 1));
ASSERT_EQm(buf, JSONB_OK,
jsonb_string(&b, buf, sizeof(buf), str, sizeof(str) - 1));
ASSERT_EQm(buf, JSONB_ERROR_NOMEM,
jsonb_key(&b, buf, sizeof(buf), str, sizeof(str) - 1));
fprintf(stderr, "%s", buf);

PASS();
}

TEST
check_string_streaming(void)
{
Expand Down Expand Up @@ -307,6 +328,7 @@ check_string_streaming(void)
SUITE(string)
{
RUN_TEST(check_string_escaping);
RUN_TEST(check_string_escaping_bounds);
RUN_TEST(check_string_streaming);
}

Expand Down

0 comments on commit 1f05cf0

Please sign in to comment.