1 /**
2  * PSA API key derivation demonstration
3  *
4  * This program calculates a key ladder: a chain of secret material, each
5  * derived from the previous one in a deterministic way based on a label.
6  * Two keys are identical if and only if they are derived from the same key
7  * using the same label.
8  *
9  * The initial key is called the master key. The master key is normally
10  * randomly generated, but it could itself be derived from another key.
11  *
12  * This program derives a series of keys called intermediate keys.
13  * The first intermediate key is derived from the master key using the
14  * first label passed on the command line. Each subsequent intermediate
15  * key is derived from the previous one using the next label passed
16  * on the command line.
17  *
18  * This program has four modes of operation:
19  *
20  * - "generate": generate a random master key.
21  * - "wrap": derive a wrapping key from the last intermediate key,
22  *           and use that key to encrypt-and-authenticate some data.
23  * - "unwrap": derive a wrapping key from the last intermediate key,
24  *             and use that key to decrypt-and-authenticate some
25  *             ciphertext created by wrap mode.
26  * - "save": save the last intermediate key so that it can be reused as
27  *           the master key in another run of the program.
28  *
29  * See the usage() output for the command line usage. See the file
30  * `key_ladder_demo.sh` for an example run.
31  */
32 
33 /*
34  *  Copyright The Mbed TLS Contributors
35  *  SPDX-License-Identifier: Apache-2.0
36  *
37  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
38  *  not use this file except in compliance with the License.
39  *  You may obtain a copy of the License at
40  *
41  *  http://www.apache.org/licenses/LICENSE-2.0
42  *
43  *  Unless required by applicable law or agreed to in writing, software
44  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
45  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
46  *  See the License for the specific language governing permissions and
47  *  limitations under the License.
48  */
49 
50 /* First include Mbed TLS headers to get the Mbed TLS configuration and
51  * platform definitions that we'll use in this program. Also include
52  * standard C headers for functions we'll use here. */
53 #include "mbedtls/build_info.h"
54 
55 #include <stdlib.h>
56 #include <stdio.h>
57 #include <string.h>
58 
59 #include "mbedtls/platform.h" // for mbedtls_setbuf
60 #include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
61 
62 #include <psa/crypto.h>
63 
64 /* If the build options we need are not enabled, compile a placeholder. */
65 #if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) ||      \
66     !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) ||        \
67     !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO) || \
68     defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
main(void)69 int main(void)
70 {
71     printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
72            "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
73            "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
74            "not defined and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER "
75            "defined.\n");
76     return 0;
77 }
78 #else
79 
80 /* The real program starts here. */
81 
82 /* Run a system function and bail out if it fails. */
83 #define SYS_CHECK(expr)                                       \
84     do                                                          \
85     {                                                           \
86         if (!(expr))                                        \
87         {                                                       \
88             perror( #expr);                                    \
89             status = DEMO_ERROR;                                \
90             goto exit;                                          \
91         }                                                       \
92     }                                                           \
93     while (0)
94 
95 /* Run a PSA function and bail out if it fails. */
96 #define PSA_CHECK(expr)                                       \
97     do                                                          \
98     {                                                           \
99         status = (expr);                                      \
100         if (status != PSA_SUCCESS)                             \
101         {                                                       \
102             printf("Error %d at line %d: %s\n",                \
103                    (int) status,                               \
104                    __LINE__,                                   \
105                    #expr);                                    \
106             goto exit;                                          \
107         }                                                       \
108     }                                                           \
109     while (0)
110 
111 /* To report operational errors in this program, use an error code that is
112  * different from every PSA error code. */
113 #define DEMO_ERROR 120
114 
115 /* The maximum supported key ladder depth. */
116 #define MAX_LADDER_DEPTH 10
117 
118 /* Salt to use when deriving an intermediate key. */
119 #define DERIVE_KEY_SALT ((uint8_t *) "key_ladder_demo.derive")
120 #define DERIVE_KEY_SALT_LENGTH (strlen((const char *) DERIVE_KEY_SALT))
121 
122 /* Salt to use when deriving a wrapping key. */
123 #define WRAPPING_KEY_SALT ((uint8_t *) "key_ladder_demo.wrap")
124 #define WRAPPING_KEY_SALT_LENGTH (strlen((const char *) WRAPPING_KEY_SALT))
125 
126 /* Size of the key derivation keys (applies both to the master key and
127  * to intermediate keys). */
128 #define KEY_SIZE_BYTES 40
129 
130 /* Algorithm for key derivation. */
131 #define KDF_ALG PSA_ALG_HKDF(PSA_ALG_SHA_256)
132 
133 /* Type and size of the key used to wrap data. */
134 #define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
135 #define WRAPPING_KEY_BITS 128
136 
137 /* Cipher mode used to wrap data. */
138 #define WRAPPING_ALG PSA_ALG_CCM
139 
140 /* Nonce size used to wrap data. */
141 #define WRAPPING_IV_SIZE 13
142 
143 /* Header used in files containing wrapped data. We'll save this header
144  * directly without worrying about data representation issues such as
145  * integer sizes and endianness, because the data is meant to be read
146  * back by the same program on the same machine. */
147 #define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
148 #define WRAPPED_DATA_MAGIC_LENGTH (sizeof(WRAPPED_DATA_MAGIC))
149 typedef struct {
150     char magic[WRAPPED_DATA_MAGIC_LENGTH];
151     size_t ad_size; /* Size of the additional data, which is this header. */
152     size_t payload_size; /* Size of the encrypted data. */
153     /* Store the IV inside the additional data. It's convenient. */
154     uint8_t iv[WRAPPING_IV_SIZE];
155 } wrapped_data_header_t;
156 
157 /* The modes that this program can operate in (see usage). */
158 enum program_mode {
159     MODE_GENERATE,
160     MODE_SAVE,
161     MODE_UNWRAP,
162     MODE_WRAP
163 };
164 
165 /* Save a key to a file. In the real world, you may want to export a derived
166  * key sometimes, to share it with another party. */
save_key(psa_key_id_t key,const char * output_file_name)167 static psa_status_t save_key(psa_key_id_t key,
168                              const char *output_file_name)
169 {
170     psa_status_t status = PSA_SUCCESS;
171     uint8_t key_data[KEY_SIZE_BYTES];
172     size_t key_size;
173     FILE *key_file = NULL;
174 
175     PSA_CHECK(psa_export_key(key,
176                              key_data, sizeof(key_data),
177                              &key_size));
178     SYS_CHECK((key_file = fopen(output_file_name, "wb")) != NULL);
179     /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
180     mbedtls_setbuf(key_file, NULL);
181     SYS_CHECK(fwrite(key_data, 1, key_size, key_file) == key_size);
182     SYS_CHECK(fclose(key_file) == 0);
183     key_file = NULL;
184 
185 exit:
186     if (key_file != NULL) {
187         fclose(key_file);
188     }
189     return status;
190 }
191 
192 /* Generate a master key for use in this demo.
193  *
194  * Normally a master key would be non-exportable. For the purpose of this
195  * demo, we want to save it to a file, to avoid relying on the keystore
196  * capability of the PSA crypto library. */
generate(const char * key_file_name)197 static psa_status_t generate(const char *key_file_name)
198 {
199     psa_status_t status = PSA_SUCCESS;
200     psa_key_id_t key = 0;
201     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
202 
203     psa_set_key_usage_flags(&attributes,
204                             PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
205     psa_set_key_algorithm(&attributes, KDF_ALG);
206     psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
207     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(KEY_SIZE_BYTES));
208 
209     PSA_CHECK(psa_generate_key(&attributes, &key));
210 
211     PSA_CHECK(save_key(key, key_file_name));
212 
213 exit:
214     (void) psa_destroy_key(key);
215     return status;
216 }
217 
218 /* Load the master key from a file.
219  *
220  * In the real world, this master key would be stored in an internal memory
221  * and the storage would be managed by the keystore capability of the PSA
222  * crypto library. */
import_key_from_file(psa_key_usage_t usage,psa_algorithm_t alg,const char * key_file_name,psa_key_id_t * master_key)223 static psa_status_t import_key_from_file(psa_key_usage_t usage,
224                                          psa_algorithm_t alg,
225                                          const char *key_file_name,
226                                          psa_key_id_t *master_key)
227 {
228     psa_status_t status = PSA_SUCCESS;
229     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
230     uint8_t key_data[KEY_SIZE_BYTES];
231     size_t key_size;
232     FILE *key_file = NULL;
233     unsigned char extra_byte;
234 
235     SYS_CHECK((key_file = fopen(key_file_name, "rb")) != NULL);
236     /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
237     mbedtls_setbuf(key_file, NULL);
238     SYS_CHECK((key_size = fread(key_data, 1, sizeof(key_data),
239                                 key_file)) != 0);
240     if (fread(&extra_byte, 1, 1, key_file) != 0) {
241         printf("Key file too large (max: %u).\n",
242                (unsigned) sizeof(key_data));
243         status = DEMO_ERROR;
244         goto exit;
245     }
246     SYS_CHECK(fclose(key_file) == 0);
247     key_file = NULL;
248 
249     psa_set_key_usage_flags(&attributes, usage);
250     psa_set_key_algorithm(&attributes, alg);
251     psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
252     PSA_CHECK(psa_import_key(&attributes, key_data, key_size, master_key));
253 exit:
254     if (key_file != NULL) {
255         fclose(key_file);
256     }
257     mbedtls_platform_zeroize(key_data, sizeof(key_data));
258     if (status != PSA_SUCCESS) {
259         /* If the key creation hasn't happened yet or has failed,
260          * *master_key is null. psa_destroy_key( 0 ) is
261          * guaranteed to do nothing and return PSA_SUCCESS. */
262         (void) psa_destroy_key(*master_key);
263         *master_key = 0;
264     }
265     return status;
266 }
267 
268 /* Derive the intermediate keys, using the list of labels provided on
269  * the command line. On input, *key is the master key identifier.
270  * This function destroys the master key. On successful output, *key
271  * is the identifier of the final derived key.
272  */
derive_key_ladder(const char * ladder[],size_t ladder_depth,psa_key_id_t * key)273 static psa_status_t derive_key_ladder(const char *ladder[],
274                                       size_t ladder_depth,
275                                       psa_key_id_t *key)
276 {
277     psa_status_t status = PSA_SUCCESS;
278     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
279     psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
280     size_t i;
281 
282     psa_set_key_usage_flags(&attributes,
283                             PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
284     psa_set_key_algorithm(&attributes, KDF_ALG);
285     psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
286     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(KEY_SIZE_BYTES));
287 
288     /* For each label in turn, ... */
289     for (i = 0; i < ladder_depth; i++) {
290         /* Start deriving material from the master key (if i=0) or from
291          * the current intermediate key (if i>0). */
292         PSA_CHECK(psa_key_derivation_setup(&operation, KDF_ALG));
293         PSA_CHECK(psa_key_derivation_input_bytes(
294                       &operation, PSA_KEY_DERIVATION_INPUT_SALT,
295                       DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH));
296         PSA_CHECK(psa_key_derivation_input_key(
297                       &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
298                       *key));
299         PSA_CHECK(psa_key_derivation_input_bytes(
300                       &operation, PSA_KEY_DERIVATION_INPUT_INFO,
301                       (uint8_t *) ladder[i], strlen(ladder[i])));
302         /* When the parent key is not the master key, destroy it,
303          * since it is no longer needed. */
304         PSA_CHECK(psa_destroy_key(*key));
305         *key = 0;
306         /* Derive the next intermediate key from the parent key. */
307         PSA_CHECK(psa_key_derivation_output_key(&attributes, &operation,
308                                                 key));
309         PSA_CHECK(psa_key_derivation_abort(&operation));
310     }
311 
312 exit:
313     psa_key_derivation_abort(&operation);
314     if (status != PSA_SUCCESS) {
315         psa_destroy_key(*key);
316         *key = 0;
317     }
318     return status;
319 }
320 
321 /* Derive a wrapping key from the last intermediate key. */
derive_wrapping_key(psa_key_usage_t usage,psa_key_id_t derived_key,psa_key_id_t * wrapping_key)322 static psa_status_t derive_wrapping_key(psa_key_usage_t usage,
323                                         psa_key_id_t derived_key,
324                                         psa_key_id_t *wrapping_key)
325 {
326     psa_status_t status = PSA_SUCCESS;
327     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
328     psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
329 
330     *wrapping_key = 0;
331 
332     /* Set up a key derivation operation from the key derived from
333      * the master key. */
334     PSA_CHECK(psa_key_derivation_setup(&operation, KDF_ALG));
335     PSA_CHECK(psa_key_derivation_input_bytes(
336                   &operation, PSA_KEY_DERIVATION_INPUT_SALT,
337                   WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH));
338     PSA_CHECK(psa_key_derivation_input_key(
339                   &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
340                   derived_key));
341     PSA_CHECK(psa_key_derivation_input_bytes(
342                   &operation, PSA_KEY_DERIVATION_INPUT_INFO,
343                   NULL, 0));
344 
345     /* Create the wrapping key. */
346     psa_set_key_usage_flags(&attributes, usage);
347     psa_set_key_algorithm(&attributes, WRAPPING_ALG);
348     psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
349     psa_set_key_bits(&attributes, WRAPPING_KEY_BITS);
350     PSA_CHECK(psa_key_derivation_output_key(&attributes, &operation,
351                                             wrapping_key));
352 
353 exit:
354     psa_key_derivation_abort(&operation);
355     return status;
356 }
357 
wrap_data(const char * input_file_name,const char * output_file_name,psa_key_id_t wrapping_key)358 static psa_status_t wrap_data(const char *input_file_name,
359                               const char *output_file_name,
360                               psa_key_id_t wrapping_key)
361 {
362     psa_status_t status;
363     FILE *input_file = NULL;
364     FILE *output_file = NULL;
365     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
366     psa_key_type_t key_type;
367     long input_position;
368     size_t input_size;
369     size_t buffer_size = 0;
370     unsigned char *buffer = NULL;
371     size_t ciphertext_size;
372     wrapped_data_header_t header;
373 
374     /* Find the size of the data to wrap. */
375     SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
376     /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
377     mbedtls_setbuf(input_file, NULL);
378     SYS_CHECK(fseek(input_file, 0, SEEK_END) == 0);
379     SYS_CHECK((input_position = ftell(input_file)) != -1);
380 #if LONG_MAX > SIZE_MAX
381     if (input_position > SIZE_MAX) {
382         printf("Input file too large.\n");
383         status = DEMO_ERROR;
384         goto exit;
385     }
386 #endif
387     input_size = input_position;
388     PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
389     key_type = psa_get_key_type(&attributes);
390     buffer_size =
391         PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, input_size);
392     /* Check for integer overflow. */
393     if (buffer_size < input_size) {
394         printf("Input file too large.\n");
395         status = DEMO_ERROR;
396         goto exit;
397     }
398 
399     /* Load the data to wrap. */
400     SYS_CHECK(fseek(input_file, 0, SEEK_SET) == 0);
401     SYS_CHECK((buffer = calloc(1, buffer_size)) != NULL);
402     SYS_CHECK(fread(buffer, 1, input_size, input_file) == input_size);
403     SYS_CHECK(fclose(input_file) == 0);
404     input_file = NULL;
405 
406     /* Construct a header. */
407     memcpy(&header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH);
408     header.ad_size = sizeof(header);
409     header.payload_size = input_size;
410 
411     /* Wrap the data. */
412     PSA_CHECK(psa_generate_random(header.iv, WRAPPING_IV_SIZE));
413     PSA_CHECK(psa_aead_encrypt(wrapping_key, WRAPPING_ALG,
414                                header.iv, WRAPPING_IV_SIZE,
415                                (uint8_t *) &header, sizeof(header),
416                                buffer, input_size,
417                                buffer, buffer_size,
418                                &ciphertext_size));
419 
420     /* Write the output. */
421     SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
422     /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
423     mbedtls_setbuf(output_file, NULL);
424     SYS_CHECK(fwrite(&header, 1, sizeof(header),
425                      output_file) == sizeof(header));
426     SYS_CHECK(fwrite(buffer, 1, ciphertext_size,
427                      output_file) == ciphertext_size);
428     SYS_CHECK(fclose(output_file) == 0);
429     output_file = NULL;
430 
431 exit:
432     if (input_file != NULL) {
433         fclose(input_file);
434     }
435     if (output_file != NULL) {
436         fclose(output_file);
437     }
438     if (buffer != NULL) {
439         mbedtls_platform_zeroize(buffer, buffer_size);
440     }
441     free(buffer);
442     return status;
443 }
444 
unwrap_data(const char * input_file_name,const char * output_file_name,psa_key_id_t wrapping_key)445 static psa_status_t unwrap_data(const char *input_file_name,
446                                 const char *output_file_name,
447                                 psa_key_id_t wrapping_key)
448 {
449     psa_status_t status;
450     FILE *input_file = NULL;
451     FILE *output_file = NULL;
452     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
453     psa_key_type_t key_type;
454     unsigned char *buffer = NULL;
455     size_t ciphertext_size = 0;
456     size_t plaintext_size;
457     wrapped_data_header_t header;
458     unsigned char extra_byte;
459 
460     /* Load and validate the header. */
461     SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
462     /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
463     mbedtls_setbuf(input_file, NULL);
464     SYS_CHECK(fread(&header, 1, sizeof(header),
465                     input_file) == sizeof(header));
466     if (memcmp(&header.magic, WRAPPED_DATA_MAGIC,
467                WRAPPED_DATA_MAGIC_LENGTH) != 0) {
468         printf("The input does not start with a valid magic header.\n");
469         status = DEMO_ERROR;
470         goto exit;
471     }
472     if (header.ad_size != sizeof(header)) {
473         printf("The header size is not correct.\n");
474         status = DEMO_ERROR;
475         goto exit;
476     }
477     PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
478     key_type = psa_get_key_type(&attributes);
479     ciphertext_size =
480         PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, header.payload_size);
481     /* Check for integer overflow. */
482     if (ciphertext_size < header.payload_size) {
483         printf("Input file too large.\n");
484         status = DEMO_ERROR;
485         goto exit;
486     }
487 
488     /* Load the payload data. */
489     SYS_CHECK((buffer = calloc(1, ciphertext_size)) != NULL);
490     SYS_CHECK(fread(buffer, 1, ciphertext_size,
491                     input_file) == ciphertext_size);
492     if (fread(&extra_byte, 1, 1, input_file) != 0) {
493         printf("Extra garbage after ciphertext\n");
494         status = DEMO_ERROR;
495         goto exit;
496     }
497     SYS_CHECK(fclose(input_file) == 0);
498     input_file = NULL;
499 
500     /* Unwrap the data. */
501     PSA_CHECK(psa_aead_decrypt(wrapping_key, WRAPPING_ALG,
502                                header.iv, WRAPPING_IV_SIZE,
503                                (uint8_t *) &header, sizeof(header),
504                                buffer, ciphertext_size,
505                                buffer, ciphertext_size,
506                                &plaintext_size));
507     if (plaintext_size != header.payload_size) {
508         printf("Incorrect payload size in the header.\n");
509         status = DEMO_ERROR;
510         goto exit;
511     }
512 
513     /* Write the output. */
514     SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
515     /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
516     mbedtls_setbuf(output_file, NULL);
517     SYS_CHECK(fwrite(buffer, 1, plaintext_size,
518                      output_file) == plaintext_size);
519     SYS_CHECK(fclose(output_file) == 0);
520     output_file = NULL;
521 
522 exit:
523     if (input_file != NULL) {
524         fclose(input_file);
525     }
526     if (output_file != NULL) {
527         fclose(output_file);
528     }
529     if (buffer != NULL) {
530         mbedtls_platform_zeroize(buffer, ciphertext_size);
531     }
532     free(buffer);
533     return status;
534 }
535 
run(enum program_mode mode,const char * key_file_name,const char * ladder[],size_t ladder_depth,const char * input_file_name,const char * output_file_name)536 static psa_status_t run(enum program_mode mode,
537                         const char *key_file_name,
538                         const char *ladder[], size_t ladder_depth,
539                         const char *input_file_name,
540                         const char *output_file_name)
541 {
542     psa_status_t status = PSA_SUCCESS;
543     psa_key_id_t derivation_key = 0;
544     psa_key_id_t wrapping_key = 0;
545 
546     /* Initialize the PSA crypto library. */
547     PSA_CHECK(psa_crypto_init());
548 
549     /* Generate mode is unlike the others. Generate the master key and exit. */
550     if (mode == MODE_GENERATE) {
551         return generate(key_file_name);
552     }
553 
554     /* Read the master key. */
555     PSA_CHECK(import_key_from_file(PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
556                                    KDF_ALG,
557                                    key_file_name,
558                                    &derivation_key));
559 
560     /* Calculate the derived key for this session. */
561     PSA_CHECK(derive_key_ladder(ladder, ladder_depth,
562                                 &derivation_key));
563 
564     switch (mode) {
565         case MODE_SAVE:
566             PSA_CHECK(save_key(derivation_key, output_file_name));
567             break;
568         case MODE_UNWRAP:
569             PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_DECRYPT,
570                                           derivation_key,
571                                           &wrapping_key));
572             PSA_CHECK(unwrap_data(input_file_name, output_file_name,
573                                   wrapping_key));
574             break;
575         case MODE_WRAP:
576             PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_ENCRYPT,
577                                           derivation_key,
578                                           &wrapping_key));
579             PSA_CHECK(wrap_data(input_file_name, output_file_name,
580                                 wrapping_key));
581             break;
582         default:
583             /* Unreachable but some compilers don't realize it. */
584             break;
585     }
586 
587 exit:
588     /* Destroy any remaining key. Deinitializing the crypto library would do
589      * this anyway since they are volatile keys, but explicitly destroying
590      * keys makes the code easier to reuse. */
591     (void) psa_destroy_key(derivation_key);
592     (void) psa_destroy_key(wrapping_key);
593     /* Deinitialize the PSA crypto library. */
594     mbedtls_psa_crypto_free();
595     return status;
596 }
597 
usage(void)598 static void usage(void)
599 {
600     printf("Usage: key_ladder_demo MODE [OPTION=VALUE]...\n");
601     printf("Demonstrate the usage of a key derivation ladder.\n");
602     printf("\n");
603     printf("Modes:\n");
604     printf("  generate  Generate the master key\n");
605     printf("  save      Save the derived key\n");
606     printf("  unwrap    Unwrap (decrypt) input with the derived key\n");
607     printf("  wrap      Wrap (encrypt) input with the derived key\n");
608     printf("\n");
609     printf("Options:\n");
610     printf("  input=FILENAME    Input file (required for wrap/unwrap)\n");
611     printf("  master=FILENAME   File containing the master key (default: master.key)\n");
612     printf("  output=FILENAME   Output file (required for save/wrap/unwrap)\n");
613     printf("  label=TEXT        Label for the key derivation.\n");
614     printf("                    This may be repeated multiple times.\n");
615     printf("                    To get the same key, you must use the same master key\n");
616     printf("                    and the same sequence of labels.\n");
617 }
618 
main(int argc,char * argv[])619 int main(int argc, char *argv[])
620 {
621     const char *key_file_name = "master.key";
622     const char *input_file_name = NULL;
623     const char *output_file_name = NULL;
624     const char *ladder[MAX_LADDER_DEPTH];
625     size_t ladder_depth = 0;
626     int i;
627     enum program_mode mode;
628     psa_status_t status;
629 
630     if (argc <= 1 ||
631         strcmp(argv[1], "help") == 0 ||
632         strcmp(argv[1], "-help") == 0 ||
633         strcmp(argv[1], "--help") == 0) {
634         usage();
635         return EXIT_SUCCESS;
636     }
637 
638     for (i = 2; i < argc; i++) {
639         char *q = strchr(argv[i], '=');
640         if (q == NULL) {
641             printf("Missing argument to option %s\n", argv[i]);
642             goto usage_failure;
643         }
644         *q = 0;
645         ++q;
646         if (strcmp(argv[i], "input") == 0) {
647             input_file_name = q;
648         } else if (strcmp(argv[i], "label") == 0) {
649             if (ladder_depth == MAX_LADDER_DEPTH) {
650                 printf("Maximum ladder depth %u exceeded.\n",
651                        (unsigned) MAX_LADDER_DEPTH);
652                 return EXIT_FAILURE;
653             }
654             ladder[ladder_depth] = q;
655             ++ladder_depth;
656         } else if (strcmp(argv[i], "master") == 0) {
657             key_file_name = q;
658         } else if (strcmp(argv[i], "output") == 0) {
659             output_file_name = q;
660         } else {
661             printf("Unknown option: %s\n", argv[i]);
662             goto usage_failure;
663         }
664     }
665 
666     if (strcmp(argv[1], "generate") == 0) {
667         mode = MODE_GENERATE;
668     } else if (strcmp(argv[1], "save") == 0) {
669         mode = MODE_SAVE;
670     } else if (strcmp(argv[1], "unwrap") == 0) {
671         mode = MODE_UNWRAP;
672     } else if (strcmp(argv[1], "wrap") == 0) {
673         mode = MODE_WRAP;
674     } else {
675         printf("Unknown action: %s\n", argv[1]);
676         goto usage_failure;
677     }
678 
679     if (input_file_name == NULL &&
680         (mode == MODE_WRAP || mode == MODE_UNWRAP)) {
681         printf("Required argument missing: input\n");
682         return DEMO_ERROR;
683     }
684     if (output_file_name == NULL &&
685         (mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP)) {
686         printf("Required argument missing: output\n");
687         return DEMO_ERROR;
688     }
689 
690     status = run(mode, key_file_name,
691                  ladder, ladder_depth,
692                  input_file_name, output_file_name);
693     return status == PSA_SUCCESS ?
694            EXIT_SUCCESS :
695            EXIT_FAILURE;
696 
697 usage_failure:
698     usage();
699     return EXIT_FAILURE;
700 }
701 #endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C &&
702           MBEDTLS_AES_C && MBEDTLS_CCM_C &&
703           MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */
704