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