blob: 2734ceb7fb21695df992004f195ff50ea0b7ad2d [file] [log] [blame]
Gilles Peskinef0fa4362018-07-16 17:08:43 +02001/**
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
Bence Szépkúti86974652020-06-15 11:59:37 +020033/*
Bence Szépkúti1e148272020-08-07 13:07:28 +020034 * Copyright The Mbed TLS Contributors
Dave Rodgman16799db2023-11-02 19:47:20 +000035 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskinef0fa4362018-07-16 17:08:43 +020036 */
37
38/* First include Mbed TLS headers to get the Mbed TLS configuration and
39 * platform definitions that we'll use in this program. Also include
40 * standard C headers for functions we'll use here. */
Bence Szépkútic662b362021-05-27 11:25:03 +020041#include "mbedtls/build_info.h"
Gilles Peskinef0fa4362018-07-16 17:08:43 +020042
Gilles Peskinef0fa4362018-07-16 17:08:43 +020043#include <stdlib.h>
Gilles Peskinef0fa4362018-07-16 17:08:43 +020044#include <stdio.h>
45#include <string.h>
46
Gilles Peskine6d576c92022-06-30 17:06:11 +020047#include "mbedtls/platform.h" // for mbedtls_setbuf
Gilles Peskinef0fa4362018-07-16 17:08:43 +020048#include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
49
Gilles Peskine4e2cc532019-05-29 14:30:27 +020050#include <psa/crypto.h>
51
Gilles Peskinef0fa4362018-07-16 17:08:43 +020052/* If the build options we need are not enabled, compile a placeholder. */
Manuel Pégourié-Gonnard33783b42023-03-21 17:24:20 +010053#if !defined(PSA_WANT_ALG_SHA_256) || !defined(MBEDTLS_MD_C) || \
Ronald Cronadc2ff22020-09-16 16:49:27 +020054 !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
55 !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO) || \
56 defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
Gilles Peskine449bd832023-01-11 14:50:10 +010057int main(void)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020058{
Manuel Pégourié-Gonnard33783b42023-03-21 17:24:20 +010059 printf("PSA_WANT_ALG_SHA_256 and/or MBEDTLS_MD_C and/or "
Gilles Peskine449bd832023-01-11 14:50:10 +010060 "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
61 "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
62 "not defined and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER "
63 "defined.\n");
64 return 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +020065}
66#else
67
68/* The real program starts here. */
69
Gilles Peskinef0fa4362018-07-16 17:08:43 +020070/* Run a system function and bail out if it fails. */
Gilles Peskine449bd832023-01-11 14:50:10 +010071#define SYS_CHECK(expr) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020072 do \
73 { \
Gilles Peskine449bd832023-01-11 14:50:10 +010074 if (!(expr)) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020075 { \
Gilles Peskine449bd832023-01-11 14:50:10 +010076 perror( #expr); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020077 status = DEMO_ERROR; \
78 goto exit; \
79 } \
80 } \
Gilles Peskine449bd832023-01-11 14:50:10 +010081 while (0)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020082
83/* Run a PSA function and bail out if it fails. */
Gilles Peskine449bd832023-01-11 14:50:10 +010084#define PSA_CHECK(expr) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020085 do \
86 { \
Gilles Peskine449bd832023-01-11 14:50:10 +010087 status = (expr); \
88 if (status != PSA_SUCCESS) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020089 { \
Gilles Peskine449bd832023-01-11 14:50:10 +010090 printf("Error %d at line %d: %s\n", \
91 (int) status, \
92 __LINE__, \
93 #expr); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020094 goto exit; \
95 } \
96 } \
Gilles Peskine449bd832023-01-11 14:50:10 +010097 while (0)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020098
99/* To report operational errors in this program, use an error code that is
100 * different from every PSA error code. */
101#define DEMO_ERROR 120
102
103/* The maximum supported key ladder depth. */
104#define MAX_LADDER_DEPTH 10
105
106/* Salt to use when deriving an intermediate key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100107#define DERIVE_KEY_SALT ((uint8_t *) "key_ladder_demo.derive")
108#define DERIVE_KEY_SALT_LENGTH (strlen((const char *) DERIVE_KEY_SALT))
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200109
110/* Salt to use when deriving a wrapping key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100111#define WRAPPING_KEY_SALT ((uint8_t *) "key_ladder_demo.wrap")
112#define WRAPPING_KEY_SALT_LENGTH (strlen((const char *) WRAPPING_KEY_SALT))
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200113
114/* Size of the key derivation keys (applies both to the master key and
115 * to intermediate keys). */
116#define KEY_SIZE_BYTES 40
117
118/* Algorithm for key derivation. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100119#define KDF_ALG PSA_ALG_HKDF(PSA_ALG_SHA_256)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200120
121/* Type and size of the key used to wrap data. */
122#define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
123#define WRAPPING_KEY_BITS 128
124
125/* Cipher mode used to wrap data. */
126#define WRAPPING_ALG PSA_ALG_CCM
127
128/* Nonce size used to wrap data. */
129#define WRAPPING_IV_SIZE 13
130
131/* Header used in files containing wrapped data. We'll save this header
132 * directly without worrying about data representation issues such as
133 * integer sizes and endianness, because the data is meant to be read
134 * back by the same program on the same machine. */
135#define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
Gilles Peskine449bd832023-01-11 14:50:10 +0100136#define WRAPPED_DATA_MAGIC_LENGTH (sizeof(WRAPPED_DATA_MAGIC))
137typedef struct {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200138 char magic[WRAPPED_DATA_MAGIC_LENGTH];
139 size_t ad_size; /* Size of the additional data, which is this header. */
140 size_t payload_size; /* Size of the encrypted data. */
141 /* Store the IV inside the additional data. It's convenient. */
142 uint8_t iv[WRAPPING_IV_SIZE];
143} wrapped_data_header_t;
144
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200145/* The modes that this program can operate in (see usage). */
Gilles Peskine449bd832023-01-11 14:50:10 +0100146enum program_mode {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200147 MODE_GENERATE,
148 MODE_SAVE,
149 MODE_UNWRAP,
150 MODE_WRAP
151};
152
153/* Save a key to a file. In the real world, you may want to export a derived
154 * key sometimes, to share it with another party. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100155static psa_status_t save_key(psa_key_id_t key,
156 const char *output_file_name)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200157{
158 psa_status_t status = PSA_SUCCESS;
159 uint8_t key_data[KEY_SIZE_BYTES];
160 size_t key_size;
161 FILE *key_file = NULL;
162
Gilles Peskine449bd832023-01-11 14:50:10 +0100163 PSA_CHECK(psa_export_key(key,
164 key_data, sizeof(key_data),
165 &key_size));
166 SYS_CHECK((key_file = fopen(output_file_name, "wb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200167 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100168 mbedtls_setbuf(key_file, NULL);
169 SYS_CHECK(fwrite(key_data, 1, key_size, key_file) == key_size);
170 SYS_CHECK(fclose(key_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200171 key_file = NULL;
172
173exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100174 if (key_file != NULL) {
175 fclose(key_file);
176 }
177 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200178}
179
180/* Generate a master key for use in this demo.
181 *
182 * Normally a master key would be non-exportable. For the purpose of this
183 * demo, we want to save it to a file, to avoid relying on the keystore
184 * capability of the PSA crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100185static psa_status_t generate(const char *key_file_name)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200186{
187 psa_status_t status = PSA_SUCCESS;
Ronald Cronadc2ff22020-09-16 16:49:27 +0200188 psa_key_id_t key = 0;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200189 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200190
Gilles Peskine449bd832023-01-11 14:50:10 +0100191 psa_set_key_usage_flags(&attributes,
192 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
193 psa_set_key_algorithm(&attributes, KDF_ALG);
194 psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
195 psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(KEY_SIZE_BYTES));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200196
Gilles Peskine449bd832023-01-11 14:50:10 +0100197 PSA_CHECK(psa_generate_key(&attributes, &key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200198
Gilles Peskine449bd832023-01-11 14:50:10 +0100199 PSA_CHECK(save_key(key, key_file_name));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200200
201exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100202 (void) psa_destroy_key(key);
203 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200204}
205
206/* Load the master key from a file.
207 *
208 * In the real world, this master key would be stored in an internal memory
209 * and the storage would be managed by the keystore capability of the PSA
210 * crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100211static psa_status_t import_key_from_file(psa_key_usage_t usage,
212 psa_algorithm_t alg,
213 const char *key_file_name,
214 psa_key_id_t *master_key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200215{
216 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200217 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200218 uint8_t key_data[KEY_SIZE_BYTES];
219 size_t key_size;
220 FILE *key_file = NULL;
221 unsigned char extra_byte;
222
Gilles Peskine449bd832023-01-11 14:50:10 +0100223 SYS_CHECK((key_file = fopen(key_file_name, "rb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200224 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100225 mbedtls_setbuf(key_file, NULL);
226 SYS_CHECK((key_size = fread(key_data, 1, sizeof(key_data),
227 key_file)) != 0);
228 if (fread(&extra_byte, 1, 1, key_file) != 0) {
229 printf("Key file too large (max: %u).\n",
230 (unsigned) sizeof(key_data));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200231 status = DEMO_ERROR;
232 goto exit;
233 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100234 SYS_CHECK(fclose(key_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200235 key_file = NULL;
236
Gilles Peskine449bd832023-01-11 14:50:10 +0100237 psa_set_key_usage_flags(&attributes, usage);
238 psa_set_key_algorithm(&attributes, alg);
239 psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
240 PSA_CHECK(psa_import_key(&attributes, key_data, key_size, master_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200241exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100242 if (key_file != NULL) {
243 fclose(key_file);
244 }
245 mbedtls_platform_zeroize(key_data, sizeof(key_data));
246 if (status != PSA_SUCCESS) {
Gilles Peskine5163a922019-05-27 14:52:34 +0200247 /* If the key creation hasn't happened yet or has failed,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200248 * *master_key is null. psa_destroy_key( 0 ) is
249 * guaranteed to do nothing and return PSA_SUCCESS. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100250 (void) psa_destroy_key(*master_key);
Ronald Cronadc2ff22020-09-16 16:49:27 +0200251 *master_key = 0;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100252 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100253 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200254}
255
256/* Derive the intermediate keys, using the list of labels provided on
Ronald Cronadc2ff22020-09-16 16:49:27 +0200257 * the command line. On input, *key is the master key identifier.
258 * This function destroys the master key. On successful output, *key
259 * is the identifier of the final derived key.
260 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100261static psa_status_t derive_key_ladder(const char *ladder[],
262 size_t ladder_depth,
263 psa_key_id_t *key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200264{
265 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200266 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200267 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200268 size_t i;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200269
Gilles Peskine449bd832023-01-11 14:50:10 +0100270 psa_set_key_usage_flags(&attributes,
271 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
272 psa_set_key_algorithm(&attributes, KDF_ALG);
273 psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
274 psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(KEY_SIZE_BYTES));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200275
276 /* For each label in turn, ... */
Gilles Peskine449bd832023-01-11 14:50:10 +0100277 for (i = 0; i < ladder_depth; i++) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200278 /* Start deriving material from the master key (if i=0) or from
279 * the current intermediate key (if i>0). */
Gilles Peskine449bd832023-01-11 14:50:10 +0100280 PSA_CHECK(psa_key_derivation_setup(&operation, KDF_ALG));
281 PSA_CHECK(psa_key_derivation_input_bytes(
282 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
283 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH));
284 PSA_CHECK(psa_key_derivation_input_key(
285 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
286 *key));
287 PSA_CHECK(psa_key_derivation_input_bytes(
288 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
289 (uint8_t *) ladder[i], strlen(ladder[i])));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200290 /* When the parent key is not the master key, destroy it,
291 * since it is no longer needed. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100292 PSA_CHECK(psa_destroy_key(*key));
Ronald Cronadc2ff22020-09-16 16:49:27 +0200293 *key = 0;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200294 /* Derive the next intermediate key from the parent key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100295 PSA_CHECK(psa_key_derivation_output_key(&attributes, &operation,
296 key));
297 PSA_CHECK(psa_key_derivation_abort(&operation));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200298 }
299
300exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100301 psa_key_derivation_abort(&operation);
302 if (status != PSA_SUCCESS) {
303 psa_destroy_key(*key);
Ronald Cronadc2ff22020-09-16 16:49:27 +0200304 *key = 0;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100305 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100306 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200307}
308
309/* Derive a wrapping key from the last intermediate key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100310static psa_status_t derive_wrapping_key(psa_key_usage_t usage,
311 psa_key_id_t derived_key,
312 psa_key_id_t *wrapping_key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200313{
314 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200315 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200316 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200317
Ronald Cronadc2ff22020-09-16 16:49:27 +0200318 *wrapping_key = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200319
Gilles Peskine2a38e242019-05-29 14:33:00 +0200320 /* Set up a key derivation operation from the key derived from
321 * the master key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100322 PSA_CHECK(psa_key_derivation_setup(&operation, KDF_ALG));
323 PSA_CHECK(psa_key_derivation_input_bytes(
324 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
325 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH));
326 PSA_CHECK(psa_key_derivation_input_key(
327 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
328 derived_key));
329 PSA_CHECK(psa_key_derivation_input_bytes(
330 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
331 NULL, 0));
Gilles Peskine2a38e242019-05-29 14:33:00 +0200332
333 /* Create the wrapping key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100334 psa_set_key_usage_flags(&attributes, usage);
335 psa_set_key_algorithm(&attributes, WRAPPING_ALG);
336 psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
337 psa_set_key_bits(&attributes, WRAPPING_KEY_BITS);
338 PSA_CHECK(psa_key_derivation_output_key(&attributes, &operation,
339 wrapping_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200340
341exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100342 psa_key_derivation_abort(&operation);
343 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200344}
345
Gilles Peskine449bd832023-01-11 14:50:10 +0100346static psa_status_t wrap_data(const char *input_file_name,
347 const char *output_file_name,
348 psa_key_id_t wrapping_key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200349{
350 psa_status_t status;
351 FILE *input_file = NULL;
352 FILE *output_file = NULL;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100353 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
354 psa_key_type_t key_type;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200355 long input_position;
356 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100357 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200358 unsigned char *buffer = NULL;
359 size_t ciphertext_size;
360 wrapped_data_header_t header;
361
362 /* Find the size of the data to wrap. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100363 SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200364 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100365 mbedtls_setbuf(input_file, NULL);
366 SYS_CHECK(fseek(input_file, 0, SEEK_END) == 0);
367 SYS_CHECK((input_position = ftell(input_file)) != -1);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200368#if LONG_MAX > SIZE_MAX
Gilles Peskine449bd832023-01-11 14:50:10 +0100369 if (input_position > SIZE_MAX) {
370 printf("Input file too large.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200371 status = DEMO_ERROR;
372 goto exit;
373 }
374#endif
375 input_size = input_position;
Gilles Peskine449bd832023-01-11 14:50:10 +0100376 PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
377 key_type = psa_get_key_type(&attributes);
Bence Szépkútiec174e22021-03-19 18:46:15 +0100378 buffer_size =
Gilles Peskine449bd832023-01-11 14:50:10 +0100379 PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, input_size);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200380 /* Check for integer overflow. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100381 if (buffer_size < input_size) {
382 printf("Input file too large.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200383 status = DEMO_ERROR;
384 goto exit;
385 }
386
387 /* Load the data to wrap. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100388 SYS_CHECK(fseek(input_file, 0, SEEK_SET) == 0);
389 SYS_CHECK((buffer = calloc(1, buffer_size)) != NULL);
390 SYS_CHECK(fread(buffer, 1, input_size, input_file) == input_size);
391 SYS_CHECK(fclose(input_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200392 input_file = NULL;
393
394 /* Construct a header. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100395 memcpy(&header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH);
396 header.ad_size = sizeof(header);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200397 header.payload_size = input_size;
398
399 /* Wrap the data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100400 PSA_CHECK(psa_generate_random(header.iv, WRAPPING_IV_SIZE));
401 PSA_CHECK(psa_aead_encrypt(wrapping_key, WRAPPING_ALG,
402 header.iv, WRAPPING_IV_SIZE,
403 (uint8_t *) &header, sizeof(header),
404 buffer, input_size,
405 buffer, buffer_size,
406 &ciphertext_size));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200407
408 /* Write the output. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100409 SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200410 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100411 mbedtls_setbuf(output_file, NULL);
412 SYS_CHECK(fwrite(&header, 1, sizeof(header),
413 output_file) == sizeof(header));
414 SYS_CHECK(fwrite(buffer, 1, ciphertext_size,
415 output_file) == ciphertext_size);
416 SYS_CHECK(fclose(output_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200417 output_file = NULL;
418
419exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100420 if (input_file != NULL) {
421 fclose(input_file);
422 }
423 if (output_file != NULL) {
424 fclose(output_file);
425 }
426 if (buffer != NULL) {
427 mbedtls_platform_zeroize(buffer, buffer_size);
428 }
429 free(buffer);
430 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200431}
432
Gilles Peskine449bd832023-01-11 14:50:10 +0100433static psa_status_t unwrap_data(const char *input_file_name,
434 const char *output_file_name,
435 psa_key_id_t wrapping_key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200436{
437 psa_status_t status;
438 FILE *input_file = NULL;
439 FILE *output_file = NULL;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100440 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
441 psa_key_type_t key_type;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200442 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100443 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200444 size_t plaintext_size;
445 wrapped_data_header_t header;
446 unsigned char extra_byte;
447
448 /* Load and validate the header. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100449 SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200450 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100451 mbedtls_setbuf(input_file, NULL);
452 SYS_CHECK(fread(&header, 1, sizeof(header),
453 input_file) == sizeof(header));
454 if (memcmp(&header.magic, WRAPPED_DATA_MAGIC,
455 WRAPPED_DATA_MAGIC_LENGTH) != 0) {
456 printf("The input does not start with a valid magic header.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200457 status = DEMO_ERROR;
458 goto exit;
459 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100460 if (header.ad_size != sizeof(header)) {
461 printf("The header size is not correct.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200462 status = DEMO_ERROR;
463 goto exit;
464 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100465 PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
466 key_type = psa_get_key_type(&attributes);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200467 ciphertext_size =
Gilles Peskine449bd832023-01-11 14:50:10 +0100468 PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, header.payload_size);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200469 /* Check for integer overflow. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100470 if (ciphertext_size < header.payload_size) {
471 printf("Input file too large.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200472 status = DEMO_ERROR;
473 goto exit;
474 }
475
476 /* Load the payload data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100477 SYS_CHECK((buffer = calloc(1, ciphertext_size)) != NULL);
478 SYS_CHECK(fread(buffer, 1, ciphertext_size,
479 input_file) == ciphertext_size);
480 if (fread(&extra_byte, 1, 1, input_file) != 0) {
481 printf("Extra garbage after ciphertext\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200482 status = DEMO_ERROR;
483 goto exit;
484 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100485 SYS_CHECK(fclose(input_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200486 input_file = NULL;
487
488 /* Unwrap the data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100489 PSA_CHECK(psa_aead_decrypt(wrapping_key, WRAPPING_ALG,
490 header.iv, WRAPPING_IV_SIZE,
491 (uint8_t *) &header, sizeof(header),
492 buffer, ciphertext_size,
493 buffer, ciphertext_size,
494 &plaintext_size));
495 if (plaintext_size != header.payload_size) {
496 printf("Incorrect payload size in the header.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200497 status = DEMO_ERROR;
498 goto exit;
499 }
500
501 /* Write the output. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100502 SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200503 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100504 mbedtls_setbuf(output_file, NULL);
505 SYS_CHECK(fwrite(buffer, 1, plaintext_size,
506 output_file) == plaintext_size);
507 SYS_CHECK(fclose(output_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200508 output_file = NULL;
509
510exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100511 if (input_file != NULL) {
512 fclose(input_file);
513 }
514 if (output_file != NULL) {
515 fclose(output_file);
516 }
517 if (buffer != NULL) {
518 mbedtls_platform_zeroize(buffer, ciphertext_size);
519 }
520 free(buffer);
521 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200522}
523
Gilles Peskine449bd832023-01-11 14:50:10 +0100524static psa_status_t run(enum program_mode mode,
525 const char *key_file_name,
526 const char *ladder[], size_t ladder_depth,
527 const char *input_file_name,
528 const char *output_file_name)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200529{
530 psa_status_t status = PSA_SUCCESS;
Ronald Cronadc2ff22020-09-16 16:49:27 +0200531 psa_key_id_t derivation_key = 0;
532 psa_key_id_t wrapping_key = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200533
534 /* Initialize the PSA crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100535 PSA_CHECK(psa_crypto_init());
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200536
537 /* Generate mode is unlike the others. Generate the master key and exit. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100538 if (mode == MODE_GENERATE) {
539 return generate(key_file_name);
540 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200541
542 /* Read the master key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100543 PSA_CHECK(import_key_from_file(PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
544 KDF_ALG,
545 key_file_name,
546 &derivation_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200547
548 /* Calculate the derived key for this session. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100549 PSA_CHECK(derive_key_ladder(ladder, ladder_depth,
550 &derivation_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200551
Gilles Peskine449bd832023-01-11 14:50:10 +0100552 switch (mode) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200553 case MODE_SAVE:
Gilles Peskine449bd832023-01-11 14:50:10 +0100554 PSA_CHECK(save_key(derivation_key, output_file_name));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200555 break;
556 case MODE_UNWRAP:
Gilles Peskine449bd832023-01-11 14:50:10 +0100557 PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_DECRYPT,
558 derivation_key,
559 &wrapping_key));
560 PSA_CHECK(unwrap_data(input_file_name, output_file_name,
561 wrapping_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200562 break;
563 case MODE_WRAP:
Gilles Peskine449bd832023-01-11 14:50:10 +0100564 PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_ENCRYPT,
565 derivation_key,
566 &wrapping_key));
567 PSA_CHECK(wrap_data(input_file_name, output_file_name,
568 wrapping_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200569 break;
570 default:
571 /* Unreachable but some compilers don't realize it. */
572 break;
573 }
574
575exit:
Ronald Cronadc2ff22020-09-16 16:49:27 +0200576 /* Destroy any remaining key. Deinitializing the crypto library would do
577 * this anyway since they are volatile keys, but explicitly destroying
Ronald Cron77c89f52020-11-10 17:45:56 +0100578 * keys makes the code easier to reuse. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100579 (void) psa_destroy_key(derivation_key);
580 (void) psa_destroy_key(wrapping_key);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200581 /* Deinitialize the PSA crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100582 mbedtls_psa_crypto_free();
583 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200584}
585
Gilles Peskine449bd832023-01-11 14:50:10 +0100586static void usage(void)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200587{
Gilles Peskine449bd832023-01-11 14:50:10 +0100588 printf("Usage: key_ladder_demo MODE [OPTION=VALUE]...\n");
589 printf("Demonstrate the usage of a key derivation ladder.\n");
590 printf("\n");
591 printf("Modes:\n");
592 printf(" generate Generate the master key\n");
593 printf(" save Save the derived key\n");
594 printf(" unwrap Unwrap (decrypt) input with the derived key\n");
595 printf(" wrap Wrap (encrypt) input with the derived key\n");
596 printf("\n");
597 printf("Options:\n");
598 printf(" input=FILENAME Input file (required for wrap/unwrap)\n");
599 printf(" master=FILENAME File containing the master key (default: master.key)\n");
600 printf(" output=FILENAME Output file (required for save/wrap/unwrap)\n");
601 printf(" label=TEXT Label for the key derivation.\n");
602 printf(" This may be repeated multiple times.\n");
603 printf(" To get the same key, you must use the same master key\n");
604 printf(" and the same sequence of labels.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200605}
606
Gilles Peskine449bd832023-01-11 14:50:10 +0100607int main(int argc, char *argv[])
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200608{
Gilles Peskine738f0172019-01-02 17:25:16 +0100609 const char *key_file_name = "master.key";
610 const char *input_file_name = NULL;
611 const char *output_file_name = NULL;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200612 const char *ladder[MAX_LADDER_DEPTH];
613 size_t ladder_depth = 0;
614 int i;
615 enum program_mode mode;
616 psa_status_t status;
617
Gilles Peskine449bd832023-01-11 14:50:10 +0100618 if (argc <= 1 ||
619 strcmp(argv[1], "help") == 0 ||
620 strcmp(argv[1], "-help") == 0 ||
621 strcmp(argv[1], "--help") == 0) {
622 usage();
623 return EXIT_SUCCESS;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200624 }
625
Gilles Peskine449bd832023-01-11 14:50:10 +0100626 for (i = 2; i < argc; i++) {
627 char *q = strchr(argv[i], '=');
628 if (q == NULL) {
629 printf("Missing argument to option %s\n", argv[i]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200630 goto usage_failure;
631 }
632 *q = 0;
633 ++q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100634 if (strcmp(argv[i], "input") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200635 input_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100636 } else if (strcmp(argv[i], "label") == 0) {
637 if (ladder_depth == MAX_LADDER_DEPTH) {
638 printf("Maximum ladder depth %u exceeded.\n",
639 (unsigned) MAX_LADDER_DEPTH);
640 return EXIT_FAILURE;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200641 }
642 ladder[ladder_depth] = q;
643 ++ladder_depth;
Gilles Peskine449bd832023-01-11 14:50:10 +0100644 } else if (strcmp(argv[i], "master") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200645 key_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100646 } else if (strcmp(argv[i], "output") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200647 output_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100648 } else {
649 printf("Unknown option: %s\n", argv[i]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200650 goto usage_failure;
651 }
652 }
653
Gilles Peskine449bd832023-01-11 14:50:10 +0100654 if (strcmp(argv[1], "generate") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200655 mode = MODE_GENERATE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100656 } else if (strcmp(argv[1], "save") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200657 mode = MODE_SAVE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100658 } else if (strcmp(argv[1], "unwrap") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200659 mode = MODE_UNWRAP;
Gilles Peskine449bd832023-01-11 14:50:10 +0100660 } else if (strcmp(argv[1], "wrap") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200661 mode = MODE_WRAP;
Gilles Peskine449bd832023-01-11 14:50:10 +0100662 } else {
663 printf("Unknown action: %s\n", argv[1]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200664 goto usage_failure;
665 }
666
Gilles Peskine449bd832023-01-11 14:50:10 +0100667 if (input_file_name == NULL &&
668 (mode == MODE_WRAP || mode == MODE_UNWRAP)) {
669 printf("Required argument missing: input\n");
670 return DEMO_ERROR;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200671 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100672 if (output_file_name == NULL &&
673 (mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP)) {
674 printf("Required argument missing: output\n");
675 return DEMO_ERROR;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200676 }
677
Gilles Peskine449bd832023-01-11 14:50:10 +0100678 status = run(mode, key_file_name,
679 ladder, ladder_depth,
680 input_file_name, output_file_name);
681 return status == PSA_SUCCESS ?
682 EXIT_SUCCESS :
683 EXIT_FAILURE;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200684
685usage_failure:
Gilles Peskine449bd832023-01-11 14:50:10 +0100686 usage();
687 return EXIT_FAILURE;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200688}
Manuel Pégourié-Gonnard33783b42023-03-21 17:24:20 +0100689#endif /* PSA_WANT_ALG_SHA_256 && MBEDTLS_MD_C &&
David Horstmann5b98d732022-11-10 18:55:00 +0000690 MBEDTLS_AES_C && MBEDTLS_CCM_C &&
691 MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */