blob: 0ea434fc5f713a420b8828f583852db2617ff64a [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. */
Ronald Cron3e9cc2c2024-10-22 15:39:33 +0200395 memset(&header, 0, sizeof(header));
Gilles Peskine449bd832023-01-11 14:50:10 +0100396 memcpy(&header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH);
397 header.ad_size = sizeof(header);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200398 header.payload_size = input_size;
399
400 /* Wrap the data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100401 PSA_CHECK(psa_generate_random(header.iv, WRAPPING_IV_SIZE));
402 PSA_CHECK(psa_aead_encrypt(wrapping_key, WRAPPING_ALG,
403 header.iv, WRAPPING_IV_SIZE,
404 (uint8_t *) &header, sizeof(header),
405 buffer, input_size,
406 buffer, buffer_size,
407 &ciphertext_size));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200408
409 /* Write the output. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100410 SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200411 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100412 mbedtls_setbuf(output_file, NULL);
413 SYS_CHECK(fwrite(&header, 1, sizeof(header),
414 output_file) == sizeof(header));
415 SYS_CHECK(fwrite(buffer, 1, ciphertext_size,
416 output_file) == ciphertext_size);
417 SYS_CHECK(fclose(output_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200418 output_file = NULL;
419
420exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100421 if (input_file != NULL) {
422 fclose(input_file);
423 }
424 if (output_file != NULL) {
425 fclose(output_file);
426 }
427 if (buffer != NULL) {
428 mbedtls_platform_zeroize(buffer, buffer_size);
429 }
430 free(buffer);
431 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200432}
433
Gilles Peskine449bd832023-01-11 14:50:10 +0100434static psa_status_t unwrap_data(const char *input_file_name,
435 const char *output_file_name,
436 psa_key_id_t wrapping_key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200437{
438 psa_status_t status;
439 FILE *input_file = NULL;
440 FILE *output_file = NULL;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100441 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
442 psa_key_type_t key_type;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200443 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100444 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200445 size_t plaintext_size;
446 wrapped_data_header_t header;
447 unsigned char extra_byte;
448
449 /* Load and validate the header. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100450 SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200451 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100452 mbedtls_setbuf(input_file, NULL);
453 SYS_CHECK(fread(&header, 1, sizeof(header),
454 input_file) == sizeof(header));
455 if (memcmp(&header.magic, WRAPPED_DATA_MAGIC,
456 WRAPPED_DATA_MAGIC_LENGTH) != 0) {
457 printf("The input does not start with a valid magic header.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200458 status = DEMO_ERROR;
459 goto exit;
460 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100461 if (header.ad_size != sizeof(header)) {
462 printf("The header size is not correct.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200463 status = DEMO_ERROR;
464 goto exit;
465 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100466 PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
467 key_type = psa_get_key_type(&attributes);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200468 ciphertext_size =
Gilles Peskine449bd832023-01-11 14:50:10 +0100469 PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, header.payload_size);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200470 /* Check for integer overflow. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100471 if (ciphertext_size < header.payload_size) {
472 printf("Input file too large.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200473 status = DEMO_ERROR;
474 goto exit;
475 }
476
477 /* Load the payload data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100478 SYS_CHECK((buffer = calloc(1, ciphertext_size)) != NULL);
479 SYS_CHECK(fread(buffer, 1, ciphertext_size,
480 input_file) == ciphertext_size);
481 if (fread(&extra_byte, 1, 1, input_file) != 0) {
482 printf("Extra garbage after ciphertext\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200483 status = DEMO_ERROR;
484 goto exit;
485 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100486 SYS_CHECK(fclose(input_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200487 input_file = NULL;
488
489 /* Unwrap the data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100490 PSA_CHECK(psa_aead_decrypt(wrapping_key, WRAPPING_ALG,
491 header.iv, WRAPPING_IV_SIZE,
492 (uint8_t *) &header, sizeof(header),
493 buffer, ciphertext_size,
494 buffer, ciphertext_size,
495 &plaintext_size));
496 if (plaintext_size != header.payload_size) {
497 printf("Incorrect payload size in the header.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200498 status = DEMO_ERROR;
499 goto exit;
500 }
501
502 /* Write the output. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100503 SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200504 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100505 mbedtls_setbuf(output_file, NULL);
506 SYS_CHECK(fwrite(buffer, 1, plaintext_size,
507 output_file) == plaintext_size);
508 SYS_CHECK(fclose(output_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200509 output_file = NULL;
510
511exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100512 if (input_file != NULL) {
513 fclose(input_file);
514 }
515 if (output_file != NULL) {
516 fclose(output_file);
517 }
518 if (buffer != NULL) {
519 mbedtls_platform_zeroize(buffer, ciphertext_size);
520 }
521 free(buffer);
522 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200523}
524
Gilles Peskine449bd832023-01-11 14:50:10 +0100525static psa_status_t run(enum program_mode mode,
526 const char *key_file_name,
527 const char *ladder[], size_t ladder_depth,
528 const char *input_file_name,
529 const char *output_file_name)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200530{
531 psa_status_t status = PSA_SUCCESS;
Ronald Cronadc2ff22020-09-16 16:49:27 +0200532 psa_key_id_t derivation_key = 0;
533 psa_key_id_t wrapping_key = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200534
535 /* Initialize the PSA crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100536 PSA_CHECK(psa_crypto_init());
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200537
538 /* Generate mode is unlike the others. Generate the master key and exit. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100539 if (mode == MODE_GENERATE) {
540 return generate(key_file_name);
541 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200542
543 /* Read the master key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100544 PSA_CHECK(import_key_from_file(PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
545 KDF_ALG,
546 key_file_name,
547 &derivation_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200548
549 /* Calculate the derived key for this session. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100550 PSA_CHECK(derive_key_ladder(ladder, ladder_depth,
551 &derivation_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200552
Gilles Peskine449bd832023-01-11 14:50:10 +0100553 switch (mode) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200554 case MODE_SAVE:
Gilles Peskine449bd832023-01-11 14:50:10 +0100555 PSA_CHECK(save_key(derivation_key, output_file_name));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200556 break;
557 case MODE_UNWRAP:
Gilles Peskine449bd832023-01-11 14:50:10 +0100558 PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_DECRYPT,
559 derivation_key,
560 &wrapping_key));
561 PSA_CHECK(unwrap_data(input_file_name, output_file_name,
562 wrapping_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200563 break;
564 case MODE_WRAP:
Gilles Peskine449bd832023-01-11 14:50:10 +0100565 PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_ENCRYPT,
566 derivation_key,
567 &wrapping_key));
568 PSA_CHECK(wrap_data(input_file_name, output_file_name,
569 wrapping_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200570 break;
571 default:
572 /* Unreachable but some compilers don't realize it. */
573 break;
574 }
575
576exit:
Ronald Cronadc2ff22020-09-16 16:49:27 +0200577 /* Destroy any remaining key. Deinitializing the crypto library would do
578 * this anyway since they are volatile keys, but explicitly destroying
Ronald Cron77c89f52020-11-10 17:45:56 +0100579 * keys makes the code easier to reuse. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100580 (void) psa_destroy_key(derivation_key);
581 (void) psa_destroy_key(wrapping_key);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200582 /* Deinitialize the PSA crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100583 mbedtls_psa_crypto_free();
584 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200585}
586
Gilles Peskine449bd832023-01-11 14:50:10 +0100587static void usage(void)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200588{
Gilles Peskine449bd832023-01-11 14:50:10 +0100589 printf("Usage: key_ladder_demo MODE [OPTION=VALUE]...\n");
590 printf("Demonstrate the usage of a key derivation ladder.\n");
591 printf("\n");
592 printf("Modes:\n");
593 printf(" generate Generate the master key\n");
594 printf(" save Save the derived key\n");
595 printf(" unwrap Unwrap (decrypt) input with the derived key\n");
596 printf(" wrap Wrap (encrypt) input with the derived key\n");
597 printf("\n");
598 printf("Options:\n");
599 printf(" input=FILENAME Input file (required for wrap/unwrap)\n");
600 printf(" master=FILENAME File containing the master key (default: master.key)\n");
601 printf(" output=FILENAME Output file (required for save/wrap/unwrap)\n");
602 printf(" label=TEXT Label for the key derivation.\n");
603 printf(" This may be repeated multiple times.\n");
604 printf(" To get the same key, you must use the same master key\n");
605 printf(" and the same sequence of labels.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200606}
607
Gilles Peskine449bd832023-01-11 14:50:10 +0100608int main(int argc, char *argv[])
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200609{
Gilles Peskine738f0172019-01-02 17:25:16 +0100610 const char *key_file_name = "master.key";
611 const char *input_file_name = NULL;
612 const char *output_file_name = NULL;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200613 const char *ladder[MAX_LADDER_DEPTH];
614 size_t ladder_depth = 0;
615 int i;
616 enum program_mode mode;
617 psa_status_t status;
618
Gilles Peskine449bd832023-01-11 14:50:10 +0100619 if (argc <= 1 ||
620 strcmp(argv[1], "help") == 0 ||
621 strcmp(argv[1], "-help") == 0 ||
622 strcmp(argv[1], "--help") == 0) {
623 usage();
624 return EXIT_SUCCESS;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200625 }
626
Gilles Peskine449bd832023-01-11 14:50:10 +0100627 for (i = 2; i < argc; i++) {
628 char *q = strchr(argv[i], '=');
629 if (q == NULL) {
630 printf("Missing argument to option %s\n", argv[i]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200631 goto usage_failure;
632 }
633 *q = 0;
634 ++q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100635 if (strcmp(argv[i], "input") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200636 input_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100637 } else if (strcmp(argv[i], "label") == 0) {
638 if (ladder_depth == MAX_LADDER_DEPTH) {
639 printf("Maximum ladder depth %u exceeded.\n",
640 (unsigned) MAX_LADDER_DEPTH);
641 return EXIT_FAILURE;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200642 }
643 ladder[ladder_depth] = q;
644 ++ladder_depth;
Gilles Peskine449bd832023-01-11 14:50:10 +0100645 } else if (strcmp(argv[i], "master") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200646 key_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100647 } else if (strcmp(argv[i], "output") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200648 output_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100649 } else {
650 printf("Unknown option: %s\n", argv[i]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200651 goto usage_failure;
652 }
653 }
654
Gilles Peskine449bd832023-01-11 14:50:10 +0100655 if (strcmp(argv[1], "generate") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200656 mode = MODE_GENERATE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100657 } else if (strcmp(argv[1], "save") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200658 mode = MODE_SAVE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100659 } else if (strcmp(argv[1], "unwrap") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200660 mode = MODE_UNWRAP;
Gilles Peskine449bd832023-01-11 14:50:10 +0100661 } else if (strcmp(argv[1], "wrap") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200662 mode = MODE_WRAP;
Gilles Peskine449bd832023-01-11 14:50:10 +0100663 } else {
664 printf("Unknown action: %s\n", argv[1]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200665 goto usage_failure;
666 }
667
Gilles Peskine449bd832023-01-11 14:50:10 +0100668 if (input_file_name == NULL &&
669 (mode == MODE_WRAP || mode == MODE_UNWRAP)) {
670 printf("Required argument missing: input\n");
671 return DEMO_ERROR;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200672 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100673 if (output_file_name == NULL &&
674 (mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP)) {
675 printf("Required argument missing: output\n");
676 return DEMO_ERROR;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200677 }
678
Gilles Peskine449bd832023-01-11 14:50:10 +0100679 status = run(mode, key_file_name,
680 ladder, ladder_depth,
681 input_file_name, output_file_name);
682 return status == PSA_SUCCESS ?
683 EXIT_SUCCESS :
684 EXIT_FAILURE;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200685
686usage_failure:
Gilles Peskine449bd832023-01-11 14:50:10 +0100687 usage();
688 return EXIT_FAILURE;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200689}
Manuel Pégourié-Gonnard33783b42023-03-21 17:24:20 +0100690#endif /* PSA_WANT_ALG_SHA_256 && MBEDTLS_MD_C &&
David Horstmann5b98d732022-11-10 18:55:00 +0000691 MBEDTLS_AES_C && MBEDTLS_CCM_C &&
692 MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */