blob: 5a8e21148a000a73a4fe35a8a3dcc7297e82046e [file] [log] [blame]
Azim Khanec024482017-05-09 17:20:21 +01001#line 2 "suites/helpers.function"
SimonB0269dad2016-02-17 23:34:30 +00002/*----------------------------------------------------------------------------*/
3/* Headers */
4
Simon Butcheredb7fd92016-05-17 13:35:51 +01005#include <stdlib.h>
6
Manuel Pégourié-Gonnard2cf5a7c2015-04-08 12:49:31 +02007#if defined(MBEDTLS_PLATFORM_C)
Manuel Pégourié-Gonnard7f809972015-03-09 17:05:11 +00008#include "mbedtls/platform.h"
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +02009#else
Rich Evans00ab4702015-02-06 13:43:58 +000010#include <stdio.h>
Manuel Pégourié-Gonnard2cf5a7c2015-04-08 12:49:31 +020011#define mbedtls_fprintf fprintf
Simon Butcher25731362016-09-30 13:11:29 +010012#define mbedtls_snprintf snprintf
13#define mbedtls_calloc calloc
Manuel Pégourié-Gonnard2cf5a7c2015-04-08 12:49:31 +020014#define mbedtls_free free
15#define mbedtls_exit exit
Simon Butcherb2d5dd12016-04-27 13:35:37 +010016#define mbedtls_time time
17#define mbedtls_time_t time_t
Janos Follath55abc212016-04-18 18:18:48 +010018#define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
19#define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +020020#endif
21
SimonB0269dad2016-02-17 23:34:30 +000022#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
23#include "mbedtls/memory_buffer_alloc.h"
24#endif
25
Simon Butchera6463452018-12-06 17:41:56 +000026#if defined(MBEDTLS_CHECK_PARAMS)
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +010027#include "mbedtls/platform_util.h"
Simon Butchera6463452018-12-06 17:41:56 +000028#include <setjmp.h>
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +010029#endif
Simon Butcher747f5fe2018-12-07 16:53:57 +000030
Paul Bakkerb3dcbc12011-03-13 16:57:25 +000031#ifdef _MSC_VER
32#include <basetsd.h>
Azim Khan0fa35042018-06-22 11:34:33 +010033typedef UINT8 uint8_t;
34typedef INT32 int32_t;
Paul Bakkerb3dcbc12011-03-13 16:57:25 +000035typedef UINT32 uint32_t;
Nicholas Wilson733676b2015-11-14 13:09:01 +000036#define strncasecmp _strnicmp
37#define strcasecmp _stricmp
Paul Bakkerb3dcbc12011-03-13 16:57:25 +000038#else
Manuel Pégourié-Gonnard93866642015-06-22 19:21:23 +020039#include <stdint.h>
Paul Bakkerb3dcbc12011-03-13 16:57:25 +000040#endif
41
Paul Bakker19343182013-08-16 13:31:10 +020042#include <string.h>
43
Janos Follath8ca53b52016-10-05 10:57:49 +010044#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
45#include <unistd.h>
Nicholas Wilson2682edf2017-12-05 12:08:15 +000046#include <strings.h>
Janos Follath8ca53b52016-10-05 10:57:49 +010047#endif
SimonB0269dad2016-02-17 23:34:30 +000048
Gilles Peskinebbc4b8d2021-06-11 14:13:53 +020049#if defined(MBEDTLS_BIGNUM_C)
50#include "mbedtls/bignum.h"
51#endif
52
Gilles Peskinec0713732021-01-29 21:17:11 +010053#if defined(MBEDTLS_THREADING_C) && defined(MBEDTLS_THREADING_PTHREAD) && \
54 defined(MBEDTLS_TEST_HOOKS)
55#include "mbedtls/threading.h"
56#define MBEDTLS_TEST_MUTEX_USAGE
57#endif
58
Manuel Pégourié-Gonnardf0828472020-08-25 11:26:37 +020059/*
60 * Define the two macros
61 *
62 * #define TEST_CF_SECRET(ptr, size)
63 * #define TEST_CF_PUBLIC(ptr, size)
64 *
65 * that can be used in tests to mark a memory area as secret (no branch or
66 * memory access should depend on it) or public (default, only needs to be
67 * marked explicitly when it was derived from secret data).
68 *
69 * Arguments:
70 * - ptr: a pointer to the memory area to be marked
71 * - size: the size in bytes of the memory area
72 *
73 * Implementation:
74 * The basic idea is that of ctgrind <https://github.com/agl/ctgrind>: we can
75 * re-use tools that were designed for checking use of uninitialized memory.
76 * This file contains two implementations: one based on MemorySanitizer, the
77 * other on valgrind's memcheck. If none of them is enabled, dummy macros that
78 * do nothing are defined for convenience.
79 */
Manuel Pégourié-Gonnarda2377222020-07-28 10:53:06 +020080#if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN)
81#include <sanitizer/msan_interface.h>
82
83/* Use macros to avoid messing up with origin tracking */
84#define TEST_CF_SECRET __msan_allocated_memory
85// void __msan_allocated_memory(const volatile void* data, size_t size);
86#define TEST_CF_PUBLIC __msan_unpoison
87// void __msan_unpoison(const volatile void *a, size_t size);
88
Manuel Pégourié-Gonnardf0828472020-08-25 11:26:37 +020089#elif defined(MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND)
90#include <valgrind/memcheck.h>
91
92#define TEST_CF_SECRET VALGRIND_MAKE_MEM_UNDEFINED
93// VALGRIND_MAKE_MEM_UNDEFINED(_qzz_addr, _qzz_len)
94#define TEST_CF_PUBLIC VALGRIND_MAKE_MEM_DEFINED
95// VALGRIND_MAKE_MEM_DEFINED(_qzz_addr, _qzz_len)
96
97#else /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN ||
98 MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND */
Manuel Pégourié-Gonnarda2377222020-07-28 10:53:06 +020099
100#define TEST_CF_SECRET(ptr, size)
101#define TEST_CF_PUBLIC(ptr, size)
102
103#endif /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN */
104
Azim Khand30ca132017-06-09 04:32:58 +0100105/* Type for Hex parameters */
Azim Khan5fcca462018-06-29 11:05:32 +0100106typedef struct data_tag
Azim Khand30ca132017-06-09 04:32:58 +0100107{
108 uint8_t * x;
109 uint32_t len;
Azim Khan5fcca462018-06-29 11:05:32 +0100110} data_t;
Azim Khand30ca132017-06-09 04:32:58 +0100111
SimonB0269dad2016-02-17 23:34:30 +0000112/*----------------------------------------------------------------------------*/
Azim Khan62a5d7d2018-06-29 10:02:54 +0100113/* Status and error constants */
SimonB0269dad2016-02-17 23:34:30 +0000114
Azim Khan62a5d7d2018-06-29 10:02:54 +0100115#define DEPENDENCY_SUPPORTED 0 /* Dependency supported by build */
116#define KEY_VALUE_MAPPING_FOUND 0 /* Integer expression found */
117#define DISPATCH_TEST_SUCCESS 0 /* Test dispatch successful */
SimonB8ca7bc42016-04-17 23:24:50 +0100118
Azim Khan62a5d7d2018-06-29 10:02:54 +0100119#define KEY_VALUE_MAPPING_NOT_FOUND -1 /* Integer expression not found */
120#define DEPENDENCY_NOT_SUPPORTED -2 /* Dependency not supported */
121#define DISPATCH_TEST_FN_NOT_FOUND -3 /* Test function not found */
122#define DISPATCH_INVALID_TEST_DATA -4 /* Invalid test parameter type.
123 Only int, string, binary data
124 and integer expressions are
125 allowed */
126#define DISPATCH_UNSUPPORTED_SUITE -5 /* Test suite not supported by the
127 build */
SimonB0269dad2016-02-17 23:34:30 +0000128
Simon Butcher6542f6c2018-12-09 22:09:59 +0000129typedef enum
130{
131 PARAMFAIL_TESTSTATE_IDLE = 0, /* No parameter failure call test */
132 PARAMFAIL_TESTSTATE_PENDING, /* Test call to the parameter failure
133 * is pending */
134 PARAMFAIL_TESTSTATE_CALLED /* The test call to the parameter
135 * failure function has been made */
136} paramfail_test_state_t;
137
SimonB0269dad2016-02-17 23:34:30 +0000138
139/*----------------------------------------------------------------------------*/
140/* Macros */
141
Simon Butchera6463452018-12-06 17:41:56 +0000142/**
143 * \brief This macro tests the expression passed to it as a test step or
144 * individual test in a test case.
145 *
146 * It allows a library function to return a value and return an error
147 * code that can be tested.
148 *
149 * When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +0100150 * callback, MBEDTLS_PARAM_FAILED(), will be assumed to be a test
151 * failure.
Simon Butchera6463452018-12-06 17:41:56 +0000152 *
153 * This macro is not suitable for negative parameter validation tests,
154 * as it assumes the test step will not create an error.
155 *
156 * \param TEST The test expression to be tested.
157 */
Simon Butcher6542f6c2018-12-09 22:09:59 +0000158#define TEST_ASSERT( TEST ) \
159 do { \
160 if( ! (TEST) ) \
161 { \
162 test_fail( #TEST, __LINE__, __FILE__ ); \
163 goto exit; \
164 } \
SimonB0269dad2016-02-17 23:34:30 +0000165 } while( 0 )
166
Gilles Peskine5f45bd22021-05-31 15:40:31 +0200167/** Evaluate two expressions and fail the test case if they have different
168 * values.
169 *
170 * \param expr1 An expression to evaluate.
171 * \param expr2 The expected value of \p expr1. This can be any
172 * expression, but it is typically a constant.
173 */
174#define TEST_EQUAL( expr1, expr2 ) \
175 TEST_ASSERT( ( expr1 ) == ( expr2 ) )
176
177/** Allocate memory dynamically and fail the test case if this fails.
178 * The allocated memory will be filled with zeros.
179 *
180 * You must set \p pointer to \c NULL before calling this macro and
181 * put `mbedtls_free( pointer )` in the test's cleanup code.
182 *
183 * If \p length is zero, the resulting \p pointer will be \c NULL.
184 * This is usually what we want in tests since API functions are
185 * supposed to accept null pointers when a buffer size is zero.
186 *
187 * This macro expands to an instruction, not an expression.
188 * It may jump to the \c exit label.
189 *
190 * \param pointer An lvalue where the address of the allocated buffer
191 * will be stored.
192 * This expression may be evaluated multiple times.
193 * \param length Number of elements to allocate.
194 * This expression may be evaluated multiple times.
195 *
196 */
197#define ASSERT_ALLOC( pointer, length ) \
198 do \
199 { \
200 TEST_ASSERT( ( pointer ) == NULL ); \
201 if( ( length ) != 0 ) \
202 { \
203 ( pointer ) = mbedtls_calloc( sizeof( *( pointer ) ), \
204 ( length ) ); \
205 TEST_ASSERT( ( pointer ) != NULL ); \
206 } \
207 } \
208 while( 0 )
209
210/** Allocate memory dynamically. If the allocation fails, skip the test case.
211 *
212 * This macro behaves like #ASSERT_ALLOC, except that if the allocation
213 * fails, it marks the test as skipped rather than failed.
214 */
215#define ASSERT_ALLOC_WEAK( pointer, length ) \
216 do \
217 { \
218 TEST_ASSERT( ( pointer ) == NULL ); \
219 if( ( length ) != 0 ) \
220 { \
221 ( pointer ) = mbedtls_calloc( sizeof( *( pointer ) ), \
222 ( length ) ); \
223 TEST_ASSUME( ( pointer ) != NULL ); \
224 } \
225 } \
226 while( 0 )
Ronald Cron8e8898d2020-07-30 14:18:02 +0200227/** Compare two buffers and fail the test case if they differ.
228 *
229 * This macro expands to an instruction, not an expression.
230 * It may jump to the \c exit label.
231 *
232 * \param p1 Pointer to the start of the first buffer.
233 * \param size1 Size of the first buffer in bytes.
234 * This expression may be evaluated multiple times.
235 * \param p2 Pointer to the start of the second buffer.
236 * \param size2 Size of the second buffer in bytes.
237 * This expression may be evaluated multiple times.
238 */
239#define ASSERT_COMPARE( p1, size1, p2, size2 ) \
240 do \
241 { \
242 TEST_ASSERT( ( size1 ) == ( size2 ) ); \
243 if( ( size1 ) != 0 ) \
244 TEST_ASSERT( memcmp( ( p1 ), ( p2 ), ( size1 ) ) == 0 ); \
245 } \
246 while( 0 )
247
Hanno Beckerd3369f62019-07-05 13:31:30 +0100248/**
249 * \brief This macro tests the expression passed to it and skips the
250 * running test if it doesn't evaluate to 'true'.
251 *
252 * \param TEST The test expression to be tested.
253 */
254#define TEST_ASSUME( TEST ) \
255 do { \
256 if( ! (TEST) ) \
257 { \
258 test_skip( #TEST, __LINE__, __FILE__ ); \
259 goto exit; \
260 } \
261 } while( 0 )
262
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +0100263#if defined(MBEDTLS_CHECK_PARAMS) && !defined(MBEDTLS_PARAM_FAILED_ALT)
Simon Butchera6463452018-12-06 17:41:56 +0000264/**
265 * \brief This macro tests the statement passed to it as a test step or
266 * individual test in a test case. The macro assumes the test will fail
267 * and will generate an error.
268 *
269 * It allows a library function to return a value and tests the return
270 * code on return to confirm the given error code was returned.
271 *
272 * When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +0100273 * callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
Simon Butchera6463452018-12-06 17:41:56 +0000274 * expected failure, and the test will pass.
275 *
276 * This macro is intended for negative parameter validation tests,
277 * where the failing function may return an error value or call
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +0100278 * MBEDTLS_PARAM_FAILED() to indicate the error.
Simon Butchera6463452018-12-06 17:41:56 +0000279 *
280 * \param PARAM_ERROR_VALUE The expected error code.
281 *
282 * \param TEST The test expression to be tested.
283 */
Simon Butcher6542f6c2018-12-09 22:09:59 +0000284#define TEST_INVALID_PARAM_RET( PARAM_ERR_VALUE, TEST ) \
285 do { \
286 test_info.paramfail_test_state = PARAMFAIL_TESTSTATE_PENDING; \
Manuel Pégourié-Gonnardacfdc622018-12-11 10:36:21 +0100287 if( (TEST) != (PARAM_ERR_VALUE) || \
Simon Butcher6542f6c2018-12-09 22:09:59 +0000288 test_info.paramfail_test_state != PARAMFAIL_TESTSTATE_CALLED ) \
289 { \
290 test_fail( #TEST, __LINE__, __FILE__ ); \
291 goto exit; \
292 } \
293 } while( 0 )
Simon Butchera6463452018-12-06 17:41:56 +0000294
295/**
296 * \brief This macro tests the statement passed to it as a test step or
297 * individual test in a test case. The macro assumes the test will fail
298 * and will generate an error.
299 *
300 * It assumes the library function under test cannot return a value and
301 * assumes errors can only be indicated byt calls to
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +0100302 * MBEDTLS_PARAM_FAILED().
Simon Butchera6463452018-12-06 17:41:56 +0000303 *
304 * When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +0100305 * callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
Simon Butchera6463452018-12-06 17:41:56 +0000306 * expected failure. If MBEDTLS_CHECK_PARAMS is not enabled, no test
307 * can be made.
308 *
309 * This macro is intended for negative parameter validation tests,
310 * where the failing function can only return an error by calling
Manuel Pégourié-Gonnarda2b0e272018-12-10 15:23:58 +0100311 * MBEDTLS_PARAM_FAILED() to indicate the error.
Simon Butchera6463452018-12-06 17:41:56 +0000312 *
313 * \param TEST The test expression to be tested.
314 */
Simon Butcher6542f6c2018-12-09 22:09:59 +0000315#define TEST_INVALID_PARAM( TEST ) \
316 do { \
317 memcpy(jmp_tmp, param_fail_jmp, sizeof(jmp_buf)); \
Manuel Pégourié-Gonnardaae10fa2018-12-12 10:24:19 +0100318 if( setjmp( param_fail_jmp ) == 0 ) \
Simon Butcher6542f6c2018-12-09 22:09:59 +0000319 { \
320 TEST; \
321 test_fail( #TEST, __LINE__, __FILE__ ); \
322 goto exit; \
323 } \
324 memcpy(param_fail_jmp, jmp_tmp, sizeof(jmp_buf)); \
Simon Butchera6463452018-12-06 17:41:56 +0000325 } while( 0 )
Manuel Pégourié-Gonnard54e7f312018-12-12 11:56:09 +0100326#endif /* MBEDTLS_CHECK_PARAMS && !MBEDTLS_PARAM_FAILED_ALT */
Simon Butchera6463452018-12-06 17:41:56 +0000327
Manuel Pégourié-Gonnard44c5d582018-12-10 16:56:14 +0100328/**
329 * \brief This macro tests the statement passed to it as a test step or
330 * individual test in a test case. The macro assumes the test will not fail.
331 *
332 * It assumes the library function under test cannot return a value and
333 * assumes errors can only be indicated by calls to
334 * MBEDTLS_PARAM_FAILED().
335 *
336 * When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
337 * callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
338 * expected failure. If MBEDTLS_CHECK_PARAMS is not enabled, no test
339 * can be made.
340 *
Manuel Pégourié-Gonnardcd2b29c2018-12-12 10:23:57 +0100341 * This macro is intended to test that functions returning void
Manuel Pégourié-Gonnard44c5d582018-12-10 16:56:14 +0100342 * accept all of the parameter values they're supposed to accept - eg
343 * that they don't call MBEDTLS_PARAM_FAILED() when a parameter
Manuel Pégourié-Gonnardcd2b29c2018-12-12 10:23:57 +0100344 * that's allowed to be NULL happens to be NULL.
Manuel Pégourié-Gonnard44c5d582018-12-10 16:56:14 +0100345 *
346 * Note: for functions that return something other that void,
347 * checking that they accept all the parameters they're supposed to
348 * accept is best done by using TEST_ASSERT() and checking the return
349 * value as well.
350 *
Manuel Pégourié-Gonnard54e7f312018-12-12 11:56:09 +0100351 * Note: this macro is available even when #MBEDTLS_CHECK_PARAMS is
352 * disabled, as it makes sense to check that the functions accept all
353 * legal values even if this option is disabled - only in that case,
Manuel Pégourié-Gonnarde7306d32018-12-13 09:45:49 +0100354 * the test is more about whether the function segfaults than about
Manuel Pégourié-Gonnard54e7f312018-12-12 11:56:09 +0100355 * whether it invokes MBEDTLS_PARAM_FAILED().
356 *
Manuel Pégourié-Gonnard44c5d582018-12-10 16:56:14 +0100357 * \param TEST The test expression to be tested.
358 */
359#define TEST_VALID_PARAM( TEST ) \
360 TEST_ASSERT( ( TEST, 1 ) );
Simon Butchera6463452018-12-06 17:41:56 +0000361
Gilles Peskine137d31b2019-06-07 14:52:07 +0200362#define TEST_HELPER_ASSERT(a) if( !( a ) ) \
Rich Evans4c091142015-02-02 12:04:10 +0000363{ \
Manuel Pégourié-Gonnard2cf5a7c2015-04-08 12:49:31 +0200364 mbedtls_fprintf( stderr, "Assertion Failed at %s:%d - %s\n", \
Rich Evans4c091142015-02-02 12:04:10 +0000365 __FILE__, __LINE__, #a ); \
Manuel Pégourié-Gonnard2cf5a7c2015-04-08 12:49:31 +0200366 mbedtls_exit( 1 ); \
Rich Evans4c091142015-02-02 12:04:10 +0000367}
368
Ronald Cron07c83f22020-04-06 09:50:58 +0200369#if defined(__GNUC__)
370/* Test if arg and &(arg)[0] have the same type. This is true if arg is
371 * an array but not if it's a pointer. */
372#define IS_ARRAY_NOT_POINTER( arg ) \
373 ( ! __builtin_types_compatible_p( __typeof__( arg ), \
374 __typeof__( &( arg )[0] ) ) )
375#else
376/* On platforms where we don't know how to implement this check,
377 * omit it. Oh well, a non-portable check is better than nothing. */
378#define IS_ARRAY_NOT_POINTER( arg ) 1
379#endif
380
381/* A compile-time constant with the value 0. If `const_expr` is not a
382 * compile-time constant with a nonzero value, cause a compile-time error. */
383#define STATIC_ASSERT_EXPR( const_expr ) \
makise-homura50f6a192020-08-23 00:39:15 +0300384 ( 0 && sizeof( struct { unsigned int STATIC_ASSERT : 1 - 2 * ! ( const_expr ); } ) )
Ronald Cron07c83f22020-04-06 09:50:58 +0200385/* Return the scalar value `value` (possibly promoted). This is a compile-time
386 * constant if `value` is. `condition` must be a compile-time constant.
387 * If `condition` is false, arrange to cause a compile-time error. */
388#define STATIC_ASSERT_THEN_RETURN( condition, value ) \
389 ( STATIC_ASSERT_EXPR( condition ) ? 0 : ( value ) )
390
391#define ARRAY_LENGTH_UNSAFE( array ) \
392 ( sizeof( array ) / sizeof( *( array ) ) )
393/** Return the number of elements of a static or stack array.
394 *
395 * \param array A value of array (not pointer) type.
396 *
397 * \return The number of elements of the array.
398 */
399#define ARRAY_LENGTH( array ) \
400 ( STATIC_ASSERT_THEN_RETURN( IS_ARRAY_NOT_POINTER( array ), \
401 ARRAY_LENGTH_UNSAFE( array ) ) )
402
Paul Bakkerb3dcbc12011-03-13 16:57:25 +0000403/*
404 * 32-bit integer manipulation macros (big endian)
405 */
Paul Bakker5c2364c2012-10-01 14:41:15 +0000406#ifndef GET_UINT32_BE
407#define GET_UINT32_BE(n,b,i) \
Paul Bakkerb3dcbc12011-03-13 16:57:25 +0000408{ \
Paul Bakker5c2364c2012-10-01 14:41:15 +0000409 (n) = ( (uint32_t) (b)[(i) ] << 24 ) \
410 | ( (uint32_t) (b)[(i) + 1] << 16 ) \
411 | ( (uint32_t) (b)[(i) + 2] << 8 ) \
412 | ( (uint32_t) (b)[(i) + 3] ); \
Paul Bakkerb3dcbc12011-03-13 16:57:25 +0000413}
414#endif
415
Paul Bakker5c2364c2012-10-01 14:41:15 +0000416#ifndef PUT_UINT32_BE
417#define PUT_UINT32_BE(n,b,i) \
Paul Bakkerb3dcbc12011-03-13 16:57:25 +0000418{ \
419 (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
420 (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
421 (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
422 (b)[(i) + 3] = (unsigned char) ( (n) ); \
423}
424#endif
425
SimonB0269dad2016-02-17 23:34:30 +0000426
427/*----------------------------------------------------------------------------*/
SimonB8ca7bc42016-04-17 23:24:50 +0100428/* Global variables */
429
Hanno Beckerd3369f62019-07-05 13:31:30 +0100430typedef enum
431{
432 TEST_RESULT_SUCCESS = 0,
433 TEST_RESULT_FAILED,
434 TEST_RESULT_SKIPPED
435} test_result_t;
436
Andres Amaya Garcia3f50f512017-10-01 16:42:29 +0100437static struct
438{
Simon Butcher6542f6c2018-12-09 22:09:59 +0000439 paramfail_test_state_t paramfail_test_state;
Hanno Beckerd3369f62019-07-05 13:31:30 +0100440 test_result_t result;
Andres Amaya Garcia3f50f512017-10-01 16:42:29 +0100441 const char *test;
442 const char *filename;
443 int line_no;
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100444#if defined(MBEDTLS_TEST_MUTEX_USAGE)
445 const char *mutex_usage_error;
446#endif
Andres Amaya Garcia3f50f512017-10-01 16:42:29 +0100447}
448test_info;
SimonB8ca7bc42016-04-17 23:24:50 +0100449
Andrzej Kurek32a675f2018-04-13 06:16:04 -0400450#if defined(MBEDTLS_PLATFORM_C)
Andrzej Kurek1152fa82018-04-13 05:15:17 -0400451mbedtls_platform_context platform_ctx;
Andrzej Kurek32a675f2018-04-13 06:16:04 -0400452#endif
SimonB8ca7bc42016-04-17 23:24:50 +0100453
Simon Butchera6463452018-12-06 17:41:56 +0000454#if defined(MBEDTLS_CHECK_PARAMS)
455jmp_buf param_fail_jmp;
Simon Butcher6542f6c2018-12-09 22:09:59 +0000456jmp_buf jmp_tmp;
Simon Butchera6463452018-12-06 17:41:56 +0000457#endif
458
SimonB8ca7bc42016-04-17 23:24:50 +0100459/*----------------------------------------------------------------------------*/
Hanno Becker47deec42017-07-24 12:27:09 +0100460/* Helper flags for complex dependencies */
461
462/* Indicates whether we expect mbedtls_entropy_init
463 * to initialize some strong entropy source. */
464#if defined(MBEDTLS_TEST_NULL_ENTROPY) || \
465 ( !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) && \
466 ( !defined(MBEDTLS_NO_PLATFORM_ENTROPY) || \
467 defined(MBEDTLS_HAVEGE_C) || \
468 defined(MBEDTLS_ENTROPY_HARDWARE_ALT) || \
469 defined(ENTROPY_NV_SEED) ) )
Hanno Beckerd4a872e2017-09-07 08:09:33 +0100470#define ENTROPY_HAVE_STRONG
Hanno Becker47deec42017-07-24 12:27:09 +0100471#endif
472
473
474/*----------------------------------------------------------------------------*/
SimonB0269dad2016-02-17 23:34:30 +0000475/* Helper Functions */
Simon Butcher6542f6c2018-12-09 22:09:59 +0000476
Simon Butcherecff2192018-10-03 16:17:41 +0100477void test_fail( const char *test, int line_no, const char* filename )
Simon Butcher6542f6c2018-12-09 22:09:59 +0000478{
Gilles Peskinedfb5cff2020-08-29 15:18:23 +0200479 if( test_info.result == TEST_RESULT_FAILED )
480 {
481 /* We've already recorded the test as having failed. Don't
482 * overwrite any previous information about the failure. */
483 return;
484 }
Hanno Beckerd3369f62019-07-05 13:31:30 +0100485 test_info.result = TEST_RESULT_FAILED;
486 test_info.test = test;
487 test_info.line_no = line_no;
488 test_info.filename = filename;
489}
490
491void test_skip( const char *test, int line_no, const char* filename )
492{
493 test_info.result = TEST_RESULT_SKIPPED;
Simon Butcher6542f6c2018-12-09 22:09:59 +0000494 test_info.test = test;
495 test_info.line_no = line_no;
496 test_info.filename = filename;
497}
498
Andrzej Kurek32a675f2018-04-13 06:16:04 -0400499static int platform_setup()
500{
Andrzej Kurekf13ca952018-04-18 04:14:31 -0400501 int ret = 0;
Andrzej Kurek32a675f2018-04-13 06:16:04 -0400502#if defined(MBEDTLS_PLATFORM_C)
Andrzej Kurekf13ca952018-04-18 04:14:31 -0400503 ret = mbedtls_platform_setup( &platform_ctx );
Andrzej Kurek32a675f2018-04-13 06:16:04 -0400504#endif /* MBEDTLS_PLATFORM_C */
Andrzej Kurekf13ca952018-04-18 04:14:31 -0400505 return( ret );
Andrzej Kurek32a675f2018-04-13 06:16:04 -0400506}
507
508static void platform_teardown()
509{
510#if defined(MBEDTLS_PLATFORM_C)
511 mbedtls_platform_teardown( &platform_ctx );
512#endif /* MBEDTLS_PLATFORM_C */
513}
SimonB0269dad2016-02-17 23:34:30 +0000514
Simon Butchera6463452018-12-06 17:41:56 +0000515#if defined(MBEDTLS_CHECK_PARAMS)
Manuel Pégourié-Gonnard3ef6a6d2018-12-10 14:31:45 +0100516void mbedtls_param_failed( const char *failure_condition,
517 const char *file,
518 int line )
Simon Butchera6463452018-12-06 17:41:56 +0000519{
Simon Butcher6542f6c2018-12-09 22:09:59 +0000520 /* If we are testing the callback function... */
Manuel Pégourié-Gonnardaae10fa2018-12-12 10:24:19 +0100521 if( test_info.paramfail_test_state == PARAMFAIL_TESTSTATE_PENDING )
Simon Butcher6542f6c2018-12-09 22:09:59 +0000522 {
523 test_info.paramfail_test_state = PARAMFAIL_TESTSTATE_CALLED;
524 }
525 else
526 {
527 /* ...else we treat this as an error */
Simon Butchera6463452018-12-06 17:41:56 +0000528
Simon Butcher6542f6c2018-12-09 22:09:59 +0000529 /* Record the location of the failure, but not as a failure yet, in case
530 * it was part of the test */
531 test_fail( failure_condition, line, file );
Hanno Beckerd3369f62019-07-05 13:31:30 +0100532 test_info.result = TEST_RESULT_SUCCESS;
Simon Butcher6542f6c2018-12-09 22:09:59 +0000533
534 longjmp( param_fail_jmp, 1 );
535 }
Simon Butchera6463452018-12-06 17:41:56 +0000536}
537#endif
538
Janos Follath8ca53b52016-10-05 10:57:49 +0100539#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
gufe44650ce762020-07-30 09:02:27 +0200540static int redirect_output( FILE* out_stream, const char* path )
Janos Follath8ca53b52016-10-05 10:57:49 +0100541{
gufe44650ce762020-07-30 09:02:27 +0200542 int out_fd, dup_fd;
543 FILE* path_stream;
Janos Follath8ca53b52016-10-05 10:57:49 +0100544
gufe44650ce762020-07-30 09:02:27 +0200545 out_fd = fileno( out_stream );
546 dup_fd = dup( out_fd );
547
548 if( dup_fd == -1 )
Janos Follath8ca53b52016-10-05 10:57:49 +0100549 {
gufe44650ce762020-07-30 09:02:27 +0200550 return( -1 );
Janos Follath8ca53b52016-10-05 10:57:49 +0100551 }
552
gufe44650ce762020-07-30 09:02:27 +0200553 path_stream = fopen( path, "w" );
554 if( path_stream == NULL )
Janos Follath8ca53b52016-10-05 10:57:49 +0100555 {
gufe44650ce762020-07-30 09:02:27 +0200556 close( dup_fd );
557 return( -1 );
Janos Follath8ca53b52016-10-05 10:57:49 +0100558 }
559
gufe44650ce762020-07-30 09:02:27 +0200560 fflush( out_stream );
561 if( dup2( fileno( path_stream ), out_fd ) == -1 )
562 {
563 close( dup_fd );
564 fclose( path_stream );
565 return( -1 );
566 }
567
568 fclose( path_stream );
569 return( dup_fd );
Janos Follath8ca53b52016-10-05 10:57:49 +0100570}
571
gufe44650ce762020-07-30 09:02:27 +0200572static int restore_output( FILE* out_stream, int dup_fd )
Janos Follath8ca53b52016-10-05 10:57:49 +0100573{
gufe44650ce762020-07-30 09:02:27 +0200574 int out_fd = fileno( out_stream );
Janos Follath8ca53b52016-10-05 10:57:49 +0100575
gufe44650ce762020-07-30 09:02:27 +0200576 fflush( out_stream );
577 if( dup2( dup_fd, out_fd ) == -1 )
Janos Follath8ca53b52016-10-05 10:57:49 +0100578 {
gufe44650ce762020-07-30 09:02:27 +0200579 close( out_fd );
580 close( dup_fd );
581 return( -1 );
Janos Follath8ca53b52016-10-05 10:57:49 +0100582 }
583
gufe44650ce762020-07-30 09:02:27 +0200584 close( dup_fd );
585 return( 0 );
Simon Butchere0192962016-10-12 23:07:30 +0100586}
Janos Follath8ca53b52016-10-05 10:57:49 +0100587#endif /* __unix__ || __APPLE__ __MACH__ */
588
Ronald Crona0c9ff32020-06-08 17:05:57 +0200589int mbedtls_test_unhexify( unsigned char *obuf, const char *ibuf )
Paul Bakker367dae42009-06-28 21:50:27 +0000590{
591 unsigned char c, c2;
Rich Evans4c091142015-02-02 12:04:10 +0000592 int len = strlen( ibuf ) / 2;
Gilles Peskine137d31b2019-06-07 14:52:07 +0200593 TEST_HELPER_ASSERT( strlen( ibuf ) % 2 == 0 ); /* must be even number of bytes */
Paul Bakker367dae42009-06-28 21:50:27 +0000594
Rich Evans4c091142015-02-02 12:04:10 +0000595 while( *ibuf != 0 )
Paul Bakker367dae42009-06-28 21:50:27 +0000596 {
597 c = *ibuf++;
598 if( c >= '0' && c <= '9' )
599 c -= '0';
600 else if( c >= 'a' && c <= 'f' )
601 c -= 'a' - 10;
602 else if( c >= 'A' && c <= 'F' )
603 c -= 'A' - 10;
604 else
Gilles Peskine137d31b2019-06-07 14:52:07 +0200605 TEST_HELPER_ASSERT( 0 );
Paul Bakker367dae42009-06-28 21:50:27 +0000606
607 c2 = *ibuf++;
608 if( c2 >= '0' && c2 <= '9' )
609 c2 -= '0';
610 else if( c2 >= 'a' && c2 <= 'f' )
611 c2 -= 'a' - 10;
612 else if( c2 >= 'A' && c2 <= 'F' )
613 c2 -= 'A' - 10;
614 else
Gilles Peskine137d31b2019-06-07 14:52:07 +0200615 TEST_HELPER_ASSERT( 0 );
Paul Bakker367dae42009-06-28 21:50:27 +0000616
617 *obuf++ = ( c << 4 ) | c2;
618 }
619
620 return len;
621}
622
Ronald Crona0c9ff32020-06-08 17:05:57 +0200623void mbedtls_test_hexify( unsigned char *obuf, const unsigned char *ibuf, int len )
Paul Bakker367dae42009-06-28 21:50:27 +0000624{
625 unsigned char l, h;
626
Rich Evans42914452015-02-02 12:09:25 +0000627 while( len != 0 )
Paul Bakker367dae42009-06-28 21:50:27 +0000628 {
Rich Evans42914452015-02-02 12:09:25 +0000629 h = *ibuf / 16;
630 l = *ibuf % 16;
Paul Bakker367dae42009-06-28 21:50:27 +0000631
632 if( h < 10 )
633 *obuf++ = '0' + h;
634 else
635 *obuf++ = 'a' + h - 10;
636
637 if( l < 10 )
638 *obuf++ = '0' + l;
639 else
640 *obuf++ = 'a' + l - 10;
641
642 ++ibuf;
643 len--;
644 }
645}
Paul Bakker9dcc3222011-03-08 14:16:06 +0000646
647/**
Manuel Pégourié-Gonnard0dc5e0d2014-06-13 21:09:26 +0200648 * Allocate and zeroize a buffer.
649 *
650 * If the size if zero, a pointer to a zeroized 1-byte buffer is returned.
651 *
652 * For convenience, dies if allocation fails.
653 */
654static unsigned char *zero_alloc( size_t len )
655{
656 void *p;
Rich Evans42914452015-02-02 12:09:25 +0000657 size_t actual_len = ( len != 0 ) ? len : 1;
Manuel Pégourié-Gonnard0dc5e0d2014-06-13 21:09:26 +0200658
Manuel Pégourié-Gonnard7551cb92015-05-26 16:04:06 +0200659 p = mbedtls_calloc( 1, actual_len );
Gilles Peskine137d31b2019-06-07 14:52:07 +0200660 TEST_HELPER_ASSERT( p != NULL );
Manuel Pégourié-Gonnard0dc5e0d2014-06-13 21:09:26 +0200661
662 memset( p, 0x00, actual_len );
663
664 return( p );
665}
666
667/**
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +0200668 * Allocate and fill a buffer from hex data.
669 *
670 * The buffer is sized exactly as needed. This allows to detect buffer
671 * overruns (including overreads) when running the test suite under valgrind.
672 *
Manuel Pégourié-Gonnard0dc5e0d2014-06-13 21:09:26 +0200673 * If the size if zero, a pointer to a zeroized 1-byte buffer is returned.
674 *
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +0200675 * For convenience, dies if allocation fails.
676 */
Simon Butcherecff2192018-10-03 16:17:41 +0100677unsigned char *unhexify_alloc( const char *ibuf, size_t *olen )
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +0200678{
679 unsigned char *obuf;
680
Rich Evans42914452015-02-02 12:09:25 +0000681 *olen = strlen( ibuf ) / 2;
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +0200682
Manuel Pégourié-Gonnard0dc5e0d2014-06-13 21:09:26 +0200683 if( *olen == 0 )
684 return( zero_alloc( *olen ) );
685
Manuel Pégourié-Gonnard7551cb92015-05-26 16:04:06 +0200686 obuf = mbedtls_calloc( 1, *olen );
Gilles Peskine137d31b2019-06-07 14:52:07 +0200687 TEST_HELPER_ASSERT( obuf != NULL );
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +0200688
Ronald Crona0c9ff32020-06-08 17:05:57 +0200689 (void) mbedtls_test_unhexify( obuf, ibuf );
Manuel Pégourié-Gonnard3d49b9d2014-06-06 14:48:09 +0200690
691 return( obuf );
692}
693
694/**
Paul Bakker9dcc3222011-03-08 14:16:06 +0000695 * This function just returns data from rand().
Paul Bakker997bbd12011-03-13 15:45:42 +0000696 * Although predictable and often similar on multiple
697 * runs, this does not result in identical random on
698 * each run. So do not use this if the results of a
699 * test depend on the random data that is generated.
Paul Bakker9dcc3222011-03-08 14:16:06 +0000700 *
701 * rng_state shall be NULL.
702 */
Paul Bakkera3d195c2011-11-27 21:07:34 +0000703static int rnd_std_rand( void *rng_state, unsigned char *output, size_t len )
Paul Bakker9dcc3222011-03-08 14:16:06 +0000704{
gufe443fa7c642020-08-03 17:56:50 +0200705#if !defined(__OpenBSD__) && !defined(__NetBSD__)
Paul Bakkera3d195c2011-11-27 21:07:34 +0000706 size_t i;
707
Paul Bakker9dcc3222011-03-08 14:16:06 +0000708 if( rng_state != NULL )
709 rng_state = NULL;
710
Paul Bakkera3d195c2011-11-27 21:07:34 +0000711 for( i = 0; i < len; ++i )
712 output[i] = rand();
Paul Bakkerf96f7b62014-04-30 16:02:38 +0200713#else
714 if( rng_state != NULL )
715 rng_state = NULL;
716
717 arc4random_buf( output, len );
gufe443fa7c642020-08-03 17:56:50 +0200718#endif /* !OpenBSD && !NetBSD */
Paul Bakkera3d195c2011-11-27 21:07:34 +0000719
720 return( 0 );
Paul Bakker9dcc3222011-03-08 14:16:06 +0000721}
722
723/**
724 * This function only returns zeros
725 *
726 * rng_state shall be NULL.
727 */
Simon Butcherecff2192018-10-03 16:17:41 +0100728int rnd_zero_rand( void *rng_state, unsigned char *output, size_t len )
Paul Bakker9dcc3222011-03-08 14:16:06 +0000729{
730 if( rng_state != NULL )
731 rng_state = NULL;
732
Paul Bakkera3d195c2011-11-27 21:07:34 +0000733 memset( output, 0, len );
734
Paul Bakker9dcc3222011-03-08 14:16:06 +0000735 return( 0 );
736}
737
738typedef struct
739{
740 unsigned char *buf;
Paul Bakkera3d195c2011-11-27 21:07:34 +0000741 size_t length;
Paul Bakker997bbd12011-03-13 15:45:42 +0000742} rnd_buf_info;
Paul Bakker9dcc3222011-03-08 14:16:06 +0000743
744/**
745 * This function returns random based on a buffer it receives.
746 *
Paul Bakker997bbd12011-03-13 15:45:42 +0000747 * rng_state shall be a pointer to a rnd_buf_info structure.
Manuel Pégourié-Gonnarde670f902015-10-30 09:23:19 +0100748 *
Paul Bakker997bbd12011-03-13 15:45:42 +0000749 * The number of bytes released from the buffer on each call to
750 * the random function is specified by per_call. (Can be between
751 * 1 and 4)
Paul Bakker9dcc3222011-03-08 14:16:06 +0000752 *
753 * After the buffer is empty it will return rand();
754 */
Simon Butcherecff2192018-10-03 16:17:41 +0100755int rnd_buffer_rand( void *rng_state, unsigned char *output, size_t len )
Paul Bakker9dcc3222011-03-08 14:16:06 +0000756{
Paul Bakker997bbd12011-03-13 15:45:42 +0000757 rnd_buf_info *info = (rnd_buf_info *) rng_state;
Paul Bakkera3d195c2011-11-27 21:07:34 +0000758 size_t use_len;
Paul Bakker9dcc3222011-03-08 14:16:06 +0000759
760 if( rng_state == NULL )
Paul Bakkera3d195c2011-11-27 21:07:34 +0000761 return( rnd_std_rand( NULL, output, len ) );
Paul Bakker9dcc3222011-03-08 14:16:06 +0000762
Paul Bakkera3d195c2011-11-27 21:07:34 +0000763 use_len = len;
764 if( len > info->length )
765 use_len = info->length;
Paul Bakker997bbd12011-03-13 15:45:42 +0000766
Paul Bakkera3d195c2011-11-27 21:07:34 +0000767 if( use_len )
Paul Bakker9dcc3222011-03-08 14:16:06 +0000768 {
Paul Bakkera3d195c2011-11-27 21:07:34 +0000769 memcpy( output, info->buf, use_len );
770 info->buf += use_len;
771 info->length -= use_len;
Paul Bakker9dcc3222011-03-08 14:16:06 +0000772 }
773
Paul Bakkera3d195c2011-11-27 21:07:34 +0000774 if( len - use_len > 0 )
775 return( rnd_std_rand( NULL, output + use_len, len - use_len ) );
776
777 return( 0 );
Paul Bakker9dcc3222011-03-08 14:16:06 +0000778}
Paul Bakker997bbd12011-03-13 15:45:42 +0000779
780/**
781 * Info structure for the pseudo random function
782 *
783 * Key should be set at the start to a test-unique value.
Paul Bakkerb3dcbc12011-03-13 16:57:25 +0000784 * Do not forget endianness!
Paul Bakker997bbd12011-03-13 15:45:42 +0000785 * State( v0, v1 ) should be set to zero.
786 */
787typedef struct
788{
Paul Bakkerb3dcbc12011-03-13 16:57:25 +0000789 uint32_t key[16];
Paul Bakker997bbd12011-03-13 15:45:42 +0000790 uint32_t v0, v1;
791} rnd_pseudo_info;
792
793/**
794 * This function returns random based on a pseudo random function.
795 * This means the results should be identical on all systems.
796 * Pseudo random is based on the XTEA encryption algorithm to
797 * generate pseudorandom.
798 *
799 * rng_state shall be a pointer to a rnd_pseudo_info structure.
800 */
Simon Butcherecff2192018-10-03 16:17:41 +0100801int rnd_pseudo_rand( void *rng_state, unsigned char *output, size_t len )
Paul Bakker997bbd12011-03-13 15:45:42 +0000802{
803 rnd_pseudo_info *info = (rnd_pseudo_info *) rng_state;
Paul Bakkera3d195c2011-11-27 21:07:34 +0000804 uint32_t i, *k, sum, delta=0x9E3779B9;
Manuel Pégourié-Gonnard217a29c2014-01-03 11:59:09 +0100805 unsigned char result[4], *out = output;
Paul Bakker997bbd12011-03-13 15:45:42 +0000806
807 if( rng_state == NULL )
Paul Bakkera3d195c2011-11-27 21:07:34 +0000808 return( rnd_std_rand( NULL, output, len ) );
Paul Bakker997bbd12011-03-13 15:45:42 +0000809
Paul Bakkerb3dcbc12011-03-13 16:57:25 +0000810 k = info->key;
Paul Bakkera3d195c2011-11-27 21:07:34 +0000811
812 while( len > 0 )
Paul Bakker997bbd12011-03-13 15:45:42 +0000813 {
Paul Bakker40dd5302012-05-15 15:02:38 +0000814 size_t use_len = ( len > 4 ) ? 4 : len;
Paul Bakkera3d195c2011-11-27 21:07:34 +0000815 sum = 0;
816
Paul Bakkera3d195c2011-11-27 21:07:34 +0000817 for( i = 0; i < 32; i++ )
818 {
Rich Evans42914452015-02-02 12:09:25 +0000819 info->v0 += ( ( ( info->v1 << 4 ) ^ ( info->v1 >> 5 ) )
820 + info->v1 ) ^ ( sum + k[sum & 3] );
Paul Bakkera3d195c2011-11-27 21:07:34 +0000821 sum += delta;
Rich Evans42914452015-02-02 12:09:25 +0000822 info->v1 += ( ( ( info->v0 << 4 ) ^ ( info->v0 >> 5 ) )
823 + info->v0 ) ^ ( sum + k[( sum>>11 ) & 3] );
Paul Bakkera3d195c2011-11-27 21:07:34 +0000824 }
825
Paul Bakker5c2364c2012-10-01 14:41:15 +0000826 PUT_UINT32_BE( info->v0, result, 0 );
Manuel Pégourié-Gonnard217a29c2014-01-03 11:59:09 +0100827 memcpy( out, result, use_len );
Paul Bakkera3d195c2011-11-27 21:07:34 +0000828 len -= use_len;
Manuel Pégourié-Gonnard217a29c2014-01-03 11:59:09 +0100829 out += 4;
Paul Bakker997bbd12011-03-13 15:45:42 +0000830 }
831
Paul Bakkera3d195c2011-11-27 21:07:34 +0000832 return( 0 );
Paul Bakker997bbd12011-03-13 15:45:42 +0000833}
SimonB0269dad2016-02-17 23:34:30 +0000834
Ronald Crond2397942020-06-10 11:03:08 +0200835int mbedtls_test_hexcmp( uint8_t * a, uint8_t * b, uint32_t a_len, uint32_t b_len )
Azim Khan3499a9e2017-05-30 00:06:49 +0100836{
837 int ret = 0;
838 uint32_t i = 0;
839
Manuel Pégourié-Gonnardaae10fa2018-12-12 10:24:19 +0100840 if( a_len != b_len )
Mohammad Azim Khand2d01122018-07-18 17:48:37 +0100841 return( -1 );
Azim Khan3499a9e2017-05-30 00:06:49 +0100842
843 for( i = 0; i < a_len; i++ )
844 {
Manuel Pégourié-Gonnardaae10fa2018-12-12 10:24:19 +0100845 if( a[i] != b[i] )
Azim Khan3499a9e2017-05-30 00:06:49 +0100846 {
847 ret = -1;
848 break;
849 }
850 }
851 return ret;
852}
Gilles Peskinec0713732021-01-29 21:17:11 +0100853
Gilles Peskinebbc4b8d2021-06-11 14:13:53 +0200854#if defined(MBEDTLS_BIGNUM_C)
855int mbedtls_test_read_mpi( mbedtls_mpi *X, int radix, const char *s )
856{
857 /* mbedtls_mpi_read_string() currently retains leading zeros.
858 * It always allocates at least one limb for the value 0. */
859 if( s[0] == 0 )
860 {
861 mbedtls_mpi_free( X );
862 return( 0 );
863 }
864 else
865 return( mbedtls_mpi_read_string( X, radix, s ) );
866}
867#endif /* MBEDTLS_BIGNUM_C */
868
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100869#if defined(MBEDTLS_TEST_MUTEX_USAGE)
Gilles Peskinec0713732021-01-29 21:17:11 +0100870/** Mutex usage verification framework.
871 *
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100872 * The mutex usage verification code below aims to detect bad usage of
873 * Mbed TLS's mutex abstraction layer at runtime. Note that this is solely
874 * about the use of the mutex itself, not about checking whether the mutex
875 * correctly protects whatever it is supposed to protect.
876 *
877 * The normal usage of a mutex is:
878 * ```
879 * digraph mutex_states {
880 * "UNINITIALIZED"; // the initial state
881 * "IDLE";
882 * "FREED";
883 * "LOCKED";
884 * "UNINITIALIZED" -> "IDLE" [label="init"];
885 * "FREED" -> "IDLE" [label="init"];
886 * "IDLE" -> "LOCKED" [label="lock"];
887 * "LOCKED" -> "IDLE" [label="unlock"];
888 * "IDLE" -> "FREED" [label="free"];
889 * }
890 * ```
891 *
892 * All bad transitions that can be unambiguously detected are reported.
893 * An attempt to use an uninitialized mutex cannot be detected in general
894 * since the memory content may happen to denote a valid state. For the same
895 * reason, a double init cannot be detected.
896 * All-bits-zero is the state of a freed mutex, which is distinct from an
897 * initialized mutex, so attempting to use zero-initialized memory as a mutex
898 * without calling the init function is detected.
899 *
Gilles Peskine7252ec32021-01-29 22:20:32 +0100900 * The framework attempts to detect missing calls to init and free by counting
901 * calls to init and free. If there are more calls to init than free, this
902 * means that a mutex is not being freed somewhere, which is a memory leak
903 * on platforms where a mutex consumes resources other than the
904 * mbedtls_threading_mutex_t object itself. If there are more calls to free
905 * than init, this indicates a missing init, which is likely to be detected
906 * by an attempt to lock the mutex as well. A limitation of this framework is
907 * that it cannot detect scenarios where there is exactly the same number of
908 * calls to init and free but the calls don't match. A bug like this is
Gilles Peskineed9f7982021-02-15 18:21:55 +0100909 * unlikely to happen uniformly throughout the whole test suite though.
Gilles Peskine7252ec32021-01-29 22:20:32 +0100910 *
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100911 * If an error is detected, this framework will report what happened and the
912 * test case will be marked as failed. Unfortunately, the error report cannot
913 * indicate the exact location of the problematic call. To locate the error,
914 * use a debugger and set a breakpoint on mbedtls_test_mutex_usage_error().
Gilles Peskinec0713732021-01-29 21:17:11 +0100915 */
Gilles Peskine7ba73e52021-02-09 15:35:29 +0100916enum value_of_mutex_is_valid_field
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100917{
Gilles Peskine7ba73e52021-02-09 15:35:29 +0100918 /* Potential values for the is_valid field of mbedtls_threading_mutex_t.
919 * Note that MUTEX_FREED must be 0 and MUTEX_IDLE must be 1 for
920 * compatibility with threading_mutex_init_pthread() and
921 * threading_mutex_free_pthread(). MUTEX_LOCKED could be any nonzero
922 * value. */
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100923 MUTEX_FREED = 0, //!< Set by threading_mutex_free_pthread
924 MUTEX_IDLE = 1, //!< Set by threading_mutex_init_pthread and by our unlock
925 MUTEX_LOCKED = 2, //!< Set by our lock
926};
Gilles Peskinec0713732021-01-29 21:17:11 +0100927
Gilles Peskinec0713732021-01-29 21:17:11 +0100928typedef struct
929{
930 void (*init)( mbedtls_threading_mutex_t * );
931 void (*free)( mbedtls_threading_mutex_t * );
932 int (*lock)( mbedtls_threading_mutex_t * );
933 int (*unlock)( mbedtls_threading_mutex_t * );
934} mutex_functions_t;
935static mutex_functions_t mutex_functions;
936
Gilles Peskine7252ec32021-01-29 22:20:32 +0100937/** The total number of calls to mbedtls_mutex_init(), minus the total number
938 * of calls to mbedtls_mutex_free().
939 *
940 * Reset to 0 after each test case.
941 */
942static int live_mutexes;
943
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100944static void mbedtls_test_mutex_usage_error( mbedtls_threading_mutex_t *mutex,
945 const char *msg )
946{
947 (void) mutex;
948 if( test_info.mutex_usage_error == NULL )
949 test_info.mutex_usage_error = msg;
950 mbedtls_fprintf( stdout, "[mutex: %s] ", msg );
951 /* Don't mark the test as failed yet. This way, if the test fails later
952 * for a functional reason, the test framework will report the message
953 * and location for this functional reason. If the test passes,
954 * mbedtls_test_mutex_usage_check() will mark it as failed. */
955}
956
Gilles Peskinec0713732021-01-29 21:17:11 +0100957static void mbedtls_test_wrap_mutex_init( mbedtls_threading_mutex_t *mutex )
958{
959 mutex_functions.init( mutex );
Gilles Peskine7252ec32021-01-29 22:20:32 +0100960 if( mutex->is_valid )
961 ++live_mutexes;
Gilles Peskinec0713732021-01-29 21:17:11 +0100962}
963
964static void mbedtls_test_wrap_mutex_free( mbedtls_threading_mutex_t *mutex )
965{
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100966 switch( mutex->is_valid )
967 {
968 case MUTEX_FREED:
969 mbedtls_test_mutex_usage_error( mutex, "free without init or double free" );
970 break;
971 case MUTEX_IDLE:
972 /* Do nothing. The underlying free function will reset is_valid
973 * to 0. */
974 break;
975 case MUTEX_LOCKED:
976 mbedtls_test_mutex_usage_error( mutex, "free without unlock" );
977 break;
978 default:
979 mbedtls_test_mutex_usage_error( mutex, "corrupted state" );
980 break;
981 }
Gilles Peskine7252ec32021-01-29 22:20:32 +0100982 if( mutex->is_valid )
983 --live_mutexes;
Gilles Peskinec0713732021-01-29 21:17:11 +0100984 mutex_functions.free( mutex );
985}
986
987static int mbedtls_test_wrap_mutex_lock( mbedtls_threading_mutex_t *mutex )
988{
989 int ret = mutex_functions.lock( mutex );
Gilles Peskinecd2e2482021-01-29 21:18:09 +0100990 switch( mutex->is_valid )
991 {
992 case MUTEX_FREED:
993 mbedtls_test_mutex_usage_error( mutex, "lock without init" );
994 break;
995 case MUTEX_IDLE:
996 if( ret == 0 )
997 mutex->is_valid = 2;
998 break;
999 case MUTEX_LOCKED:
1000 mbedtls_test_mutex_usage_error( mutex, "double lock" );
1001 break;
1002 default:
1003 mbedtls_test_mutex_usage_error( mutex, "corrupted state" );
1004 break;
1005 }
Gilles Peskinec0713732021-01-29 21:17:11 +01001006 return( ret );
1007}
1008
1009static int mbedtls_test_wrap_mutex_unlock( mbedtls_threading_mutex_t *mutex )
1010{
Gilles Peskinecd2e2482021-01-29 21:18:09 +01001011 int ret = mutex_functions.unlock( mutex );
1012 switch( mutex->is_valid )
1013 {
1014 case MUTEX_FREED:
1015 mbedtls_test_mutex_usage_error( mutex, "unlock without init" );
1016 break;
1017 case MUTEX_IDLE:
1018 mbedtls_test_mutex_usage_error( mutex, "unlock without lock" );
1019 break;
1020 case MUTEX_LOCKED:
1021 if( ret == 0 )
1022 mutex->is_valid = MUTEX_IDLE;
1023 break;
1024 default:
1025 mbedtls_test_mutex_usage_error( mutex, "corrupted state" );
1026 break;
1027 }
1028 return( ret );
Gilles Peskinec0713732021-01-29 21:17:11 +01001029}
1030
1031static void mbedtls_test_mutex_usage_init( void )
1032{
1033 mutex_functions.init = mbedtls_mutex_init;
1034 mutex_functions.free = mbedtls_mutex_free;
1035 mutex_functions.lock = mbedtls_mutex_lock;
1036 mutex_functions.unlock = mbedtls_mutex_unlock;
1037 mbedtls_mutex_init = &mbedtls_test_wrap_mutex_init;
1038 mbedtls_mutex_free = &mbedtls_test_wrap_mutex_free;
1039 mbedtls_mutex_lock = &mbedtls_test_wrap_mutex_lock;
1040 mbedtls_mutex_unlock = &mbedtls_test_wrap_mutex_unlock;
1041}
1042
Gilles Peskinecd2e2482021-01-29 21:18:09 +01001043static void mbedtls_test_mutex_usage_check( void )
1044{
Gilles Peskine7252ec32021-01-29 22:20:32 +01001045 if( live_mutexes != 0 )
1046 {
1047 /* A positive number (more init than free) means that a mutex resource
1048 * is leaking (on platforms where a mutex consumes more than the
1049 * mbedtls_threading_mutex_t object itself). The rare case of a
1050 * negative number means a missing init somewhere. */
1051 mbedtls_fprintf( stdout, "[mutex: %d leaked] ", live_mutexes );
1052 live_mutexes = 0;
1053 if( test_info.mutex_usage_error == NULL )
1054 test_info.mutex_usage_error = "missing free";
1055 }
Gilles Peskinecd2e2482021-01-29 21:18:09 +01001056 if( test_info.mutex_usage_error != NULL &&
1057 test_info.result != TEST_RESULT_FAILED )
1058 {
1059 /* Functionally, the test passed. But there was a mutex usage error,
1060 * so mark the test as failed after all. */
1061 test_fail( "Mutex usage error", __LINE__, __FILE__ );
1062 }
1063 test_info.mutex_usage_error = NULL;
1064}
1065
Gilles Peskinec0713732021-01-29 21:17:11 +01001066#endif /* MBEDTLS_TEST_MUTEX_USAGE */