• 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_THREADING_C) && defined(MBEDTLS_THREADING_PTHREAD) && \
50    defined(MBEDTLS_TEST_HOOKS)
51#include "mbedtls/threading.h"
52#define MBEDTLS_TEST_MUTEX_USAGE
53#endif
54
55/*
56 * Define the two macros
57 *
58 *  #define TEST_CF_SECRET(ptr, size)
59 *  #define TEST_CF_PUBLIC(ptr, size)
60 *
61 * that can be used in tests to mark a memory area as secret (no branch or
62 * memory access should depend on it) or public (default, only needs to be
63 * marked explicitly when it was derived from secret data).
64 *
65 * Arguments:
66 * - ptr: a pointer to the memory area to be marked
67 * - size: the size in bytes of the memory area
68 *
69 * Implementation:
70 * The basic idea is that of ctgrind <https://github.com/agl/ctgrind>: we can
71 * re-use tools that were designed for checking use of uninitialized memory.
72 * This file contains two implementations: one based on MemorySanitizer, the
73 * other on valgrind's memcheck. If none of them is enabled, dummy macros that
74 * do nothing are defined for convenience.
75 */
76#if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN)
77#include <sanitizer/msan_interface.h>
78
79/* Use macros to avoid messing up with origin tracking */
80#define TEST_CF_SECRET  __msan_allocated_memory
81// void __msan_allocated_memory(const volatile void* data, size_t size);
82#define TEST_CF_PUBLIC  __msan_unpoison
83// void __msan_unpoison(const volatile void *a, size_t size);
84
85#elif defined(MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND)
86#include <valgrind/memcheck.h>
87
88#define TEST_CF_SECRET  VALGRIND_MAKE_MEM_UNDEFINED
89// VALGRIND_MAKE_MEM_UNDEFINED(_qzz_addr, _qzz_len)
90#define TEST_CF_PUBLIC  VALGRIND_MAKE_MEM_DEFINED
91// VALGRIND_MAKE_MEM_DEFINED(_qzz_addr, _qzz_len)
92
93#else /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN ||
94         MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND */
95
96#define TEST_CF_SECRET(ptr, size)
97#define TEST_CF_PUBLIC(ptr, size)
98
99#endif /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN */
100
101/* Type for Hex parameters */
102typedef struct data_tag
103{
104    uint8_t *   x;
105    uint32_t    len;
106} data_t;
107
108/*----------------------------------------------------------------------------*/
109/* Status and error constants */
110
111#define DEPENDENCY_SUPPORTED            0   /* Dependency supported by build */
112#define KEY_VALUE_MAPPING_FOUND         0   /* Integer expression found */
113#define DISPATCH_TEST_SUCCESS           0   /* Test dispatch successful */
114
115#define KEY_VALUE_MAPPING_NOT_FOUND     -1  /* Integer expression not found */
116#define DEPENDENCY_NOT_SUPPORTED        -2  /* Dependency not supported */
117#define DISPATCH_TEST_FN_NOT_FOUND      -3  /* Test function not found */
118#define DISPATCH_INVALID_TEST_DATA      -4  /* Invalid test parameter type.
119                                               Only int, string, binary data
120                                               and integer expressions are
121                                               allowed */
122#define DISPATCH_UNSUPPORTED_SUITE      -5  /* Test suite not supported by the
123                                               build */
124
125typedef enum
126{
127    PARAMFAIL_TESTSTATE_IDLE = 0,           /* No parameter failure call test */
128    PARAMFAIL_TESTSTATE_PENDING,            /* Test call to the parameter failure
129                                             * is pending */
130    PARAMFAIL_TESTSTATE_CALLED              /* The test call to the parameter
131                                             * failure function has been made */
132} paramfail_test_state_t;
133
134
135/*----------------------------------------------------------------------------*/
136/* Macros */
137
138/**
139 * \brief   This macro tests the expression passed to it as a test step or
140 *          individual test in a test case.
141 *
142 *          It allows a library function to return a value and return an error
143 *          code that can be tested.
144 *
145 *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
146 *          callback, MBEDTLS_PARAM_FAILED(), will be assumed to be a test
147 *          failure.
148 *
149 *          This macro is not suitable for negative parameter validation tests,
150 *          as it assumes the test step will not create an error.
151 *
152 * \param   TEST    The test expression to be tested.
153 */
154#define TEST_ASSERT( TEST )                                 \
155    do {                                                    \
156       if( ! (TEST) )                                       \
157       {                                                    \
158          test_fail( #TEST, __LINE__, __FILE__ );           \
159          goto exit;                                        \
160       }                                                    \
161    } while( 0 )
162
163/** Compare two buffers and fail the test case if they differ.
164 *
165 * This macro expands to an instruction, not an expression.
166 * It may jump to the \c exit label.
167 *
168 * \param p1        Pointer to the start of the first buffer.
169 * \param size1     Size of the first buffer in bytes.
170 *                  This expression may be evaluated multiple times.
171 * \param p2        Pointer to the start of the second buffer.
172 * \param size2     Size of the second buffer in bytes.
173 *                  This expression may be evaluated multiple times.
174 */
175#define ASSERT_COMPARE( p1, size1, p2, size2 )                          \
176    do                                                                  \
177    {                                                                   \
178        TEST_ASSERT( ( size1 ) == ( size2 ) );                          \
179        if( ( size1 ) != 0 )                                            \
180            TEST_ASSERT( memcmp( ( p1 ), ( p2 ), ( size1 ) ) == 0 );    \
181    }                                                                   \
182    while( 0 )
183
184/**
185 * \brief   This macro tests the expression passed to it and skips the
186 *          running test if it doesn't evaluate to 'true'.
187 *
188 * \param   TEST    The test expression to be tested.
189 */
190#define TEST_ASSUME( TEST )                         \
191    do {                                            \
192        if( ! (TEST) )                              \
193        {                                           \
194            test_skip( #TEST, __LINE__, __FILE__ ); \
195            goto exit;                              \
196        }                                           \
197    } while( 0 )
198
199#if defined(MBEDTLS_CHECK_PARAMS) && !defined(MBEDTLS_PARAM_FAILED_ALT)
200/**
201 * \brief   This macro tests the statement passed to it as a test step or
202 *          individual test in a test case. The macro assumes the test will fail
203 *          and will generate an error.
204 *
205 *          It allows a library function to return a value and tests the return
206 *          code on return to confirm the given error code was returned.
207 *
208 *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
209 *          callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
210 *          expected failure, and the test will pass.
211 *
212 *          This macro is intended for negative parameter validation tests,
213 *          where the failing function may return an error value or call
214 *          MBEDTLS_PARAM_FAILED() to indicate the error.
215 *
216 * \param   PARAM_ERROR_VALUE   The expected error code.
217 *
218 * \param   TEST                The test expression to be tested.
219 */
220#define TEST_INVALID_PARAM_RET( PARAM_ERR_VALUE, TEST )                     \
221    do {                                                                    \
222        test_info.paramfail_test_state = PARAMFAIL_TESTSTATE_PENDING;       \
223        if( (TEST) != (PARAM_ERR_VALUE) ||                                  \
224            test_info.paramfail_test_state != PARAMFAIL_TESTSTATE_CALLED )  \
225        {                                                                   \
226            test_fail( #TEST, __LINE__, __FILE__ );                         \
227            goto exit;                                                      \
228        }                                                                   \
229   } while( 0 )
230
231/**
232 * \brief   This macro tests the statement passed to it as a test step or
233 *          individual test in a test case. The macro assumes the test will fail
234 *          and will generate an error.
235 *
236 *          It assumes the library function under test cannot return a value and
237 *          assumes errors can only be indicated byt calls to
238 *          MBEDTLS_PARAM_FAILED().
239 *
240 *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
241 *          callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
242 *          expected failure. If MBEDTLS_CHECK_PARAMS is not enabled, no test
243 *          can be made.
244 *
245 *          This macro is intended for negative parameter validation tests,
246 *          where the failing function can only return an error by calling
247 *          MBEDTLS_PARAM_FAILED() to indicate the error.
248 *
249 * \param   TEST                The test expression to be tested.
250 */
251#define TEST_INVALID_PARAM( TEST )                                          \
252    do {                                                                    \
253        memcpy(jmp_tmp, param_fail_jmp, sizeof(jmp_buf));                   \
254        if( setjmp( param_fail_jmp ) == 0 )                                 \
255        {                                                                   \
256            TEST;                                                           \
257            test_fail( #TEST, __LINE__, __FILE__ );                         \
258            goto exit;                                                      \
259        }                                                                   \
260        memcpy(param_fail_jmp, jmp_tmp, sizeof(jmp_buf));                   \
261    } while( 0 )
262#endif /* MBEDTLS_CHECK_PARAMS && !MBEDTLS_PARAM_FAILED_ALT */
263
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 not fail.
267 *
268 *          It assumes the library function under test cannot return a value and
269 *          assumes errors can only be indicated by calls to
270 *          MBEDTLS_PARAM_FAILED().
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. If MBEDTLS_CHECK_PARAMS is not enabled, no test
275 *          can be made.
276 *
277 *          This macro is intended to test that functions returning void
278 *          accept all of the parameter values they're supposed to accept - eg
279 *          that they don't call MBEDTLS_PARAM_FAILED() when a parameter
280 *          that's allowed to be NULL happens to be NULL.
281 *
282 *          Note: for functions that return something other that void,
283 *          checking that they accept all the parameters they're supposed to
284 *          accept is best done by using TEST_ASSERT() and checking the return
285 *          value as well.
286 *
287 *          Note: this macro is available even when #MBEDTLS_CHECK_PARAMS is
288 *          disabled, as it makes sense to check that the functions accept all
289 *          legal values even if this option is disabled - only in that case,
290 *          the test is more about whether the function segfaults than about
291 *          whether it invokes MBEDTLS_PARAM_FAILED().
292 *
293 * \param   TEST                The test expression to be tested.
294 */
295#define TEST_VALID_PARAM( TEST )                                    \
296    TEST_ASSERT( ( TEST, 1 ) );
297
298#define TEST_HELPER_ASSERT(a) if( !( a ) )                                      \
299{                                                                   \
300    mbedtls_fprintf( stderr, "Assertion Failed at %s:%d - %s\n",   \
301                             __FILE__, __LINE__, #a );              \
302    mbedtls_exit( 1 );                                             \
303}
304
305#if defined(__GNUC__)
306/* Test if arg and &(arg)[0] have the same type. This is true if arg is
307 * an array but not if it's a pointer. */
308#define IS_ARRAY_NOT_POINTER( arg )                                     \
309    ( ! __builtin_types_compatible_p( __typeof__( arg ),                \
310                                      __typeof__( &( arg )[0] ) ) )
311#else
312/* On platforms where we don't know how to implement this check,
313 * omit it. Oh well, a non-portable check is better than nothing. */
314#define IS_ARRAY_NOT_POINTER( arg ) 1
315#endif
316
317/* A compile-time constant with the value 0. If `const_expr` is not a
318 * compile-time constant with a nonzero value, cause a compile-time error. */
319#define STATIC_ASSERT_EXPR( const_expr )                                \
320    ( 0 && sizeof( struct { unsigned int STATIC_ASSERT : 1 - 2 * ! ( const_expr ); } ) )
321/* Return the scalar value `value` (possibly promoted). This is a compile-time
322 * constant if `value` is. `condition` must be a compile-time constant.
323 * If `condition` is false, arrange to cause a compile-time error. */
324#define STATIC_ASSERT_THEN_RETURN( condition, value )   \
325    ( STATIC_ASSERT_EXPR( condition ) ? 0 : ( value ) )
326
327#define ARRAY_LENGTH_UNSAFE( array )            \
328    ( sizeof( array ) / sizeof( *( array ) ) )
329/** Return the number of elements of a static or stack array.
330 *
331 * \param array         A value of array (not pointer) type.
332 *
333 * \return The number of elements of the array.
334 */
335#define ARRAY_LENGTH( array )                                           \
336    ( STATIC_ASSERT_THEN_RETURN( IS_ARRAY_NOT_POINTER( array ),         \
337                                 ARRAY_LENGTH_UNSAFE( array ) ) )
338
339/*
340 * 32-bit integer manipulation macros (big endian)
341 */
342#ifndef GET_UINT32_BE
343#define GET_UINT32_BE(n,b,i)                            \
344{                                                       \
345    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \
346        | ( (uint32_t) (b)[(i) + 1] << 16 )             \
347        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \
348        | ( (uint32_t) (b)[(i) + 3]       );            \
349}
350#endif
351
352#ifndef PUT_UINT32_BE
353#define PUT_UINT32_BE(n,b,i)                            \
354{                                                       \
355    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \
356    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \
357    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \
358    (b)[(i) + 3] = (unsigned char) ( (n)       );       \
359}
360#endif
361
362
363/*----------------------------------------------------------------------------*/
364/* Global variables */
365
366typedef enum
367{
368    TEST_RESULT_SUCCESS = 0,
369    TEST_RESULT_FAILED,
370    TEST_RESULT_SKIPPED
371} test_result_t;
372
373static struct
374{
375    paramfail_test_state_t paramfail_test_state;
376    test_result_t result;
377    const char *test;
378    const char *filename;
379    int line_no;
380#if defined(MBEDTLS_TEST_MUTEX_USAGE)
381    const char *mutex_usage_error;
382#endif
383}
384test_info;
385
386#if defined(MBEDTLS_PLATFORM_C)
387mbedtls_platform_context platform_ctx;
388#endif
389
390#if defined(MBEDTLS_CHECK_PARAMS)
391jmp_buf param_fail_jmp;
392jmp_buf jmp_tmp;
393#endif
394
395/*----------------------------------------------------------------------------*/
396/* Helper flags for complex dependencies */
397
398/* Indicates whether we expect mbedtls_entropy_init
399 * to initialize some strong entropy source. */
400#if defined(MBEDTLS_TEST_NULL_ENTROPY) ||             \
401    ( !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) && \
402      ( !defined(MBEDTLS_NO_PLATFORM_ENTROPY)  ||     \
403         defined(MBEDTLS_HAVEGE_C)             ||     \
404         defined(MBEDTLS_ENTROPY_HARDWARE_ALT) ||     \
405         defined(ENTROPY_NV_SEED) ) )
406#define ENTROPY_HAVE_STRONG
407#endif
408
409
410/*----------------------------------------------------------------------------*/
411/* Helper Functions */
412
413void test_fail( const char *test, int line_no, const char* filename )
414{
415    if( test_info.result == TEST_RESULT_FAILED )
416    {
417        /* We've already recorded the test as having failed. Don't
418         * overwrite any previous information about the failure. */
419        return;
420    }
421    test_info.result = TEST_RESULT_FAILED;
422    test_info.test = test;
423    test_info.line_no = line_no;
424    test_info.filename = filename;
425}
426
427void test_skip( const char *test, int line_no, const char* filename )
428{
429    test_info.result = TEST_RESULT_SKIPPED;
430    test_info.test = test;
431    test_info.line_no = line_no;
432    test_info.filename = filename;
433}
434
435static int platform_setup()
436{
437    int ret = 0;
438#if defined(MBEDTLS_PLATFORM_C)
439    ret = mbedtls_platform_setup( &platform_ctx );
440#endif /* MBEDTLS_PLATFORM_C */
441    return( ret );
442}
443
444static void platform_teardown()
445{
446#if defined(MBEDTLS_PLATFORM_C)
447    mbedtls_platform_teardown( &platform_ctx );
448#endif /* MBEDTLS_PLATFORM_C */
449}
450
451#if defined(MBEDTLS_CHECK_PARAMS)
452void mbedtls_param_failed( const char *failure_condition,
453                           const char *file,
454                           int line )
455{
456    /* If we are testing the callback function...  */
457    if( test_info.paramfail_test_state == PARAMFAIL_TESTSTATE_PENDING )
458    {
459        test_info.paramfail_test_state = PARAMFAIL_TESTSTATE_CALLED;
460    }
461    else
462    {
463        /* ...else we treat this as an error */
464
465        /* Record the location of the failure, but not as a failure yet, in case
466         * it was part of the test */
467        test_fail( failure_condition, line, file );
468        test_info.result = TEST_RESULT_SUCCESS;
469
470        longjmp( param_fail_jmp, 1 );
471    }
472}
473#endif
474
475#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
476static int redirect_output( FILE* out_stream, const char* path )
477{
478    int out_fd, dup_fd;
479    FILE* path_stream;
480
481    out_fd = fileno( out_stream );
482    dup_fd = dup( out_fd );
483
484    if( dup_fd == -1 )
485    {
486        return( -1 );
487    }
488
489    path_stream = fopen( path, "w" );
490    if( path_stream == NULL )
491    {
492        close( dup_fd );
493        return( -1 );
494    }
495
496    fflush( out_stream );
497    if( dup2( fileno( path_stream ), out_fd ) == -1 )
498    {
499        close( dup_fd );
500        fclose( path_stream );
501        return( -1 );
502    }
503
504    fclose( path_stream );
505    return( dup_fd );
506}
507
508static int restore_output( FILE* out_stream, int dup_fd )
509{
510    int out_fd = fileno( out_stream );
511
512    fflush( out_stream );
513    if( dup2( dup_fd, out_fd ) == -1 )
514    {
515        close( out_fd );
516        close( dup_fd );
517        return( -1 );
518    }
519
520    close( dup_fd );
521    return( 0 );
522}
523#endif /* __unix__ || __APPLE__ __MACH__ */
524
525int mbedtls_test_unhexify( unsigned char *obuf, const char *ibuf )
526{
527    unsigned char c, c2;
528    int len = strlen( ibuf ) / 2;
529    TEST_HELPER_ASSERT( strlen( ibuf ) % 2 == 0 ); /* must be even number of bytes */
530
531    while( *ibuf != 0 )
532    {
533        c = *ibuf++;
534        if( c >= '0' && c <= '9' )
535            c -= '0';
536        else if( c >= 'a' && c <= 'f' )
537            c -= 'a' - 10;
538        else if( c >= 'A' && c <= 'F' )
539            c -= 'A' - 10;
540        else
541            TEST_HELPER_ASSERT( 0 );
542
543        c2 = *ibuf++;
544        if( c2 >= '0' && c2 <= '9' )
545            c2 -= '0';
546        else if( c2 >= 'a' && c2 <= 'f' )
547            c2 -= 'a' - 10;
548        else if( c2 >= 'A' && c2 <= 'F' )
549            c2 -= 'A' - 10;
550        else
551            TEST_HELPER_ASSERT( 0 );
552
553        *obuf++ = ( c << 4 ) | c2;
554    }
555
556    return len;
557}
558
559void mbedtls_test_hexify( unsigned char *obuf, const unsigned char *ibuf, int len )
560{
561    unsigned char l, h;
562
563    while( len != 0 )
564    {
565        h = *ibuf / 16;
566        l = *ibuf % 16;
567
568        if( h < 10 )
569            *obuf++ = '0' + h;
570        else
571            *obuf++ = 'a' + h - 10;
572
573        if( l < 10 )
574            *obuf++ = '0' + l;
575        else
576            *obuf++ = 'a' + l - 10;
577
578        ++ibuf;
579        len--;
580    }
581}
582
583/**
584 * Allocate and zeroize a buffer.
585 *
586 * If the size if zero, a pointer to a zeroized 1-byte buffer is returned.
587 *
588 * For convenience, dies if allocation fails.
589 */
590static unsigned char *zero_alloc( size_t len )
591{
592    void *p;
593    size_t actual_len = ( len != 0 ) ? len : 1;
594
595    p = mbedtls_calloc( 1, actual_len );
596    TEST_HELPER_ASSERT( p != NULL );
597
598    memset( p, 0x00, actual_len );
599
600    return( p );
601}
602
603/**
604 * Allocate and fill a buffer from hex data.
605 *
606 * The buffer is sized exactly as needed. This allows to detect buffer
607 * overruns (including overreads) when running the test suite under valgrind.
608 *
609 * If the size if zero, a pointer to a zeroized 1-byte buffer is returned.
610 *
611 * For convenience, dies if allocation fails.
612 */
613unsigned char *unhexify_alloc( const char *ibuf, size_t *olen )
614{
615    unsigned char *obuf;
616
617    *olen = strlen( ibuf ) / 2;
618
619    if( *olen == 0 )
620        return( zero_alloc( *olen ) );
621
622    obuf = mbedtls_calloc( 1, *olen );
623    TEST_HELPER_ASSERT( obuf != NULL );
624
625    (void) mbedtls_test_unhexify( obuf, ibuf );
626
627    return( obuf );
628}
629
630/**
631 * This function just returns data from rand().
632 * Although predictable and often similar on multiple
633 * runs, this does not result in identical random on
634 * each run. So do not use this if the results of a
635 * test depend on the random data that is generated.
636 *
637 * rng_state shall be NULL.
638 */
639static int rnd_std_rand( void *rng_state, unsigned char *output, size_t len )
640{
641#if !defined(__OpenBSD__) && !defined(__NetBSD__)
642    size_t i;
643
644    if( rng_state != NULL )
645        rng_state  = NULL;
646
647    for( i = 0; i < len; ++i )
648        output[i] = rand();
649#else
650    if( rng_state != NULL )
651        rng_state = NULL;
652
653    arc4random_buf( output, len );
654#endif /* !OpenBSD && !NetBSD */
655
656    return( 0 );
657}
658
659/**
660 * This function only returns zeros
661 *
662 * rng_state shall be NULL.
663 */
664int rnd_zero_rand( void *rng_state, unsigned char *output, size_t len )
665{
666    if( rng_state != NULL )
667        rng_state  = NULL;
668
669    memset( output, 0, len );
670
671    return( 0 );
672}
673
674typedef struct
675{
676    unsigned char *buf;
677    size_t length;
678} rnd_buf_info;
679
680/**
681 * This function returns random based on a buffer it receives.
682 *
683 * rng_state shall be a pointer to a rnd_buf_info structure.
684 *
685 * The number of bytes released from the buffer on each call to
686 * the random function is specified by per_call. (Can be between
687 * 1 and 4)
688 *
689 * After the buffer is empty it will return rand();
690 */
691int rnd_buffer_rand( void *rng_state, unsigned char *output, size_t len )
692{
693    rnd_buf_info *info = (rnd_buf_info *) rng_state;
694    size_t use_len;
695
696    if( rng_state == NULL )
697        return( rnd_std_rand( NULL, output, len ) );
698
699    use_len = len;
700    if( len > info->length )
701        use_len = info->length;
702
703    if( use_len )
704    {
705        memcpy( output, info->buf, use_len );
706        info->buf += use_len;
707        info->length -= use_len;
708    }
709
710    if( len - use_len > 0 )
711        return( rnd_std_rand( NULL, output + use_len, len - use_len ) );
712
713    return( 0 );
714}
715
716/**
717 * Info structure for the pseudo random function
718 *
719 * Key should be set at the start to a test-unique value.
720 * Do not forget endianness!
721 * State( v0, v1 ) should be set to zero.
722 */
723typedef struct
724{
725    uint32_t key[16];
726    uint32_t v0, v1;
727} rnd_pseudo_info;
728
729/**
730 * This function returns random based on a pseudo random function.
731 * This means the results should be identical on all systems.
732 * Pseudo random is based on the XTEA encryption algorithm to
733 * generate pseudorandom.
734 *
735 * rng_state shall be a pointer to a rnd_pseudo_info structure.
736 */
737int rnd_pseudo_rand( void *rng_state, unsigned char *output, size_t len )
738{
739    rnd_pseudo_info *info = (rnd_pseudo_info *) rng_state;
740    uint32_t i, *k, sum, delta=0x9E3779B9;
741    unsigned char result[4], *out = output;
742
743    if( rng_state == NULL )
744        return( rnd_std_rand( NULL, output, len ) );
745
746    k = info->key;
747
748    while( len > 0 )
749    {
750        size_t use_len = ( len > 4 ) ? 4 : len;
751        sum = 0;
752
753        for( i = 0; i < 32; i++ )
754        {
755            info->v0 += ( ( ( info->v1 << 4 ) ^ ( info->v1 >> 5 ) )
756                            + info->v1 ) ^ ( sum + k[sum & 3] );
757            sum += delta;
758            info->v1 += ( ( ( info->v0 << 4 ) ^ ( info->v0 >> 5 ) )
759                            + info->v0 ) ^ ( sum + k[( sum>>11 ) & 3] );
760        }
761
762        PUT_UINT32_BE( info->v0, result, 0 );
763        memcpy( out, result, use_len );
764        len -= use_len;
765        out += 4;
766    }
767
768    return( 0 );
769}
770
771int mbedtls_test_hexcmp( uint8_t * a, uint8_t * b, uint32_t a_len, uint32_t b_len )
772{
773    int ret = 0;
774    uint32_t i = 0;
775
776    if( a_len != b_len )
777        return( -1 );
778
779    for( i = 0; i < a_len; i++ )
780    {
781        if( a[i] != b[i] )
782        {
783            ret = -1;
784            break;
785        }
786    }
787    return ret;
788}
789
790#if defined(MBEDTLS_TEST_MUTEX_USAGE)
791/** Mutex usage verification framework.
792 *
793 * The mutex usage verification code below aims to detect bad usage of
794 * Mbed TLS's mutex abstraction layer at runtime. Note that this is solely
795 * about the use of the mutex itself, not about checking whether the mutex
796 * correctly protects whatever it is supposed to protect.
797 *
798 * The normal usage of a mutex is:
799 * ```
800 * digraph mutex_states {
801 *   "UNINITIALIZED"; // the initial state
802 *   "IDLE";
803 *   "FREED";
804 *   "LOCKED";
805 *   "UNINITIALIZED" -> "IDLE" [label="init"];
806 *   "FREED" -> "IDLE" [label="init"];
807 *   "IDLE" -> "LOCKED" [label="lock"];
808 *   "LOCKED" -> "IDLE" [label="unlock"];
809 *   "IDLE" -> "FREED" [label="free"];
810 * }
811 * ```
812 *
813 * All bad transitions that can be unambiguously detected are reported.
814 * An attempt to use an uninitialized mutex cannot be detected in general
815 * since the memory content may happen to denote a valid state. For the same
816 * reason, a double init cannot be detected.
817 * All-bits-zero is the state of a freed mutex, which is distinct from an
818 * initialized mutex, so attempting to use zero-initialized memory as a mutex
819 * without calling the init function is detected.
820 *
821 * The framework attempts to detect missing calls to init and free by counting
822 * calls to init and free. If there are more calls to init than free, this
823 * means that a mutex is not being freed somewhere, which is a memory leak
824 * on platforms where a mutex consumes resources other than the
825 * mbedtls_threading_mutex_t object itself. If there are more calls to free
826 * than init, this indicates a missing init, which is likely to be detected
827 * by an attempt to lock the mutex as well. A limitation of this framework is
828 * that it cannot detect scenarios where there is exactly the same number of
829 * calls to init and free but the calls don't match. A bug like this is
830 * unlikely to happen uniformly throughout the whole test suite though.
831 *
832 * If an error is detected, this framework will report what happened and the
833 * test case will be marked as failed. Unfortunately, the error report cannot
834 * indicate the exact location of the problematic call. To locate the error,
835 * use a debugger and set a breakpoint on mbedtls_test_mutex_usage_error().
836 */
837enum value_of_mutex_is_valid_field
838{
839    /* Potential values for the is_valid field of mbedtls_threading_mutex_t.
840     * Note that MUTEX_FREED must be 0 and MUTEX_IDLE must be 1 for
841     * compatibility with threading_mutex_init_pthread() and
842     * threading_mutex_free_pthread(). MUTEX_LOCKED could be any nonzero
843     * value. */
844    MUTEX_FREED = 0, //!< Set by threading_mutex_free_pthread
845    MUTEX_IDLE = 1, //!< Set by threading_mutex_init_pthread and by our unlock
846    MUTEX_LOCKED = 2, //!< Set by our lock
847};
848
849typedef struct
850{
851    void (*init)( mbedtls_threading_mutex_t * );
852    void (*free)( mbedtls_threading_mutex_t * );
853    int (*lock)( mbedtls_threading_mutex_t * );
854    int (*unlock)( mbedtls_threading_mutex_t * );
855} mutex_functions_t;
856static mutex_functions_t mutex_functions;
857
858/** The total number of calls to mbedtls_mutex_init(), minus the total number
859 * of calls to mbedtls_mutex_free().
860 *
861 * Reset to 0 after each test case.
862 */
863static int live_mutexes;
864
865static void mbedtls_test_mutex_usage_error( mbedtls_threading_mutex_t *mutex,
866                                            const char *msg )
867{
868    (void) mutex;
869    if( test_info.mutex_usage_error == NULL )
870        test_info.mutex_usage_error = msg;
871    mbedtls_fprintf( stdout, "[mutex: %s] ", msg );
872    /* Don't mark the test as failed yet. This way, if the test fails later
873     * for a functional reason, the test framework will report the message
874     * and location for this functional reason. If the test passes,
875     * mbedtls_test_mutex_usage_check() will mark it as failed. */
876}
877
878static void mbedtls_test_wrap_mutex_init( mbedtls_threading_mutex_t *mutex )
879{
880    mutex_functions.init( mutex );
881    if( mutex->is_valid )
882        ++live_mutexes;
883}
884
885static void mbedtls_test_wrap_mutex_free( mbedtls_threading_mutex_t *mutex )
886{
887    switch( mutex->is_valid )
888    {
889        case MUTEX_FREED:
890            mbedtls_test_mutex_usage_error( mutex, "free without init or double free" );
891            break;
892        case MUTEX_IDLE:
893            /* Do nothing. The underlying free function will reset is_valid
894             * to 0. */
895            break;
896        case MUTEX_LOCKED:
897            mbedtls_test_mutex_usage_error( mutex, "free without unlock" );
898            break;
899        default:
900            mbedtls_test_mutex_usage_error( mutex, "corrupted state" );
901            break;
902    }
903    if( mutex->is_valid )
904        --live_mutexes;
905    mutex_functions.free( mutex );
906}
907
908static int mbedtls_test_wrap_mutex_lock( mbedtls_threading_mutex_t *mutex )
909{
910    int ret = mutex_functions.lock( mutex );
911    switch( mutex->is_valid )
912    {
913        case MUTEX_FREED:
914            mbedtls_test_mutex_usage_error( mutex, "lock without init" );
915            break;
916        case MUTEX_IDLE:
917            if( ret == 0 )
918                mutex->is_valid = 2;
919            break;
920        case MUTEX_LOCKED:
921            mbedtls_test_mutex_usage_error( mutex, "double lock" );
922            break;
923        default:
924            mbedtls_test_mutex_usage_error( mutex, "corrupted state" );
925            break;
926    }
927    return( ret );
928}
929
930static int mbedtls_test_wrap_mutex_unlock( mbedtls_threading_mutex_t *mutex )
931{
932    int ret = mutex_functions.unlock( mutex );
933    switch( mutex->is_valid )
934    {
935        case MUTEX_FREED:
936            mbedtls_test_mutex_usage_error( mutex, "unlock without init" );
937            break;
938        case MUTEX_IDLE:
939            mbedtls_test_mutex_usage_error( mutex, "unlock without lock" );
940            break;
941        case MUTEX_LOCKED:
942            if( ret == 0 )
943                mutex->is_valid = MUTEX_IDLE;
944            break;
945        default:
946            mbedtls_test_mutex_usage_error( mutex, "corrupted state" );
947            break;
948    }
949    return( ret );
950}
951
952static void mbedtls_test_mutex_usage_init( void )
953{
954    mutex_functions.init = mbedtls_mutex_init;
955    mutex_functions.free = mbedtls_mutex_free;
956    mutex_functions.lock = mbedtls_mutex_lock;
957    mutex_functions.unlock = mbedtls_mutex_unlock;
958    mbedtls_mutex_init = &mbedtls_test_wrap_mutex_init;
959    mbedtls_mutex_free = &mbedtls_test_wrap_mutex_free;
960    mbedtls_mutex_lock = &mbedtls_test_wrap_mutex_lock;
961    mbedtls_mutex_unlock = &mbedtls_test_wrap_mutex_unlock;
962}
963
964static void mbedtls_test_mutex_usage_check( void )
965{
966    if( live_mutexes != 0 )
967    {
968        /* A positive number (more init than free) means that a mutex resource
969         * is leaking (on platforms where a mutex consumes more than the
970         * mbedtls_threading_mutex_t object itself). The rare case of a
971         * negative number means a missing init somewhere. */
972        mbedtls_fprintf( stdout, "[mutex: %d leaked] ", live_mutexes );
973        live_mutexes = 0;
974        if( test_info.mutex_usage_error == NULL )
975            test_info.mutex_usage_error = "missing free";
976    }
977    if( test_info.mutex_usage_error != NULL &&
978        test_info.result != TEST_RESULT_FAILED )
979    {
980        /* Functionally, the test passed. But there was a mutex usage error,
981         * so mark the test as failed after all. */
982        test_fail( "Mutex usage error", __LINE__, __FILE__ );
983    }
984    test_info.mutex_usage_error = NULL;
985}
986
987#endif /* MBEDTLS_TEST_MUTEX_USAGE */
988