helpers.function 32 KB

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