Wipe (some) secrets from memory after use
[tinc] / test / unit / test_xalloc.c
1 #include "unittest.h"
2 #include "../../src/xalloc.h"
3
4 static const uint8_t ref[] = {0, 1, 2, 3, 4, 5, 6, 7};
5
6 static void test_memzero_wipes_partial(void **state) {
7         (void)state;
8
9         uint8_t buf[sizeof(ref)];
10         memcpy(buf, ref, sizeof(buf));
11
12         const size_t len = 2;
13         memzero(buf, len);
14         assert_int_equal(0, buf[0]);
15         assert_int_equal(0, buf[1]);
16
17         assert_memory_equal(&buf[len], &ref[len], sizeof(ref) - len);
18 }
19
20 static void test_memzero_wipes_buffer(void **state) {
21         (void)state;
22
23         uint8_t buf[sizeof(ref)];
24         uint8_t zero[sizeof(ref)] = {0};
25
26         memcpy(buf, ref, sizeof(buf));
27         assert_memory_equal(ref, buf, sizeof(buf));
28
29         memzero(buf, sizeof(buf));
30         assert_memory_not_equal(buf, ref, sizeof(buf));
31         assert_memory_equal(zero, buf, sizeof(buf));
32 }
33
34 static void test_memzero_zerolen_does_not_change_memory(void **state) {
35         (void)state;
36
37         uint8_t buf[sizeof(ref)];
38
39         memcpy(buf, ref, sizeof(buf));
40         assert_memory_equal(ref, buf, sizeof(buf));
41
42         memzero(buf, 0);
43         assert_memory_equal(ref, buf, sizeof(buf));
44 }
45
46 // This test will fail under ASAN if xzfree forgets to call free() or overflows the buffer
47 static void test_xzfree_frees_memory(void **state) {
48         (void)state;
49
50         xzfree(xmalloc(64), 64);
51 }
52
53 int main(void) {
54         const struct CMUnitTest tests[] = {
55                 cmocka_unit_test(test_memzero_wipes_partial),
56                 cmocka_unit_test(test_memzero_wipes_buffer),
57                 cmocka_unit_test(test_memzero_zerolen_does_not_change_memory),
58                 cmocka_unit_test(test_xzfree_frees_memory),
59         };
60         return cmocka_run_group_tests(tests, NULL, NULL);
61 }