From c6859a1b4e1eae3dd039a42ea64fd76ff4316843 Mon Sep 17 00:00:00 2001 From: Miguel Company Date: Thu, 3 Jul 2025 18:53:34 +0200 Subject: [PATCH] Check remaining size before resizing sequences (#130) * Check remaining size before resizing sequences Signed-off-by: Miguel Company * Avoid linter complaining of too long function. Signed-off-by: Miguel Company --------- Signed-off-by: Miguel Company (cherry picked from commit 7283329f7c3cb654e7b843ab127ab2eda680662a) --- .../resource/msg__type_support_c.cpp.em | 10 ++++++++++ .../resource/msg__type_support.cpp.em | 12 +++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/rosidl_typesupport_fastrtps_c/resource/msg__type_support_c.cpp.em b/rosidl_typesupport_fastrtps_c/resource/msg__type_support_c.cpp.em index edf128f..8ad520b 100644 --- a/rosidl_typesupport_fastrtps_c/resource/msg__type_support_c.cpp.em +++ b/rosidl_typesupport_fastrtps_c/resource/msg__type_support_c.cpp.em @@ -356,6 +356,16 @@ else: uint32_t cdrSize; cdr >> cdrSize; size_t size = static_cast(cdrSize); + + // Check there are at least 'size' remaining bytes in the CDR stream before resizing + auto old_state = cdr.get_state(); + bool correct_size = cdr.jump(size); + cdr.set_state(old_state); + if (!correct_size) { + fprintf(stderr, "sequence size exceeds remaining buffer\n"); + return false; + } + if (ros_message->@(member.name).data) { @(array_fini)(&ros_message->@(member.name)); } diff --git a/rosidl_typesupport_fastrtps_cpp/resource/msg__type_support.cpp.em b/rosidl_typesupport_fastrtps_cpp/resource/msg__type_support.cpp.em index 3d430bd..0e2ed5a 100644 --- a/rosidl_typesupport_fastrtps_cpp/resource/msg__type_support.cpp.em +++ b/rosidl_typesupport_fastrtps_cpp/resource/msg__type_support.cpp.em @@ -235,6 +235,16 @@ cdr_deserialize( uint32_t cdrSize; cdr >> cdrSize; size_t size = static_cast(cdrSize); + + // Check there are at least 'size' remaining bytes in the CDR stream before resizing + auto old_state = cdr.get_state(); + bool correct_size = cdr.jump(size); + cdr.set_state(old_state); + if (!correct_size) { + fprintf(stderr, "sequence size exceeds remaining buffer\n"); + return false; + } + ros_message.@(member.name).resize(size); @[ if isinstance(member.type.value_type, BasicType) and member.type.value_type.typename not in ('boolean', 'wchar')]@ if (size > 0) { @@ -296,7 +306,7 @@ cdr_deserialize( @[end for]@ return true; -} +} // NOLINT(readability/fn_size) @{