From b99e99f5d9547cb7af6c3eb83f792c7cdbb7bd6d Mon Sep 17 00:00:00 2001 From: Diadlo Date: Tue, 27 Dec 2016 00:00:26 +0300 Subject: [PATCH] Add tests to secure memcmp and memzero functions. --- auto_tests/crypto_test.c | 87 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/auto_tests/crypto_test.c b/auto_tests/crypto_test.c index c1003f80..7c32b43a 100644 --- a/auto_tests/crypto_test.c +++ b/auto_tests/crypto_test.c @@ -2,7 +2,9 @@ #include "config.h" #endif +#include "../toxcore/misc_tools.h" #include "../toxcore/net_crypto.h" + #include #include #include @@ -323,6 +325,89 @@ START_TEST(test_increment_nonce) } END_TEST +START_TEST(test_memzero) +{ + uint8_t src[sizeof(test_c)]; + memcpy(src, test_c, sizeof(test_c)); + + crypto_memzero(src, sizeof(src)); + size_t i; + + for (i = 0; i < sizeof(src); i++) { + ck_assert_msg(src[i] == 0, "Memory is not zeroed"); + } +} +END_TEST + +#define CRYPTO_TEST_MEMCMP_SIZE 1024*32 +#define CRYPTO_TEST_MEMCMP_COUNT 500 +#define CRYPTO_TEST_MEMCMP_EPS 10 + +static make_quick_sort(clock_t) + +static int cmp(clock_t a, clock_t b) +{ + if (a < b) { + return -1; + } + + if (a > b) { + return 1; + } + + return 0; +} + +static clock_t memcmp_time(void *a, void *b, size_t len) +{ + clock_t start = clock(); + crypto_memcmp(a, b, len); + return clock() - start; +} + +static clock_t memcmp_median(void *a, void *b, size_t len) +{ + size_t i; + clock_t results[CRYPTO_TEST_MEMCMP_COUNT]; + + for (i = 0; i < CRYPTO_TEST_MEMCMP_COUNT; i++) { + results[i] = memcmp_time(a, b, len); + } + + clock_t_quick_sort(results, CRYPTO_TEST_MEMCMP_COUNT, cmp); + return results[CRYPTO_TEST_MEMCMP_COUNT / 2]; +} + +START_TEST(test_memcmp) +{ + uint8_t src[CRYPTO_TEST_MEMCMP_SIZE]; + rand_bytes(src, sizeof(src)); + + uint8_t same[sizeof(src)]; + memcpy(same, src, sizeof(src)); + + uint8_t not_same[sizeof(src)]; + rand_bytes(not_same, sizeof(not_same)); + + clock_t same_median = memcmp_median(src, same, sizeof(src)); + clock_t not_same_median = memcmp_median(src, not_same, sizeof(src)); + + clock_t delta; + + if (same_median > not_same_median) { + delta = same_median - not_same_median; + } else { + delta = not_same_median - same_median; + } + + ck_assert_msg(delta < CRYPTO_TEST_MEMCMP_EPS, + "Delta time is too long (%d >= %d)\n" + "Time of the same data comparation: %d\n" + "Time of the different data comparation: %d", + delta, CRYPTO_TEST_MEMCMP_EPS, same_median, not_same_median); +} +END_TEST + static Suite *crypto_suite(void) { Suite *s = suite_create("Crypto"); @@ -333,6 +418,8 @@ static Suite *crypto_suite(void) DEFTESTCASE(large_data); DEFTESTCASE(large_data_symmetric); DEFTESTCASE_SLOW(increment_nonce, 20); + DEFTESTCASE(memzero); + DEFTESTCASE(memcmp); return s; }