diff --git a/src/lib/tinybson/tinybson.cpp b/src/lib/tinybson/tinybson.cpp index e62b2e7b874..04949266df2 100644 --- a/src/lib/tinybson/tinybson.cpp +++ b/src/lib/tinybson/tinybson.cpp @@ -129,6 +129,11 @@ bson_decoder_init_file(bson_decoder_t decoder, int fd, bson_decoder_callback cal debug("total document size = %" PRIi32, decoder->total_document_size); + // The length is signed and comes from the document itself + if (decoder->total_document_size < 0) { + CODER_KILL(decoder, "negative document length"); + } + /* ready for decoding */ return 0; } @@ -169,6 +174,12 @@ bson_decoder_init_buf(bson_decoder_t decoder, void *buf, unsigned bufsize, bson_ debug("total document size = %" PRIi32, decoder->total_document_size); + // A negative length would skip the size check below, which only rejects lengths above + // the buffer + if (decoder->total_document_size < 0) { + CODER_KILL(decoder, "negative document length"); + } + if ((decoder->total_document_size > 0) && (decoder->total_document_size > (int)decoder->bufsize)) { CODER_KILL(decoder, "document length larger than buffer"); } diff --git a/src/systemcmds/tests/test_bson.cpp b/src/systemcmds/tests/test_bson.cpp index 939d51fe8d2..5c776c8817f 100644 --- a/src/systemcmds/tests/test_bson.cpp +++ b/src/systemcmds/tests/test_bson.cpp @@ -257,6 +257,27 @@ decode(bson_decoder_t decoder) } while (result > 0); } +static int +test_negative_document_size() +{ + // The document length is the first four bytes and is signed. A negative value must be + // rejected: it would otherwise skip the "larger than buffer" check, which only rejects + // lengths above the buffer size. + uint8_t buf[16] {}; + const int32_t negative_size = -2; + memcpy(buf, &negative_size, sizeof(negative_size)); + + bson_decoder_s decoder{}; + + if (bson_decoder_init_buf(&decoder, buf, sizeof(buf), decode_callback) == 0) { + PX4_ERR("FAIL: decoder: accepted a negative document length"); + return 1; + } + + PX4_INFO("PASS: decoder: rejected a negative document length"); + return 0; +} + int test_bson(int argc, char *argv[]) { @@ -295,5 +316,9 @@ test_bson(int argc, char *argv[]) decode(&decoder); free(buf); + if (test_negative_document_size() != 0) { + return 1; + } + return PX4_OK; }