Detect invalid sizes when encoding bytes fields.

This commit is contained in:
Petteri Aimonen
2013-10-24 21:45:39 +03:00
parent 86d6983156
commit ed564186e1
3 changed files with 24 additions and 3 deletions

View File

@@ -521,7 +521,10 @@ bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, c
bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src) bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src)
{ {
const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)src; const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)src;
UNUSED(field);
if (bytes->size + offsetof(pb_bytes_array_t, bytes) > field->data_size)
PB_RETURN_ERROR(stream, "bytes size exceeded");
return pb_encode_string(stream, bytes->bytes, bytes->size); return pb_encode_string(stream, bytes->bytes, bytes->size);
} }

View File

@@ -12,6 +12,10 @@ message StringMessage {
required string data = 1 [(nanopb).max_size = 10]; required string data = 1 [(nanopb).max_size = 10];
} }
message BytesMessage {
required bytes data = 1 [(nanopb).max_size = 16];
}
message CallbackArray { message CallbackArray {
// We cheat a bit and use this message for testing other types, too. // We cheat a bit and use this message for testing other types, too.
// Nanopb does not care about the actual defined data type for callback // Nanopb does not care about the actual defined data type for callback

View File

@@ -172,9 +172,9 @@ int main()
struct { size_t size; uint8_t bytes[5]; } value = {5, {'x', 'y', 'z', 'z', 'y'}}; struct { size_t size; uint8_t bytes[5]; } value = {5, {'x', 'y', 'z', 'z', 'y'}};
COMMENT("Test pb_enc_bytes") COMMENT("Test pb_enc_bytes")
TEST(WRITES(pb_enc_bytes(&s, NULL, &value), "\x05xyzzy")) TEST(WRITES(pb_enc_bytes(&s, &BytesMessage_fields[0], &value), "\x05xyzzy"))
value.size = 0; value.size = 0;
TEST(WRITES(pb_enc_bytes(&s, NULL, &value), "\x00")) TEST(WRITES(pb_enc_bytes(&s, &BytesMessage_fields[0], &value), "\x00"))
} }
{ {
@@ -258,6 +258,20 @@ int main()
"\x0A\x07\x0A\x05\x01\x02\x03\x04\x05")) "\x0A\x07\x0A\x05\x01\x02\x03\x04\x05"))
} }
{
uint8_t buffer[32];
pb_ostream_t s;
BytesMessage msg = {{3, "xyz"}};
COMMENT("Test pb_encode with bytes message.")
TEST(WRITES(pb_encode(&s, BytesMessage_fields, &msg),
"\x0A\x03xyz"))
msg.data.size = 17; /* More than maximum */
TEST(!pb_encode(&s, BytesMessage_fields, &msg))
}
{ {
uint8_t buffer[20]; uint8_t buffer[20];
pb_ostream_t s; pb_ostream_t s;