blob: a79fac640c9a7d1837108f8a7d286303129ba59b [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
Gilles Peskinef0fa4362018-07-16 17:08:43 +020035 * 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.
Gilles Peskinef0fa4362018-07-16 17:08:43 +020048 */
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. */
Bence Szépkútic662b362021-05-27 11:25:03 +020053#include "mbedtls/build_info.h"
Gilles Peskinef0fa4362018-07-16 17:08:43 +020054
Gilles Peskinef0fa4362018-07-16 17:08:43 +020055#include <stdlib.h>
Gilles Peskinef0fa4362018-07-16 17:08:43 +020056#include <stdio.h>
57#include <string.h>
58
Gilles Peskine6d576c92022-06-30 17:06:11 +020059#include "mbedtls/platform.h" // for mbedtls_setbuf
Gilles Peskinef0fa4362018-07-16 17:08:43 +020060#include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
61
Gilles Peskine4e2cc532019-05-29 14:30:27 +020062#include <psa/crypto.h>
63
Gilles Peskinef0fa4362018-07-16 17:08:43 +020064/* If the build options we need are not enabled, compile a placeholder. */
Manuel Pégourié-Gonnard33783b42023-03-21 17:24:20 +010065#if !defined(PSA_WANT_ALG_SHA_256) || !defined(MBEDTLS_MD_C) || \
Ronald Cronadc2ff22020-09-16 16:49:27 +020066 !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)
Gilles Peskine449bd832023-01-11 14:50:10 +010069int main(void)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020070{
Manuel Pégourié-Gonnard33783b42023-03-21 17:24:20 +010071 printf("PSA_WANT_ALG_SHA_256 and/or MBEDTLS_MD_C and/or "
Gilles Peskine449bd832023-01-11 14:50:10 +010072 "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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +020077}
78#else
79
80/* The real program starts here. */
81
Gilles Peskinef0fa4362018-07-16 17:08:43 +020082/* Run a system function and bail out if it fails. */
Gilles Peskine449bd832023-01-11 14:50:10 +010083#define SYS_CHECK(expr) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020084 do \
85 { \
Gilles Peskine449bd832023-01-11 14:50:10 +010086 if (!(expr)) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020087 { \
Gilles Peskine449bd832023-01-11 14:50:10 +010088 perror( #expr); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020089 status = DEMO_ERROR; \
90 goto exit; \
91 } \
92 } \
Gilles Peskine449bd832023-01-11 14:50:10 +010093 while (0)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020094
95/* Run a PSA function and bail out if it fails. */
Gilles Peskine449bd832023-01-11 14:50:10 +010096#define PSA_CHECK(expr) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +020097 do \
98 { \
Gilles Peskine449bd832023-01-11 14:50:10 +010099 status = (expr); \
100 if (status != PSA_SUCCESS) \
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200101 { \
Gilles Peskine449bd832023-01-11 14:50:10 +0100102 printf("Error %d at line %d: %s\n", \
103 (int) status, \
104 __LINE__, \
105 #expr); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200106 goto exit; \
107 } \
108 } \
Gilles Peskine449bd832023-01-11 14:50:10 +0100109 while (0)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200110
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. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100119#define DERIVE_KEY_SALT ((uint8_t *) "key_ladder_demo.derive")
120#define DERIVE_KEY_SALT_LENGTH (strlen((const char *) DERIVE_KEY_SALT))
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200121
122/* Salt to use when deriving a wrapping key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100123#define WRAPPING_KEY_SALT ((uint8_t *) "key_ladder_demo.wrap")
124#define WRAPPING_KEY_SALT_LENGTH (strlen((const char *) WRAPPING_KEY_SALT))
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200125
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. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100131#define KDF_ALG PSA_ALG_HKDF(PSA_ALG_SHA_256)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200132
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
Gilles Peskine449bd832023-01-11 14:50:10 +0100148#define WRAPPED_DATA_MAGIC_LENGTH (sizeof(WRAPPED_DATA_MAGIC))
149typedef struct {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200150 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
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200157/* The modes that this program can operate in (see usage). */
Gilles Peskine449bd832023-01-11 14:50:10 +0100158enum program_mode {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200159 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. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100167static psa_status_t save_key(psa_key_id_t key,
168 const char *output_file_name)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200169{
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
Gilles Peskine449bd832023-01-11 14:50:10 +0100175 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);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200179 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100180 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);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200183 key_file = NULL;
184
185exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100186 if (key_file != NULL) {
187 fclose(key_file);
188 }
189 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200190}
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. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100197static psa_status_t generate(const char *key_file_name)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200198{
199 psa_status_t status = PSA_SUCCESS;
Ronald Cronadc2ff22020-09-16 16:49:27 +0200200 psa_key_id_t key = 0;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200201 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200202
Gilles Peskine449bd832023-01-11 14:50:10 +0100203 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200208
Gilles Peskine449bd832023-01-11 14:50:10 +0100209 PSA_CHECK(psa_generate_key(&attributes, &key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200210
Gilles Peskine449bd832023-01-11 14:50:10 +0100211 PSA_CHECK(save_key(key, key_file_name));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200212
213exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100214 (void) psa_destroy_key(key);
215 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200216}
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. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100223static 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)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200227{
228 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200229 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200230 uint8_t key_data[KEY_SIZE_BYTES];
231 size_t key_size;
232 FILE *key_file = NULL;
233 unsigned char extra_byte;
234
Gilles Peskine449bd832023-01-11 14:50:10 +0100235 SYS_CHECK((key_file = fopen(key_file_name, "rb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200236 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100237 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200243 status = DEMO_ERROR;
244 goto exit;
245 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100246 SYS_CHECK(fclose(key_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200247 key_file = NULL;
248
Gilles Peskine449bd832023-01-11 14:50:10 +0100249 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200253exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100254 if (key_file != NULL) {
255 fclose(key_file);
256 }
257 mbedtls_platform_zeroize(key_data, sizeof(key_data));
258 if (status != PSA_SUCCESS) {
Gilles Peskine5163a922019-05-27 14:52:34 +0200259 /* If the key creation hasn't happened yet or has failed,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200260 * *master_key is null. psa_destroy_key( 0 ) is
261 * guaranteed to do nothing and return PSA_SUCCESS. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100262 (void) psa_destroy_key(*master_key);
Ronald Cronadc2ff22020-09-16 16:49:27 +0200263 *master_key = 0;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100264 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100265 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200266}
267
268/* Derive the intermediate keys, using the list of labels provided on
Ronald Cronadc2ff22020-09-16 16:49:27 +0200269 * 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 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100273static psa_status_t derive_key_ladder(const char *ladder[],
274 size_t ladder_depth,
275 psa_key_id_t *key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200276{
277 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200278 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200279 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200280 size_t i;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200281
Gilles Peskine449bd832023-01-11 14:50:10 +0100282 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200287
288 /* For each label in turn, ... */
Gilles Peskine449bd832023-01-11 14:50:10 +0100289 for (i = 0; i < ladder_depth; i++) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200290 /* Start deriving material from the master key (if i=0) or from
291 * the current intermediate key (if i>0). */
Gilles Peskine449bd832023-01-11 14:50:10 +0100292 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])));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200302 /* When the parent key is not the master key, destroy it,
303 * since it is no longer needed. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100304 PSA_CHECK(psa_destroy_key(*key));
Ronald Cronadc2ff22020-09-16 16:49:27 +0200305 *key = 0;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200306 /* Derive the next intermediate key from the parent key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100307 PSA_CHECK(psa_key_derivation_output_key(&attributes, &operation,
308 key));
309 PSA_CHECK(psa_key_derivation_abort(&operation));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200310 }
311
312exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100313 psa_key_derivation_abort(&operation);
314 if (status != PSA_SUCCESS) {
315 psa_destroy_key(*key);
Ronald Cronadc2ff22020-09-16 16:49:27 +0200316 *key = 0;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100317 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100318 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200319}
320
321/* Derive a wrapping key from the last intermediate key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100322static 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)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200325{
326 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200327 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200328 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200329
Ronald Cronadc2ff22020-09-16 16:49:27 +0200330 *wrapping_key = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200331
Gilles Peskine2a38e242019-05-29 14:33:00 +0200332 /* Set up a key derivation operation from the key derived from
333 * the master key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100334 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));
Gilles Peskine2a38e242019-05-29 14:33:00 +0200344
345 /* Create the wrapping key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100346 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200352
353exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100354 psa_key_derivation_abort(&operation);
355 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200356}
357
Gilles Peskine449bd832023-01-11 14:50:10 +0100358static psa_status_t wrap_data(const char *input_file_name,
359 const char *output_file_name,
360 psa_key_id_t wrapping_key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200361{
362 psa_status_t status;
363 FILE *input_file = NULL;
364 FILE *output_file = NULL;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100365 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
366 psa_key_type_t key_type;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200367 long input_position;
368 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100369 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200370 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. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100375 SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200376 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100377 mbedtls_setbuf(input_file, NULL);
378 SYS_CHECK(fseek(input_file, 0, SEEK_END) == 0);
379 SYS_CHECK((input_position = ftell(input_file)) != -1);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200380#if LONG_MAX > SIZE_MAX
Gilles Peskine449bd832023-01-11 14:50:10 +0100381 if (input_position > SIZE_MAX) {
382 printf("Input file too large.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200383 status = DEMO_ERROR;
384 goto exit;
385 }
386#endif
387 input_size = input_position;
Gilles Peskine449bd832023-01-11 14:50:10 +0100388 PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
389 key_type = psa_get_key_type(&attributes);
Bence Szépkútiec174e22021-03-19 18:46:15 +0100390 buffer_size =
Gilles Peskine449bd832023-01-11 14:50:10 +0100391 PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, input_size);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200392 /* Check for integer overflow. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100393 if (buffer_size < input_size) {
394 printf("Input file too large.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200395 status = DEMO_ERROR;
396 goto exit;
397 }
398
399 /* Load the data to wrap. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100400 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);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200404 input_file = NULL;
405
406 /* Construct a header. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100407 memcpy(&header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH);
408 header.ad_size = sizeof(header);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200409 header.payload_size = input_size;
410
411 /* Wrap the data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100412 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200419
420 /* Write the output. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100421 SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200422 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100423 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);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200429 output_file = NULL;
430
431exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100432 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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200443}
444
Gilles Peskine449bd832023-01-11 14:50:10 +0100445static psa_status_t unwrap_data(const char *input_file_name,
446 const char *output_file_name,
447 psa_key_id_t wrapping_key)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200448{
449 psa_status_t status;
450 FILE *input_file = NULL;
451 FILE *output_file = NULL;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100452 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
453 psa_key_type_t key_type;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200454 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100455 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200456 size_t plaintext_size;
457 wrapped_data_header_t header;
458 unsigned char extra_byte;
459
460 /* Load and validate the header. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100461 SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200462 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100463 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");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200469 status = DEMO_ERROR;
470 goto exit;
471 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100472 if (header.ad_size != sizeof(header)) {
473 printf("The header size is not correct.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200474 status = DEMO_ERROR;
475 goto exit;
476 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100477 PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
478 key_type = psa_get_key_type(&attributes);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200479 ciphertext_size =
Gilles Peskine449bd832023-01-11 14:50:10 +0100480 PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, header.payload_size);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200481 /* Check for integer overflow. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100482 if (ciphertext_size < header.payload_size) {
483 printf("Input file too large.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200484 status = DEMO_ERROR;
485 goto exit;
486 }
487
488 /* Load the payload data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100489 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");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200494 status = DEMO_ERROR;
495 goto exit;
496 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100497 SYS_CHECK(fclose(input_file) == 0);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200498 input_file = NULL;
499
500 /* Unwrap the data. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100501 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");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200509 status = DEMO_ERROR;
510 goto exit;
511 }
512
513 /* Write the output. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100514 SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
Gilles Peskine6d576c92022-06-30 17:06:11 +0200515 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100516 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);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200520 output_file = NULL;
521
522exit:
Gilles Peskine449bd832023-01-11 14:50:10 +0100523 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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200534}
535
Gilles Peskine449bd832023-01-11 14:50:10 +0100536static 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)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200541{
542 psa_status_t status = PSA_SUCCESS;
Ronald Cronadc2ff22020-09-16 16:49:27 +0200543 psa_key_id_t derivation_key = 0;
544 psa_key_id_t wrapping_key = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200545
546 /* Initialize the PSA crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100547 PSA_CHECK(psa_crypto_init());
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200548
549 /* Generate mode is unlike the others. Generate the master key and exit. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100550 if (mode == MODE_GENERATE) {
551 return generate(key_file_name);
552 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200553
554 /* Read the master key. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100555 PSA_CHECK(import_key_from_file(PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
556 KDF_ALG,
557 key_file_name,
558 &derivation_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200559
560 /* Calculate the derived key for this session. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100561 PSA_CHECK(derive_key_ladder(ladder, ladder_depth,
562 &derivation_key));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200563
Gilles Peskine449bd832023-01-11 14:50:10 +0100564 switch (mode) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200565 case MODE_SAVE:
Gilles Peskine449bd832023-01-11 14:50:10 +0100566 PSA_CHECK(save_key(derivation_key, output_file_name));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200567 break;
568 case MODE_UNWRAP:
Gilles Peskine449bd832023-01-11 14:50:10 +0100569 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200574 break;
575 case MODE_WRAP:
Gilles Peskine449bd832023-01-11 14:50:10 +0100576 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));
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200581 break;
582 default:
583 /* Unreachable but some compilers don't realize it. */
584 break;
585 }
586
587exit:
Ronald Cronadc2ff22020-09-16 16:49:27 +0200588 /* Destroy any remaining key. Deinitializing the crypto library would do
589 * this anyway since they are volatile keys, but explicitly destroying
Ronald Cron77c89f52020-11-10 17:45:56 +0100590 * keys makes the code easier to reuse. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100591 (void) psa_destroy_key(derivation_key);
592 (void) psa_destroy_key(wrapping_key);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200593 /* Deinitialize the PSA crypto library. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100594 mbedtls_psa_crypto_free();
595 return status;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200596}
597
Gilles Peskine449bd832023-01-11 14:50:10 +0100598static void usage(void)
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200599{
Gilles Peskine449bd832023-01-11 14:50:10 +0100600 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");
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200617}
618
Gilles Peskine449bd832023-01-11 14:50:10 +0100619int main(int argc, char *argv[])
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200620{
Gilles Peskine738f0172019-01-02 17:25:16 +0100621 const char *key_file_name = "master.key";
622 const char *input_file_name = NULL;
623 const char *output_file_name = NULL;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200624 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
Gilles Peskine449bd832023-01-11 14:50:10 +0100630 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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200636 }
637
Gilles Peskine449bd832023-01-11 14:50:10 +0100638 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]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200642 goto usage_failure;
643 }
644 *q = 0;
645 ++q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100646 if (strcmp(argv[i], "input") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200647 input_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100648 } 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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200653 }
654 ladder[ladder_depth] = q;
655 ++ladder_depth;
Gilles Peskine449bd832023-01-11 14:50:10 +0100656 } else if (strcmp(argv[i], "master") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200657 key_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100658 } else if (strcmp(argv[i], "output") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200659 output_file_name = q;
Gilles Peskine449bd832023-01-11 14:50:10 +0100660 } else {
661 printf("Unknown option: %s\n", argv[i]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200662 goto usage_failure;
663 }
664 }
665
Gilles Peskine449bd832023-01-11 14:50:10 +0100666 if (strcmp(argv[1], "generate") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200667 mode = MODE_GENERATE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100668 } else if (strcmp(argv[1], "save") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200669 mode = MODE_SAVE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100670 } else if (strcmp(argv[1], "unwrap") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200671 mode = MODE_UNWRAP;
Gilles Peskine449bd832023-01-11 14:50:10 +0100672 } else if (strcmp(argv[1], "wrap") == 0) {
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200673 mode = MODE_WRAP;
Gilles Peskine449bd832023-01-11 14:50:10 +0100674 } else {
675 printf("Unknown action: %s\n", argv[1]);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200676 goto usage_failure;
677 }
678
Gilles Peskine449bd832023-01-11 14:50:10 +0100679 if (input_file_name == NULL &&
680 (mode == MODE_WRAP || mode == MODE_UNWRAP)) {
681 printf("Required argument missing: input\n");
682 return DEMO_ERROR;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200683 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100684 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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200688 }
689
Gilles Peskine449bd832023-01-11 14:50:10 +0100690 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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200696
697usage_failure:
Gilles Peskine449bd832023-01-11 14:50:10 +0100698 usage();
699 return EXIT_FAILURE;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200700}
Manuel Pégourié-Gonnard33783b42023-03-21 17:24:20 +0100701#endif /* PSA_WANT_ALG_SHA_256 && MBEDTLS_MD_C &&
David Horstmann5b98d732022-11-10 18:55:00 +0000702 MBEDTLS_AES_C && MBEDTLS_CCM_C &&
703 MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */