Fix segmentation fault in mbedtls_test_buffer
This error occurs when free space in the buffer is in the middle (the buffer has come full circle) and function mbedtls_test_buffer_put is called. Then the arguments for memcpy are calculated incorrectly and program ends with segmentation fault
@@ -77,6 +77,11 @@ int mbedtls_test_buffer_put( mbedtls_test_buffer *buf,
return ( input_len == 0 ) ? 0 : -1;
}
+ /* Check if the buffer has not come full circle and free space is not in
+ * the middle */
+ if( buf->start + buf->content_length < buf->capacity )
+ {
+
/* Calculate the number of bytes that need to be placed at lower memory
* address */
if( buf->start + buf->content_length + input_len
@@ -89,8 +94,16 @@ int mbedtls_test_buffer_put( mbedtls_test_buffer *buf,
memcpy( buf->buffer + buf->start + buf->content_length, input,
input_len - overflow );
memcpy( buf->buffer, input + input_len - overflow, overflow );
- buf->content_length += input_len;
+ }
+ else
+ {
+ /* The buffer has come full circle and free space is in the middle */
+ memcpy( buf->buffer + buf->start + buf->content_length - buf->capacity,
+ input, input_len );
+ }
+
+ buf->content_length += input_len;
return input_len;
}
@@ -743,6 +756,16 @@ void test_callback_buffer_sanity()
TEST_ASSERT( mbedtls_test_buffer_put( &buf, NULL, 0 ) == 0 );
TEST_ASSERT( mbedtls_test_buffer_get( &buf, NULL, 0 ) == 0 );
+ /* Make sure calling put several times in the row is safe */
+
+ TEST_ASSERT( mbedtls_test_buffer_put( &buf, input, sizeof( input ) )
+ == sizeof( input ) );
+ TEST_ASSERT( mbedtls_test_buffer_get( &buf, output, 2 ) == 2 );
+ TEST_ASSERT( mbedtls_test_buffer_put( &buf, input, 1 ) == 1 );
+ TEST_ASSERT( mbedtls_test_buffer_put( &buf, input, 2 ) == 1 );
+ TEST_ASSERT( mbedtls_test_buffer_put( &buf, input, 2 ) == 0 );
+
+
exit:
mbedtls_test_buffer_free( &buf );
