• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#line 2 "suites/helpers.function"
2/*----------------------------------------------------------------------------*/
3/* Headers */
4
5#include <stdlib.h>
6
7#if defined(MBEDTLS_PLATFORM_C)
8#include "mbedtls/platform.h"
9#else
10#include <stdio.h>
11#define mbedtls_fprintf    fprintf
12#define mbedtls_snprintf   snprintf
13#define mbedtls_calloc     calloc
14#define mbedtls_free       free
15#define mbedtls_exit       exit
16#define mbedtls_time       time
17#define mbedtls_time_t     time_t
18#define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
19#define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
20#endif
21
22#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
23#include "mbedtls/memory_buffer_alloc.h"
24#endif
25
26#if defined(MBEDTLS_CHECK_PARAMS)
27#include "mbedtls/platform_util.h"
28#include <setjmp.h>
29#endif
30
31#ifdef _MSC_VER
32#include <basetsd.h>
33typedef UINT8 uint8_t;
34typedef INT32 int32_t;
35typedef UINT32 uint32_t;
36#define strncasecmp _strnicmp
37#define strcasecmp _stricmp
38#else
39#include <stdint.h>
40#endif
41
42#include <string.h>
43
44#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
45#include <unistd.h>
46#include <strings.h>
47#endif
48
49#if defined(MBEDTLS_BIGNUM_C)
50#include "mbedtls/bignum.h"
51#endif
52
53#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
59/*
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 */
80#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
89#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 */
99
100#define TEST_CF_SECRET(ptr, size)
101#define TEST_CF_PUBLIC(ptr, size)
102
103#endif /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN */
104
105/* Type for Hex parameters */
106typedef struct data_tag
107{
108    uint8_t *   x;
109    uint32_t    len;
110} data_t;
111
112/*----------------------------------------------------------------------------*/
113/* Status and error constants */
114
115#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 */
118
119#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 */
128
129typedef 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
138
139/*----------------------------------------------------------------------------*/
140/* Macros */
141
142/**
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
150 *          callback, MBEDTLS_PARAM_FAILED(), will be assumed to be a test
151 *          failure.
152 *
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 */
158#define TEST_ASSERT( TEST )                                 \
159    do {                                                    \
160       if( ! (TEST) )                                       \
161       {                                                    \
162          test_fail( #TEST, __LINE__, __FILE__ );           \
163          goto exit;                                        \
164       }                                                    \
165    } while( 0 )
166
167/** 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 )
227/** 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
248/**
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
263#if defined(MBEDTLS_CHECK_PARAMS) && !defined(MBEDTLS_PARAM_FAILED_ALT)
264/**
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
273 *          callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
274 *          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
278 *          MBEDTLS_PARAM_FAILED() to indicate the error.
279 *
280 * \param   PARAM_ERROR_VALUE   The expected error code.
281 *
282 * \param   TEST                The test expression to be tested.
283 */
284#define TEST_INVALID_PARAM_RET( PARAM_ERR_VALUE, TEST )                     \
285    do {                                                                    \
286        test_info.paramfail_test_state = PARAMFAIL_TESTSTATE_PENDING;       \
287        if( (TEST) != (PARAM_ERR_VALUE) ||                                  \
288            test_info.paramfail_test_state != PARAMFAIL_TESTSTATE_CALLED )  \
289        {                                                                   \
290            test_fail( #TEST, __LINE__, __FILE__ );                         \
291            goto exit;                                                      \
292        }                                                                   \
293   } while( 0 )
294
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
302 *          MBEDTLS_PARAM_FAILED().
303 *
304 *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
305 *          callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
306 *          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
311 *          MBEDTLS_PARAM_FAILED() to indicate the error.
312 *
313 * \param   TEST                The test expression to be tested.
314 */
315#define TEST_INVALID_PARAM( TEST )                                          \
316    do {                                                                    \
317        memcpy(jmp_tmp, param_fail_jmp, sizeof(jmp_buf));                   \
318        if( setjmp( param_fail_jmp ) == 0 )                                 \
319        {                                                                   \
320            TEST;                                                           \
321            test_fail( #TEST, __LINE__, __FILE__ );                         \
322            goto exit;                                                      \
323        }                                                                   \
324        memcpy(param_fail_jmp, jmp_tmp, sizeof(jmp_buf));                   \
325    } while( 0 )
326#endif /* MBEDTLS_CHECK_PARAMS && !MBEDTLS_PARAM_FAILED_ALT */
327
328/**
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 *
341 *          This macro is intended to test that functions returning void
342 *          accept all of the parameter values they're supposed to accept - eg
343 *          that they don't call MBEDTLS_PARAM_FAILED() when a parameter
344 *          that's allowed to be NULL happens to be NULL.
345 *
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 *
351 *          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,
354 *          the test is more about whether the function segfaults than about
355 *          whether it invokes MBEDTLS_PARAM_FAILED().
356 *
357 * \param   TEST                The test expression to be tested.
358 */
359#define TEST_VALID_PARAM( TEST )                                    \
360    TEST_ASSERT( ( TEST, 1 ) );
361
362#define TEST_HELPER_ASSERT(a) if( !( a ) )                                      \
363{                                                                   \
364    mbedtls_fprintf( stderr, "Assertion Failed at %s:%d - %s\n",   \
365                             __FILE__, __LINE__, #a );              \
366    mbedtls_exit( 1 );                                             \
367}
368
369#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 )                                \
384    ( 0 && sizeof( struct { unsigned int STATIC_ASSERT : 1 - 2 * ! ( const_expr ); } ) )
385/* 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
403/*
404 * 32-bit integer manipulation macros (big endian)
405 */
406#ifndef GET_UINT32_BE
407#define GET_UINT32_BE(n,b,i)                            \
408{                                                       \
409    (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]       );            \
413}
414#endif
415
416#ifndef PUT_UINT32_BE
417#define PUT_UINT32_BE(n,b,i)                            \
418{                                                       \
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
426
427/*----------------------------------------------------------------------------*/
428/* Global variables */
429
430typedef enum
431{
432    TEST_RESULT_SUCCESS = 0,
433    TEST_RESULT_FAILED,
434    TEST_RESULT_SKIPPED
435} test_result_t;
436
437static struct
438{
439    paramfail_test_state_t paramfail_test_state;
440    test_result_t result;
441    const char *test;
442    const char *filename;
443    int line_no;
444#if defined(MBEDTLS_TEST_MUTEX_USAGE)
445    const char *mutex_usage_error;
446#endif
447}
448test_info;
449
450#if defined(MBEDTLS_PLATFORM_C)
451mbedtls_platform_context platform_ctx;
452#endif
453
454#if defined(MBEDTLS_CHECK_PARAMS)
455jmp_buf param_fail_jmp;
456jmp_buf jmp_tmp;
457#endif
458
459/*----------------------------------------------------------------------------*/
460/* 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) ) )
470#define ENTROPY_HAVE_STRONG
471#endif
472
473
474/*----------------------------------------------------------------------------*/
475/* Helper Functions */
476
477void test_fail( const char *test, int line_no, const char* filename )
478{
479    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    }
485    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;
494    test_info.test = test;
495    test_info.line_no = line_no;
496    test_info.filename = filename;
497}
498
499static int platform_setup()
500{
501    int ret = 0;
502#if defined(MBEDTLS_PLATFORM_C)
503    ret = mbedtls_platform_setup( &platform_ctx );
504#endif /* MBEDTLS_PLATFORM_C */
505    return( ret );
506}
507
508static void platform_teardown()
509{
510#if defined(MBEDTLS_PLATFORM_C)
511    mbedtls_platform_teardown( &platform_ctx );
512#endif /* MBEDTLS_PLATFORM_C */
513}
514
515#if defined(MBEDTLS_CHECK_PARAMS)
516void mbedtls_param_failed( const char *failure_condition,
517                           const char *file,
518                           int line )
519{
520    /* If we are testing the callback function...  */
521    if( test_info.paramfail_test_state == PARAMFAIL_TESTSTATE_PENDING )
522    {
523        test_info.paramfail_test_state = PARAMFAIL_TESTSTATE_CALLED;
524    }
525    else
526    {
527        /* ...else we treat this as an error */
528
529        /* 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 );
532        test_info.result = TEST_RESULT_SUCCESS;
533
534        longjmp( param_fail_jmp, 1 );
535    }
536}
537#endif
538
539#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
540static int redirect_output( FILE* out_stream, const char* path )
541{
542    int out_fd, dup_fd;
543    FILE* path_stream;
544
545    out_fd = fileno( out_stream );
546    dup_fd = dup( out_fd );
547
548    if( dup_fd == -1 )
549    {
550        return( -1 );
551    }
552
553    path_stream = fopen( path, "w" );
554    if( path_stream == NULL )
555    {
556        close( dup_fd );
557        return( -1 );
558    }
559
560    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 );
570}
571
572static int restore_output( FILE* out_stream, int dup_fd )
573{
574    int out_fd = fileno( out_stream );
575
576    fflush( out_stream );
577    if( dup2( dup_fd, out_fd ) == -1 )
578    {
579        close( out_fd );
580        close( dup_fd );
581        return( -1 );
582    }
583
584    close( dup_fd );
585    return( 0 );
586}
587#endif /* __unix__ || __APPLE__ __MACH__ */
588
589int mbedtls_test_unhexify( unsigned char *obuf, const char *ibuf )
590{
591    unsigned char c, c2;
592    int len = strlen( ibuf ) / 2;
593    TEST_HELPER_ASSERT( strlen( ibuf ) % 2 == 0 ); /* must be even number of bytes */
594
595    while( *ibuf != 0 )
596    {
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
605            TEST_HELPER_ASSERT( 0 );
606
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
615            TEST_HELPER_ASSERT( 0 );
616
617        *obuf++ = ( c << 4 ) | c2;
618    }
619
620    return len;
621}
622
623void mbedtls_test_hexify( unsigned char *obuf, const unsigned char *ibuf, int len )
624{
625    unsigned char l, h;
626
627    while( len != 0 )
628    {
629        h = *ibuf / 16;
630        l = *ibuf % 16;
631
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}
646
647/**
648 * 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;
657    size_t actual_len = ( len != 0 ) ? len : 1;
658
659    p = mbedtls_calloc( 1, actual_len );
660    TEST_HELPER_ASSERT( p != NULL );
661
662    memset( p, 0x00, actual_len );
663
664    return( p );
665}
666
667/**
668 * 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 *
673 * If the size if zero, a pointer to a zeroized 1-byte buffer is returned.
674 *
675 * For convenience, dies if allocation fails.
676 */
677unsigned char *unhexify_alloc( const char *ibuf, size_t *olen )
678{
679    unsigned char *obuf;
680
681    *olen = strlen( ibuf ) / 2;
682
683    if( *olen == 0 )
684        return( zero_alloc( *olen ) );
685
686    obuf = mbedtls_calloc( 1, *olen );
687    TEST_HELPER_ASSERT( obuf != NULL );
688
689    (void) mbedtls_test_unhexify( obuf, ibuf );
690
691    return( obuf );
692}
693
694/**
695 * This function just returns data from rand().
696 * 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.
700 *
701 * rng_state shall be NULL.
702 */
703static int rnd_std_rand( void *rng_state, unsigned char *output, size_t len )
704{
705#if !defined(__OpenBSD__) && !defined(__NetBSD__)
706    size_t i;
707
708    if( rng_state != NULL )
709        rng_state  = NULL;
710
711    for( i = 0; i < len; ++i )
712        output[i] = rand();
713#else
714    if( rng_state != NULL )
715        rng_state = NULL;
716
717    arc4random_buf( output, len );
718#endif /* !OpenBSD && !NetBSD */
719
720    return( 0 );
721}
722
723/**
724 * This function only returns zeros
725 *
726 * rng_state shall be NULL.
727 */
728int rnd_zero_rand( void *rng_state, unsigned char *output, size_t len )
729{
730    if( rng_state != NULL )
731        rng_state  = NULL;
732
733    memset( output, 0, len );
734
735    return( 0 );
736}
737
738typedef struct
739{
740    unsigned char *buf;
741    size_t length;
742} rnd_buf_info;
743
744/**
745 * This function returns random based on a buffer it receives.
746 *
747 * rng_state shall be a pointer to a rnd_buf_info structure.
748 *
749 * 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)
752 *
753 * After the buffer is empty it will return rand();
754 */
755int rnd_buffer_rand( void *rng_state, unsigned char *output, size_t len )
756{
757    rnd_buf_info *info = (rnd_buf_info *) rng_state;
758    size_t use_len;
759
760    if( rng_state == NULL )
761        return( rnd_std_rand( NULL, output, len ) );
762
763    use_len = len;
764    if( len > info->length )
765        use_len = info->length;
766
767    if( use_len )
768    {
769        memcpy( output, info->buf, use_len );
770        info->buf += use_len;
771        info->length -= use_len;
772    }
773
774    if( len - use_len > 0 )
775        return( rnd_std_rand( NULL, output + use_len, len - use_len ) );
776
777    return( 0 );
778}
779
780/**
781 * Info structure for the pseudo random function
782 *
783 * Key should be set at the start to a test-unique value.
784 * Do not forget endianness!
785 * State( v0, v1 ) should be set to zero.
786 */
787typedef struct
788{
789    uint32_t key[16];
790    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 */
801int rnd_pseudo_rand( void *rng_state, unsigned char *output, size_t len )
802{
803    rnd_pseudo_info *info = (rnd_pseudo_info *) rng_state;
804    uint32_t i, *k, sum, delta=0x9E3779B9;
805    unsigned char result[4], *out = output;
806
807    if( rng_state == NULL )
808        return( rnd_std_rand( NULL, output, len ) );
809
810    k = info->key;
811
812    while( len > 0 )
813    {
814        size_t use_len = ( len > 4 ) ? 4 : len;
815        sum = 0;
816
817        for( i = 0; i < 32; i++ )
818        {
819            info->v0 += ( ( ( info->v1 << 4 ) ^ ( info->v1 >> 5 ) )
820                            + info->v1 ) ^ ( sum + k[sum & 3] );
821            sum += delta;
822            info->v1 += ( ( ( info->v0 << 4 ) ^ ( info->v0 >> 5 ) )
823                            + info->v0 ) ^ ( sum + k[( sum>>11 ) & 3] );
824        }
825
826        PUT_UINT32_BE( info->v0, result, 0 );
827        memcpy( out, result, use_len );
828        len -= use_len;
829        out += 4;
830    }
831
832    return( 0 );
833}
834
835int mbedtls_test_hexcmp( uint8_t * a, uint8_t * b, uint32_t a_len, uint32_t b_len )
836{
837    int ret = 0;
838    uint32_t i = 0;
839
840    if( a_len != b_len )
841        return( -1 );
842
843    for( i = 0; i < a_len; i++ )
844    {
845        if( a[i] != b[i] )
846        {
847            ret = -1;
848            break;
849        }
850    }
851    return ret;
852}
853
854#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
869#if defined(MBEDTLS_TEST_MUTEX_USAGE)
870/** Mutex usage verification framework.
871 *
872 * 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 *
900 * 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
909 * unlikely to happen uniformly throughout the whole test suite though.
910 *
911 * 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().
915 */
916enum value_of_mutex_is_valid_field
917{
918    /* 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. */
923    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};
927
928typedef 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
937/** 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
944static 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
957static void mbedtls_test_wrap_mutex_init( mbedtls_threading_mutex_t *mutex )
958{
959    mutex_functions.init( mutex );
960    if( mutex->is_valid )
961        ++live_mutexes;
962}
963
964static void mbedtls_test_wrap_mutex_free( mbedtls_threading_mutex_t *mutex )
965{
966    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    }
982    if( mutex->is_valid )
983        --live_mutexes;
984    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 );
990    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    }
1006    return( ret );
1007}
1008
1009static int mbedtls_test_wrap_mutex_unlock( mbedtls_threading_mutex_t *mutex )
1010{
1011    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 );
1029}
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
1043static void mbedtls_test_mutex_usage_check( void )
1044{
1045    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    }
1056    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
1066#endif /* MBEDTLS_TEST_MUTEX_USAGE */
1067