aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPetteri Aimonen <jpa@git.mail.kapsi.fi>2013-10-24 21:45:39 +0300
committerPetteri Aimonen <jpa@git.mail.kapsi.fi>2013-10-24 21:45:39 +0300
commited564186e14c79c767096f4b306dc3c6c5bd2e7d (patch)
tree5fde14736419a4a8513c0c6a5c6a42e926344ea0
parent86d698315608c372868bb55f6d2c609600ac8e41 (diff)
Detect invalid sizes when encoding bytes fields.
-rw-r--r--pb_encode.c5
-rw-r--r--tests/common/unittestproto.proto4
-rw-r--r--tests/encode_unittests/encode_unittests.c18
3 files changed, 24 insertions, 3 deletions
diff --git a/pb_encode.c b/pb_encode.c
index 4aced3cb..563c1bb7 100644
--- a/pb_encode.c
+++ b/pb_encode.c
@@ -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)
{
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);
}
diff --git a/tests/common/unittestproto.proto b/tests/common/unittestproto.proto
index 7024942e..eb3e7dec 100644
--- a/tests/common/unittestproto.proto
+++ b/tests/common/unittestproto.proto
@@ -12,6 +12,10 @@ message StringMessage {
required string data = 1 [(nanopb).max_size = 10];
}
+message BytesMessage {
+ required bytes data = 1 [(nanopb).max_size = 16];
+}
+
message CallbackArray {
// 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
diff --git a/tests/encode_unittests/encode_unittests.c b/tests/encode_unittests/encode_unittests.c
index 14bc62ee..fd9a730c 100644
--- a/tests/encode_unittests/encode_unittests.c
+++ b/tests/encode_unittests/encode_unittests.c
@@ -172,9 +172,9 @@ int main()
struct { size_t size; uint8_t bytes[5]; } value = {5, {'x', 'y', 'z', 'z', 'y'}};
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;
- TEST(WRITES(pb_enc_bytes(&s, NULL, &value), "\x00"))
+ TEST(WRITES(pb_enc_bytes(&s, &BytesMessage_fields[0], &value), "\x00"))
}
{
@@ -259,6 +259,20 @@ int main()
}
{
+ 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];
pb_ostream_t s;
IntegerContainer msg = {{5, {1,2,3,4,5}}};