1 /*
2  *  Self-test demonstration program
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
9 
10 #include "mbedtls/build_info.h"
11 
12 #include "mbedtls/entropy.h"
13 #include "mbedtls/hmac_drbg.h"
14 #include "mbedtls/ctr_drbg.h"
15 #include "mbedtls/dhm.h"
16 #include "mbedtls/gcm.h"
17 #include "mbedtls/ccm.h"
18 #include "mbedtls/cmac.h"
19 #include "mbedtls/md5.h"
20 #include "mbedtls/ripemd160.h"
21 #include "mbedtls/sha1.h"
22 #include "mbedtls/sha256.h"
23 #include "mbedtls/sha512.h"
24 #include "mbedtls/sha3.h"
25 #include "mbedtls/des.h"
26 #include "mbedtls/aes.h"
27 #include "mbedtls/camellia.h"
28 #include "mbedtls/aria.h"
29 #include "mbedtls/chacha20.h"
30 #include "mbedtls/poly1305.h"
31 #include "mbedtls/chachapoly.h"
32 #include "mbedtls/base64.h"
33 #include "mbedtls/bignum.h"
34 #include "mbedtls/rsa.h"
35 #include "mbedtls/x509.h"
36 #include "mbedtls/pkcs5.h"
37 #include "mbedtls/ecp.h"
38 #include "mbedtls/ecjpake.h"
39 #include "mbedtls/timing.h"
40 #include "mbedtls/nist_kw.h"
41 #include "mbedtls/debug.h"
42 
43 #include <limits.h>
44 #include <string.h>
45 
46 #include "mbedtls/platform.h"
47 
48 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
49 #include "mbedtls/memory_buffer_alloc.h"
50 #endif
51 
52 
53 #if defined MBEDTLS_SELF_TEST
54 /* Sanity check for malloc. This is not expected to fail, and is rather
55  * intended to display potentially useful information about the platform,
56  * in particular the behavior of malloc(0). */
calloc_self_test(int verbose)57 static int calloc_self_test(int verbose)
58 {
59     int failures = 0;
60     void *empty1 = mbedtls_calloc(0, 1);
61     void *empty2 = mbedtls_calloc(0, 1);
62     void *buffer1 = mbedtls_calloc(1, 1);
63     void *buffer2 = mbedtls_calloc(1, 1);
64     unsigned int buffer_3_size = 256;
65     unsigned int buffer_4_size = 4097; /* Allocate more than the usual page size */
66     unsigned char *buffer3 = mbedtls_calloc(buffer_3_size, 1);
67     unsigned char *buffer4 = mbedtls_calloc(buffer_4_size, 1);
68 
69     if (empty1 == NULL && empty2 == NULL) {
70         if (verbose) {
71             mbedtls_printf("  CALLOC(0,1): passed (NULL)\n");
72         }
73     } else if (empty1 == NULL || empty2 == NULL) {
74         if (verbose) {
75             mbedtls_printf("  CALLOC(0,1): failed (mix of NULL and non-NULL)\n");
76         }
77         ++failures;
78     } else if (empty1 == empty2) {
79         if (verbose) {
80             mbedtls_printf("  CALLOC(0,1): passed (same non-null)\n");
81         }
82     } else {
83         if (verbose) {
84             mbedtls_printf("  CALLOC(0,1): passed (distinct non-null)\n");
85         }
86     }
87 
88     mbedtls_free(empty1);
89     mbedtls_free(empty2);
90 
91     empty1 = mbedtls_calloc(1, 0);
92     empty2 = mbedtls_calloc(1, 0);
93     if (empty1 == NULL && empty2 == NULL) {
94         if (verbose) {
95             mbedtls_printf("  CALLOC(1,0): passed (NULL)\n");
96         }
97     } else if (empty1 == NULL || empty2 == NULL) {
98         if (verbose) {
99             mbedtls_printf("  CALLOC(1,0): failed (mix of NULL and non-NULL)\n");
100         }
101         ++failures;
102     } else if (empty1 == empty2) {
103         if (verbose) {
104             mbedtls_printf("  CALLOC(1,0): passed (same non-null)\n");
105         }
106     } else {
107         if (verbose) {
108             mbedtls_printf("  CALLOC(1,0): passed (distinct non-null)\n");
109         }
110     }
111 
112     if (buffer1 == NULL || buffer2 == NULL) {
113         if (verbose) {
114             mbedtls_printf("  CALLOC(1): failed (NULL)\n");
115         }
116         ++failures;
117     } else if (buffer1 == buffer2) {
118         if (verbose) {
119             mbedtls_printf("  CALLOC(1): failed (same buffer twice)\n");
120         }
121         ++failures;
122     } else {
123         if (verbose) {
124             mbedtls_printf("  CALLOC(1): passed\n");
125         }
126     }
127 
128     mbedtls_free(buffer1);
129     buffer1 = mbedtls_calloc(1, 1);
130     if (buffer1 == NULL) {
131         if (verbose) {
132             mbedtls_printf("  CALLOC(1 again): failed (NULL)\n");
133         }
134         ++failures;
135     } else {
136         if (verbose) {
137             mbedtls_printf("  CALLOC(1 again): passed\n");
138         }
139     }
140 
141     for (unsigned int i = 0; i < buffer_3_size; i++) {
142         if (buffer3[i] != 0) {
143             ++failures;
144             if (verbose) {
145                 mbedtls_printf("  CALLOC(%u): failed (memory not initialized to 0)\n",
146                                buffer_3_size);
147             }
148             break;
149         }
150     }
151 
152     for (unsigned int i = 0; i < buffer_4_size; i++) {
153         if (buffer4[i] != 0) {
154             ++failures;
155             if (verbose) {
156                 mbedtls_printf("  CALLOC(%u): failed (memory not initialized to 0)\n",
157                                buffer_4_size);
158             }
159             break;
160         }
161     }
162 
163     if (verbose) {
164         mbedtls_printf("\n");
165     }
166     mbedtls_free(empty1);
167     mbedtls_free(empty2);
168     mbedtls_free(buffer1);
169     mbedtls_free(buffer2);
170     mbedtls_free(buffer3);
171     mbedtls_free(buffer4);
172     return failures;
173 }
174 #endif /* MBEDTLS_SELF_TEST */
175 
test_snprintf(size_t n,const char * ref_buf,int ref_ret)176 static int test_snprintf(size_t n, const char *ref_buf, int ref_ret)
177 {
178     int ret;
179     char buf[10] = "xxxxxxxxx";
180     const char ref[10] = "xxxxxxxxx";
181 
182     ret = mbedtls_snprintf(buf, n, "%s", "123");
183     if (ret < 0 || (size_t) ret >= n) {
184         ret = -1;
185     }
186 
187     if (strncmp(ref_buf, buf, sizeof(buf)) != 0 ||
188         ref_ret != ret ||
189         memcmp(buf + n, ref + n, sizeof(buf) - n) != 0) {
190         return 1;
191     }
192 
193     return 0;
194 }
195 
run_test_snprintf(void)196 static int run_test_snprintf(void)
197 {
198     return test_snprintf(0, "xxxxxxxxx",  -1) != 0 ||
199            test_snprintf(1, "",           -1) != 0 ||
200            test_snprintf(2, "1",          -1) != 0 ||
201            test_snprintf(3, "12",         -1) != 0 ||
202            test_snprintf(4, "123",         3) != 0 ||
203            test_snprintf(5, "123",         3) != 0;
204 }
205 
206 /*
207  * Check if a seed file is present, and if not create one for the entropy
208  * self-test. If this fails, we attempt the test anyway, so no error is passed
209  * back.
210  */
211 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_ENTROPY_C)
212 #if defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
create_entropy_seed_file(void)213 static void create_entropy_seed_file(void)
214 {
215     int result;
216     size_t output_len = 0;
217     unsigned char seed_value[MBEDTLS_ENTROPY_BLOCK_SIZE];
218 
219     /* Attempt to read the entropy seed file. If this fails - attempt to write
220      * to the file to ensure one is present. */
221     result = mbedtls_platform_std_nv_seed_read(seed_value,
222                                                MBEDTLS_ENTROPY_BLOCK_SIZE);
223     if (0 == result) {
224         return;
225     }
226 
227     result = mbedtls_platform_entropy_poll(NULL,
228                                            seed_value,
229                                            MBEDTLS_ENTROPY_BLOCK_SIZE,
230                                            &output_len);
231     if (0 != result) {
232         return;
233     }
234 
235     if (MBEDTLS_ENTROPY_BLOCK_SIZE != output_len) {
236         return;
237     }
238 
239     mbedtls_platform_std_nv_seed_write(seed_value, MBEDTLS_ENTROPY_BLOCK_SIZE);
240 }
241 #endif
242 
mbedtls_entropy_self_test_wrapper(int verbose)243 int mbedtls_entropy_self_test_wrapper(int verbose)
244 {
245 #if defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
246     create_entropy_seed_file();
247 #endif
248     return mbedtls_entropy_self_test(verbose);
249 }
250 #endif
251 
252 #if defined(MBEDTLS_SELF_TEST)
253 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
mbedtls_memory_buffer_alloc_free_and_self_test(int verbose)254 int mbedtls_memory_buffer_alloc_free_and_self_test(int verbose)
255 {
256     if (verbose != 0) {
257 #if defined(MBEDTLS_MEMORY_DEBUG)
258         mbedtls_memory_buffer_alloc_status();
259 #endif
260     }
261     mbedtls_memory_buffer_alloc_free();
262     return mbedtls_memory_buffer_alloc_self_test(verbose);
263 }
264 #endif
265 
266 typedef struct {
267     const char *name;
268     int (*function)(int);
269 } selftest_t;
270 
271 const selftest_t selftests[] =
272 {
273     { "calloc", calloc_self_test },
274 #if defined(MBEDTLS_MD5_C)
275     { "md5", mbedtls_md5_self_test },
276 #endif
277 #if defined(MBEDTLS_RIPEMD160_C)
278     { "ripemd160", mbedtls_ripemd160_self_test },
279 #endif
280 #if defined(MBEDTLS_SHA1_C)
281     { "sha1", mbedtls_sha1_self_test },
282 #endif
283 #if defined(MBEDTLS_SHA224_C)
284     { "sha224", mbedtls_sha224_self_test },
285 #endif
286 #if defined(MBEDTLS_SHA256_C)
287     { "sha256", mbedtls_sha256_self_test },
288 #endif
289 #if defined(MBEDTLS_SHA384_C)
290     { "sha384", mbedtls_sha384_self_test },
291 #endif
292 #if defined(MBEDTLS_SHA512_C)
293     { "sha512", mbedtls_sha512_self_test },
294 #endif
295 #if defined(MBEDTLS_SHA3_C)
296     { "sha3", mbedtls_sha3_self_test },
297 #endif
298 #if defined(MBEDTLS_DES_C)
299     { "des", mbedtls_des_self_test },
300 #endif
301 #if defined(MBEDTLS_AES_C)
302     { "aes", mbedtls_aes_self_test },
303 #endif
304 #if defined(MBEDTLS_GCM_C) && defined(MBEDTLS_AES_C)
305     { "gcm", mbedtls_gcm_self_test },
306 #endif
307 #if defined(MBEDTLS_CCM_C) && defined(MBEDTLS_AES_C)
308     { "ccm", mbedtls_ccm_self_test },
309 #endif
310 #if defined(MBEDTLS_NIST_KW_C) && defined(MBEDTLS_AES_C)
311     { "nist_kw", mbedtls_nist_kw_self_test },
312 #endif
313 #if defined(MBEDTLS_CMAC_C)
314     { "cmac", mbedtls_cmac_self_test },
315 #endif
316 #if defined(MBEDTLS_CHACHA20_C)
317     { "chacha20", mbedtls_chacha20_self_test },
318 #endif
319 #if defined(MBEDTLS_POLY1305_C)
320     { "poly1305", mbedtls_poly1305_self_test },
321 #endif
322 #if defined(MBEDTLS_CHACHAPOLY_C)
323     { "chacha20-poly1305", mbedtls_chachapoly_self_test },
324 #endif
325 #if defined(MBEDTLS_BASE64_C)
326     { "base64", mbedtls_base64_self_test },
327 #endif
328 #if defined(MBEDTLS_BIGNUM_C)
329     { "mpi", mbedtls_mpi_self_test },
330 #endif
331 #if defined(MBEDTLS_RSA_C)
332     { "rsa", mbedtls_rsa_self_test },
333 #endif
334 #if defined(MBEDTLS_CAMELLIA_C)
335     { "camellia", mbedtls_camellia_self_test },
336 #endif
337 #if defined(MBEDTLS_ARIA_C)
338     { "aria", mbedtls_aria_self_test },
339 #endif
340 #if defined(MBEDTLS_CTR_DRBG_C)
341     { "ctr_drbg", mbedtls_ctr_drbg_self_test },
342 #endif
343 #if defined(MBEDTLS_HMAC_DRBG_C)
344     { "hmac_drbg", mbedtls_hmac_drbg_self_test },
345 #endif
346 #if defined(MBEDTLS_ECP_C)
347     { "ecp", mbedtls_ecp_self_test },
348 #endif
349 #if defined(MBEDTLS_ECJPAKE_C)
350     { "ecjpake", mbedtls_ecjpake_self_test },
351 #endif
352 #if defined(MBEDTLS_DHM_C)
353     { "dhm", mbedtls_dhm_self_test },
354 #endif
355 #if defined(MBEDTLS_ENTROPY_C)
356     { "entropy", mbedtls_entropy_self_test_wrapper },
357 #endif
358 #if defined(MBEDTLS_PKCS5_C)
359     { "pkcs5", mbedtls_pkcs5_self_test },
360 #endif
361 /* Heap test comes last */
362 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
363     { "memory_buffer_alloc", mbedtls_memory_buffer_alloc_free_and_self_test },
364 #endif
365     { NULL, NULL }
366 };
367 #endif /* MBEDTLS_SELF_TEST */
368 
main(int argc,char * argv[])369 int main(int argc, char *argv[])
370 {
371 #if defined(MBEDTLS_SELF_TEST)
372     const selftest_t *test;
373 #endif /* MBEDTLS_SELF_TEST */
374     char **argp;
375     int v = 1; /* v=1 for verbose mode */
376     int exclude_mode = 0;
377     int suites_tested = 0, suites_failed = 0;
378 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && defined(MBEDTLS_SELF_TEST)
379     unsigned char buf[1000000];
380 #endif
381     void *pointer;
382 
383     /*
384      * Check some basic platform requirements as specified in README.md
385      */
386     if (SIZE_MAX < INT_MAX || SIZE_MAX < UINT_MAX) {
387         mbedtls_printf("SIZE_MAX must be at least as big as INT_MAX and UINT_MAX\n");
388         mbedtls_exit(MBEDTLS_EXIT_FAILURE);
389     }
390 
391     if (sizeof(int) < 4) {
392         mbedtls_printf("int must be at least 32 bits\n");
393         mbedtls_exit(MBEDTLS_EXIT_FAILURE);
394     }
395 
396     if (sizeof(size_t) < 4) {
397         mbedtls_printf("size_t must be at least 32 bits\n");
398         mbedtls_exit(MBEDTLS_EXIT_FAILURE);
399     }
400 
401     uint32_t endian_test = 0x12345678;
402     char *p = (char *) &endian_test;
403     if (!(p[0] == 0x12 && p[1] == 0x34 && p[2] == 0x56 && p[3] == 0x78) &&
404         !(p[3] == 0x12 && p[2] == 0x34 && p[1] == 0x56 && p[0] == 0x78)) {
405         mbedtls_printf("Mixed-endian platforms are not supported\n");
406         mbedtls_exit(MBEDTLS_EXIT_FAILURE);
407     }
408 
409     /*
410      * The C standard doesn't guarantee that all-bits-0 is the representation
411      * of a NULL pointer. We do however use that in our code for initializing
412      * structures, which should work on every modern platform. Let's be sure.
413      */
414     memset(&pointer, 0, sizeof(void *));
415     if (pointer != NULL) {
416         mbedtls_printf("all-bits-zero is not a NULL pointer\n");
417         mbedtls_exit(MBEDTLS_EXIT_FAILURE);
418     }
419 
420     /*
421      * The C standard allows padding bits in the representation
422      * of standard integer types, but our code does currently not
423      * support them.
424      *
425      * Here we check that the underlying C implementation doesn't
426      * use padding bits, and fail cleanly if it does.
427      *
428      * The check works by casting the maximum value representable
429      * by a given integer type into the unpadded integer type of the
430      * same bit-width and checking that it agrees with the maximum value
431      * of that unpadded type. For example, for a 4-byte int,
432      * MAX_INT should be 0x7fffffff in int32_t. This assumes that
433      * CHAR_BIT == 8, which is checked in check_config.h.
434      *
435      * We assume that [u]intxx_t exist and that they don't
436      * have padding bits, as the standard requires.
437      */
438 
439 #define CHECK_PADDING_SIGNED(TYPE, NAME)                                \
440     do                                                                  \
441     {                                                                   \
442         if (sizeof(TYPE) == 2 || sizeof(TYPE) == 4 ||               \
443             sizeof(TYPE) == 8) {                                 \
444             if ((sizeof(TYPE) == 2 &&                                \
445                  (int16_t) NAME ## _MAX != 0x7FFF)             ||       \
446                 (sizeof(TYPE) == 4 &&                                \
447                  (int32_t) NAME ## _MAX != 0x7FFFFFFF)         ||       \
448                 (sizeof(TYPE) == 8 &&                                \
449                  (int64_t) NAME ## _MAX != 0x7FFFFFFFFFFFFFFF))        \
450             {                                                           \
451                 mbedtls_printf("Type '" #TYPE "' has padding bits\n"); \
452                 mbedtls_exit(MBEDTLS_EXIT_FAILURE);                   \
453             }                                                           \
454         } else {                                                        \
455             mbedtls_printf("Padding checks only implemented for types of size 2, 4 or 8" \
456                            " - cannot check type '" #TYPE "' of size %" MBEDTLS_PRINTF_SIZET "\n",       \
457                            sizeof(TYPE));                                       \
458             mbedtls_exit(MBEDTLS_EXIT_FAILURE);                       \
459         }                                                               \
460     } while (0)
461 
462 #define CHECK_PADDING_UNSIGNED(TYPE, NAME)                              \
463     do                                                                  \
464     {                                                                   \
465         if ((sizeof(TYPE) == 2 &&                                    \
466              (uint16_t) NAME ## _MAX != 0xFFFF)             ||        \
467             (sizeof(TYPE) == 4 &&                                    \
468              (uint32_t) NAME ## _MAX != 0xFFFFFFFF)         ||        \
469             (sizeof(TYPE) == 8 &&                                    \
470              (uint64_t) NAME ## _MAX != 0xFFFFFFFFFFFFFFFF))         \
471         {                                                               \
472             mbedtls_printf("Type '" #TYPE "' has padding bits\n");    \
473             mbedtls_exit(MBEDTLS_EXIT_FAILURE);                       \
474         }                                                               \
475     } while (0)
476 
477     CHECK_PADDING_SIGNED(short,        SHRT);
478     CHECK_PADDING_SIGNED(int,           INT);
479     CHECK_PADDING_SIGNED(long,         LONG);
480     CHECK_PADDING_SIGNED(long long,   LLONG);
481     CHECK_PADDING_SIGNED(ptrdiff_t, PTRDIFF);
482 
483     CHECK_PADDING_UNSIGNED(unsigned short,      USHRT);
484     CHECK_PADDING_UNSIGNED(unsigned,             UINT);
485     CHECK_PADDING_UNSIGNED(unsigned long,       ULONG);
486     CHECK_PADDING_UNSIGNED(unsigned long long, ULLONG);
487     CHECK_PADDING_UNSIGNED(size_t,               SIZE);
488 
489 #undef CHECK_PADDING_SIGNED
490 #undef CHECK_PADDING_UNSIGNED
491 
492     /*
493      * Make sure we have a snprintf that correctly zero-terminates
494      */
495     if (run_test_snprintf() != 0) {
496         mbedtls_printf("the snprintf implementation is broken\n");
497         mbedtls_exit(MBEDTLS_EXIT_FAILURE);
498     }
499 
500     for (argp = argv + (argc >= 1 ? 1 : argc); *argp != NULL; ++argp) {
501         if (strcmp(*argp, "--quiet") == 0 ||
502             strcmp(*argp, "-q") == 0) {
503             v = 0;
504         } else if (strcmp(*argp, "--exclude") == 0 ||
505                    strcmp(*argp, "-x") == 0) {
506             exclude_mode = 1;
507         } else {
508             break;
509         }
510     }
511 
512     if (v != 0) {
513         mbedtls_printf("\n");
514     }
515 
516 #if defined(MBEDTLS_SELF_TEST)
517 
518 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
519     mbedtls_memory_buffer_alloc_init(buf, sizeof(buf));
520 #endif
521 
522     if (*argp != NULL && exclude_mode == 0) {
523         /* Run the specified tests */
524         for (; *argp != NULL; argp++) {
525             for (test = selftests; test->name != NULL; test++) {
526                 if (!strcmp(*argp, test->name)) {
527                     if (test->function(v)  != 0) {
528                         suites_failed++;
529                     }
530                     suites_tested++;
531                     break;
532                 }
533             }
534             if (test->name == NULL) {
535                 mbedtls_printf("  Test suite %s not available -> failed\n\n", *argp);
536                 suites_failed++;
537             }
538         }
539     } else {
540         /* Run all the tests except excluded ones */
541         for (test = selftests; test->name != NULL; test++) {
542             if (exclude_mode) {
543                 char **excluded;
544                 for (excluded = argp; *excluded != NULL; ++excluded) {
545                     if (!strcmp(*excluded, test->name)) {
546                         break;
547                     }
548                 }
549                 if (*excluded) {
550                     if (v) {
551                         mbedtls_printf("  Skip: %s\n", test->name);
552                     }
553                     continue;
554                 }
555             }
556             if (test->function(v)  != 0) {
557                 suites_failed++;
558             }
559             suites_tested++;
560         }
561     }
562 
563 #else
564     (void) exclude_mode;
565     mbedtls_printf(" MBEDTLS_SELF_TEST not defined.\n");
566 #endif
567 
568     if (v != 0) {
569         mbedtls_printf("  Executed %d test suites\n\n", suites_tested);
570 
571         if (suites_failed > 0) {
572             mbedtls_printf("  [ %d tests FAIL ]\n\n", suites_failed);
573         } else {
574             mbedtls_printf("  [ All tests PASS ]\n\n");
575         }
576     }
577 
578     if (suites_failed > 0) {
579         mbedtls_exit(MBEDTLS_EXIT_FAILURE);
580     }
581 
582     mbedtls_exit(MBEDTLS_EXIT_SUCCESS);
583 }
584