blob: 13037190dd5dbdee04d8d8ded179877e44a85eca [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. */
Ronald Cronadc2ff22020-09-16 16:49:27 +020065#if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
66 !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
67 !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO) || \
68 defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020069int main( void )
70{
Ronald Cronadc2ff22020-09-16 16:49:27 +020071 printf( "MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
72 "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
73 "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
74 "not defined and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER "
75 "defined.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +020076 return( 0 );
77}
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. */
83#define SYS_CHECK( expr ) \
84 do \
85 { \
86 if( ! ( expr ) ) \
87 { \
88 perror( #expr ); \
89 status = DEMO_ERROR; \
90 goto exit; \
91 } \
92 } \
93 while( 0 )
94
95/* Run a PSA function and bail out if it fails. */
96#define PSA_CHECK( expr ) \
97 do \
98 { \
99 status = ( expr ); \
100 if( status != PSA_SUCCESS ) \
101 { \
Kenneth Soerensen518d4352020-04-01 17:22:45 +0200102 printf( "Error %d at line %d: %s\n", \
Jaeden Amerofa30c332018-12-21 18:42:18 +0000103 (int) status, \
104 __LINE__, \
105 #expr ); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200106 goto exit; \
107 } \
108 } \
109 while( 0 )
110
111/* To report operational errors in this program, use an error code that is
112 * different from every PSA error code. */
113#define DEMO_ERROR 120
114
115/* The maximum supported key ladder depth. */
116#define MAX_LADDER_DEPTH 10
117
118/* Salt to use when deriving an intermediate key. */
119#define DERIVE_KEY_SALT ( (uint8_t *) "key_ladder_demo.derive" )
120#define DERIVE_KEY_SALT_LENGTH ( strlen( (const char*) DERIVE_KEY_SALT ) )
121
122/* Salt to use when deriving a wrapping key. */
123#define WRAPPING_KEY_SALT ( (uint8_t *) "key_ladder_demo.wrap" )
124#define WRAPPING_KEY_SALT_LENGTH ( strlen( (const char*) WRAPPING_KEY_SALT ) )
125
126/* Size of the key derivation keys (applies both to the master key and
127 * to intermediate keys). */
128#define KEY_SIZE_BYTES 40
129
130/* Algorithm for key derivation. */
131#define KDF_ALG PSA_ALG_HKDF( PSA_ALG_SHA_256 )
132
133/* Type and size of the key used to wrap data. */
134#define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
135#define WRAPPING_KEY_BITS 128
136
137/* Cipher mode used to wrap data. */
138#define WRAPPING_ALG PSA_ALG_CCM
139
140/* Nonce size used to wrap data. */
141#define WRAPPING_IV_SIZE 13
142
143/* Header used in files containing wrapped data. We'll save this header
144 * directly without worrying about data representation issues such as
145 * integer sizes and endianness, because the data is meant to be read
146 * back by the same program on the same machine. */
147#define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
148#define WRAPPED_DATA_MAGIC_LENGTH ( sizeof( WRAPPED_DATA_MAGIC ) )
149typedef struct
150{
151 char magic[WRAPPED_DATA_MAGIC_LENGTH];
152 size_t ad_size; /* Size of the additional data, which is this header. */
153 size_t payload_size; /* Size of the encrypted data. */
154 /* Store the IV inside the additional data. It's convenient. */
155 uint8_t iv[WRAPPING_IV_SIZE];
156} wrapped_data_header_t;
157
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200158/* The modes that this program can operate in (see usage). */
159enum program_mode
160{
161 MODE_GENERATE,
162 MODE_SAVE,
163 MODE_UNWRAP,
164 MODE_WRAP
165};
166
167/* Save a key to a file. In the real world, you may want to export a derived
168 * key sometimes, to share it with another party. */
Ronald Cronadc2ff22020-09-16 16:49:27 +0200169static psa_status_t save_key( psa_key_id_t key,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200170 const char *output_file_name )
171{
172 psa_status_t status = PSA_SUCCESS;
173 uint8_t key_data[KEY_SIZE_BYTES];
174 size_t key_size;
175 FILE *key_file = NULL;
176
Ronald Cronadc2ff22020-09-16 16:49:27 +0200177 PSA_CHECK( psa_export_key( key,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200178 key_data, sizeof( key_data ),
179 &key_size ) );
180 SYS_CHECK( ( key_file = fopen( output_file_name, "wb" ) ) != NULL );
Gilles Peskine6d576c92022-06-30 17:06:11 +0200181 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
182 mbedtls_setbuf( key_file, NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200183 SYS_CHECK( fwrite( key_data, 1, key_size, key_file ) == key_size );
184 SYS_CHECK( fclose( key_file ) == 0 );
185 key_file = NULL;
186
187exit:
188 if( key_file != NULL)
189 fclose( key_file );
190 return( status );
191}
192
193/* Generate a master key for use in this demo.
194 *
195 * Normally a master key would be non-exportable. For the purpose of this
196 * demo, we want to save it to a file, to avoid relying on the keystore
197 * capability of the PSA crypto library. */
198static psa_status_t generate( const char *key_file_name )
199{
200 psa_status_t status = PSA_SUCCESS;
Ronald Cronadc2ff22020-09-16 16:49:27 +0200201 psa_key_id_t key = 0;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200202 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200203
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200204 psa_set_key_usage_flags( &attributes,
205 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
206 psa_set_key_algorithm( &attributes, KDF_ALG );
207 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine3a4f1f82019-04-26 13:49:28 +0200208 psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200209
Ronald Cronadc2ff22020-09-16 16:49:27 +0200210 PSA_CHECK( psa_generate_key( &attributes, &key ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200211
Ronald Cronadc2ff22020-09-16 16:49:27 +0200212 PSA_CHECK( save_key( key, key_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200213
214exit:
Ronald Cronadc2ff22020-09-16 16:49:27 +0200215 (void) psa_destroy_key( key );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200216 return( status );
217}
218
219/* Load the master key from a file.
220 *
221 * In the real world, this master key would be stored in an internal memory
222 * and the storage would be managed by the keystore capability of the PSA
223 * crypto library. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100224static psa_status_t import_key_from_file( psa_key_usage_t usage,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200225 psa_algorithm_t alg,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100226 const char *key_file_name,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200227 psa_key_id_t *master_key )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200228{
229 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200230 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200231 uint8_t key_data[KEY_SIZE_BYTES];
232 size_t key_size;
233 FILE *key_file = NULL;
234 unsigned char extra_byte;
235
236 SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
Gilles Peskine6d576c92022-06-30 17:06:11 +0200237 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
238 mbedtls_setbuf( key_file, NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200239 SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
240 key_file ) ) != 0 );
241 if( fread( &extra_byte, 1, 1, key_file ) != 0 )
242 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000243 printf( "Key file too large (max: %u).\n",
244 (unsigned) sizeof( key_data ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200245 status = DEMO_ERROR;
246 goto exit;
247 }
248 SYS_CHECK( fclose( key_file ) == 0 );
249 key_file = NULL;
250
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200251 psa_set_key_usage_flags( &attributes, usage );
252 psa_set_key_algorithm( &attributes, alg );
253 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Ronald Cronadc2ff22020-09-16 16:49:27 +0200254 PSA_CHECK( psa_import_key( &attributes, key_data, key_size, master_key ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200255exit:
256 if( key_file != NULL )
257 fclose( key_file );
258 mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100259 if( status != PSA_SUCCESS )
260 {
Gilles Peskine5163a922019-05-27 14:52:34 +0200261 /* If the key creation hasn't happened yet or has failed,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200262 * *master_key is null. psa_destroy_key( 0 ) is
263 * guaranteed to do nothing and return PSA_SUCCESS. */
264 (void) psa_destroy_key( *master_key );
265 *master_key = 0;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100266 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200267 return( status );
268}
269
270/* Derive the intermediate keys, using the list of labels provided on
Ronald Cronadc2ff22020-09-16 16:49:27 +0200271 * the command line. On input, *key is the master key identifier.
272 * This function destroys the master key. On successful output, *key
273 * is the identifier of the final derived key.
274 */
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200275static psa_status_t derive_key_ladder( const char *ladder[],
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100276 size_t ladder_depth,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200277 psa_key_id_t *key )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200278{
279 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200280 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200281 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200282 size_t i;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200283
284 psa_set_key_usage_flags( &attributes,
285 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
286 psa_set_key_algorithm( &attributes, KDF_ALG );
287 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine3a4f1f82019-04-26 13:49:28 +0200288 psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200289
290 /* For each label in turn, ... */
291 for( i = 0; i < ladder_depth; i++ )
292 {
293 /* Start deriving material from the master key (if i=0) or from
294 * the current intermediate key (if i>0). */
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200295 PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
296 PSA_CHECK( psa_key_derivation_input_bytes(
297 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
298 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH ) );
299 PSA_CHECK( psa_key_derivation_input_key(
300 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200301 *key ) );
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200302 PSA_CHECK( psa_key_derivation_input_bytes(
303 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
304 (uint8_t*) ladder[i], strlen( ladder[i] ) ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200305 /* When the parent key is not the master key, destroy it,
306 * since it is no longer needed. */
Ronald Cronadc2ff22020-09-16 16:49:27 +0200307 PSA_CHECK( psa_destroy_key( *key ) );
308 *key = 0;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200309 /* Derive the next intermediate key from the parent key. */
310 PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200311 key ) );
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200312 PSA_CHECK( psa_key_derivation_abort( &operation ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200313 }
314
315exit:
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200316 psa_key_derivation_abort( &operation );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100317 if( status != PSA_SUCCESS )
318 {
Ronald Cronadc2ff22020-09-16 16:49:27 +0200319 psa_destroy_key( *key );
320 *key = 0;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100321 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200322 return( status );
323}
324
325/* Derive a wrapping key from the last intermediate key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100326static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200327 psa_key_id_t derived_key,
328 psa_key_id_t *wrapping_key )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200329{
330 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200331 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200332 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200333
Ronald Cronadc2ff22020-09-16 16:49:27 +0200334 *wrapping_key = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200335
Gilles Peskine2a38e242019-05-29 14:33:00 +0200336 /* Set up a key derivation operation from the key derived from
337 * the master key. */
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200338 PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
339 PSA_CHECK( psa_key_derivation_input_bytes(
340 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
341 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH ) );
342 PSA_CHECK( psa_key_derivation_input_key(
343 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200344 derived_key ) );
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200345 PSA_CHECK( psa_key_derivation_input_bytes(
346 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
347 NULL, 0 ) );
Gilles Peskine2a38e242019-05-29 14:33:00 +0200348
349 /* Create the wrapping key. */
350 psa_set_key_usage_flags( &attributes, usage );
351 psa_set_key_algorithm( &attributes, WRAPPING_ALG );
352 psa_set_key_type( &attributes, PSA_KEY_TYPE_AES );
353 psa_set_key_bits( &attributes, WRAPPING_KEY_BITS );
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200354 PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200355 wrapping_key ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200356
357exit:
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200358 psa_key_derivation_abort( &operation );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200359 return( status );
360}
361
362static psa_status_t wrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100363 const char *output_file_name,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200364 psa_key_id_t wrapping_key )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200365{
366 psa_status_t status;
367 FILE *input_file = NULL;
368 FILE *output_file = NULL;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100369 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
370 psa_key_type_t key_type;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200371 long input_position;
372 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100373 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200374 unsigned char *buffer = NULL;
375 size_t ciphertext_size;
376 wrapped_data_header_t header;
377
378 /* Find the size of the data to wrap. */
379 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
Gilles Peskine6d576c92022-06-30 17:06:11 +0200380 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
381 mbedtls_setbuf( input_file, NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200382 SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
383 SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
384#if LONG_MAX > SIZE_MAX
385 if( input_position > SIZE_MAX )
386 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000387 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200388 status = DEMO_ERROR;
389 goto exit;
390 }
391#endif
392 input_size = input_position;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100393 PSA_CHECK( psa_get_key_attributes( wrapping_key, &attributes ) );
394 key_type = psa_get_key_type( &attributes );
395 buffer_size =
396 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( key_type, WRAPPING_ALG, input_size );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200397 /* Check for integer overflow. */
398 if( buffer_size < input_size )
399 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000400 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200401 status = DEMO_ERROR;
402 goto exit;
403 }
404
405 /* Load the data to wrap. */
406 SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000407 SYS_CHECK( ( buffer = calloc( 1, buffer_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200408 SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
409 SYS_CHECK( fclose( input_file ) == 0 );
410 input_file = NULL;
411
412 /* Construct a header. */
413 memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
414 header.ad_size = sizeof( header );
415 header.payload_size = input_size;
416
417 /* Wrap the data. */
418 PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
Ronald Cronadc2ff22020-09-16 16:49:27 +0200419 PSA_CHECK( psa_aead_encrypt( wrapping_key, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200420 header.iv, WRAPPING_IV_SIZE,
421 (uint8_t *) &header, sizeof( header ),
422 buffer, input_size,
423 buffer, buffer_size,
424 &ciphertext_size ) );
425
426 /* Write the output. */
427 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
Gilles Peskine6d576c92022-06-30 17:06:11 +0200428 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
429 mbedtls_setbuf( output_file, NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200430 SYS_CHECK( fwrite( &header, 1, sizeof( header ),
431 output_file ) == sizeof( header ) );
432 SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
433 output_file ) == ciphertext_size );
434 SYS_CHECK( fclose( output_file ) == 0 );
435 output_file = NULL;
436
437exit:
438 if( input_file != NULL )
439 fclose( input_file );
440 if( output_file != NULL )
441 fclose( output_file );
442 if( buffer != NULL )
443 mbedtls_platform_zeroize( buffer, buffer_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000444 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200445 return( status );
446}
447
448static psa_status_t unwrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100449 const char *output_file_name,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200450 psa_key_id_t wrapping_key )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200451{
452 psa_status_t status;
453 FILE *input_file = NULL;
454 FILE *output_file = NULL;
Bence Szépkútiec174e22021-03-19 18:46:15 +0100455 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
456 psa_key_type_t key_type;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200457 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100458 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200459 size_t plaintext_size;
460 wrapped_data_header_t header;
461 unsigned char extra_byte;
462
463 /* Load and validate the header. */
464 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
Gilles Peskine6d576c92022-06-30 17:06:11 +0200465 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
466 mbedtls_setbuf( input_file, NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200467 SYS_CHECK( fread( &header, 1, sizeof( header ),
468 input_file ) == sizeof( header ) );
469 if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
470 WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
471 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000472 printf( "The input does not start with a valid magic header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200473 status = DEMO_ERROR;
474 goto exit;
475 }
476 if( header.ad_size != sizeof( header ) )
477 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000478 printf( "The header size is not correct.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200479 status = DEMO_ERROR;
480 goto exit;
481 }
Bence Szépkútiec174e22021-03-19 18:46:15 +0100482 PSA_CHECK( psa_get_key_attributes( wrapping_key, &attributes) );
483 key_type = psa_get_key_type( &attributes);
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200484 ciphertext_size =
Bence Szépkútiec174e22021-03-19 18:46:15 +0100485 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( key_type, WRAPPING_ALG, header.payload_size );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200486 /* Check for integer overflow. */
487 if( ciphertext_size < header.payload_size )
488 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000489 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200490 status = DEMO_ERROR;
491 goto exit;
492 }
493
494 /* Load the payload data. */
Jaeden Amerofa30c332018-12-21 18:42:18 +0000495 SYS_CHECK( ( buffer = calloc( 1, ciphertext_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200496 SYS_CHECK( fread( buffer, 1, ciphertext_size,
497 input_file ) == ciphertext_size );
498 if( fread( &extra_byte, 1, 1, input_file ) != 0 )
499 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000500 printf( "Extra garbage after ciphertext\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200501 status = DEMO_ERROR;
502 goto exit;
503 }
504 SYS_CHECK( fclose( input_file ) == 0 );
505 input_file = NULL;
506
507 /* Unwrap the data. */
Ronald Cronadc2ff22020-09-16 16:49:27 +0200508 PSA_CHECK( psa_aead_decrypt( wrapping_key, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200509 header.iv, WRAPPING_IV_SIZE,
510 (uint8_t *) &header, sizeof( header ),
511 buffer, ciphertext_size,
512 buffer, ciphertext_size,
513 &plaintext_size ) );
514 if( plaintext_size != header.payload_size )
515 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000516 printf( "Incorrect payload size in the header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200517 status = DEMO_ERROR;
518 goto exit;
519 }
520
521 /* Write the output. */
522 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
Gilles Peskine6d576c92022-06-30 17:06:11 +0200523 /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
524 mbedtls_setbuf( output_file, NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200525 SYS_CHECK( fwrite( buffer, 1, plaintext_size,
526 output_file ) == plaintext_size );
527 SYS_CHECK( fclose( output_file ) == 0 );
528 output_file = NULL;
529
530exit:
531 if( input_file != NULL )
532 fclose( input_file );
533 if( output_file != NULL )
534 fclose( output_file );
535 if( buffer != NULL )
536 mbedtls_platform_zeroize( buffer, ciphertext_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000537 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200538 return( status );
539}
540
541static psa_status_t run( enum program_mode mode,
542 const char *key_file_name,
543 const char *ladder[], size_t ladder_depth,
544 const char *input_file_name,
545 const char *output_file_name )
546{
547 psa_status_t status = PSA_SUCCESS;
Ronald Cronadc2ff22020-09-16 16:49:27 +0200548 psa_key_id_t derivation_key = 0;
549 psa_key_id_t wrapping_key = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200550
551 /* Initialize the PSA crypto library. */
552 PSA_CHECK( psa_crypto_init( ) );
553
554 /* Generate mode is unlike the others. Generate the master key and exit. */
555 if( mode == MODE_GENERATE )
556 return( generate( key_file_name ) );
557
558 /* Read the master key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100559 PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200560 KDF_ALG,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100561 key_file_name,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200562 &derivation_key ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200563
564 /* Calculate the derived key for this session. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100565 PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200566 &derivation_key ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200567
568 switch( mode )
569 {
570 case MODE_SAVE:
Ronald Cronadc2ff22020-09-16 16:49:27 +0200571 PSA_CHECK( save_key( derivation_key, output_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200572 break;
573 case MODE_UNWRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100574 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200575 derivation_key,
576 &wrapping_key ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100577 PSA_CHECK( unwrap_data( input_file_name, output_file_name,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200578 wrapping_key ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200579 break;
580 case MODE_WRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100581 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200582 derivation_key,
583 &wrapping_key ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100584 PSA_CHECK( wrap_data( input_file_name, output_file_name,
Ronald Cronadc2ff22020-09-16 16:49:27 +0200585 wrapping_key ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200586 break;
587 default:
588 /* Unreachable but some compilers don't realize it. */
589 break;
590 }
591
592exit:
Ronald Cronadc2ff22020-09-16 16:49:27 +0200593 /* Destroy any remaining key. Deinitializing the crypto library would do
594 * this anyway since they are volatile keys, but explicitly destroying
Ronald Cron77c89f52020-11-10 17:45:56 +0100595 * keys makes the code easier to reuse. */
Ronald Cronadc2ff22020-09-16 16:49:27 +0200596 (void) psa_destroy_key( derivation_key );
597 (void) psa_destroy_key( wrapping_key );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200598 /* Deinitialize the PSA crypto library. */
599 mbedtls_psa_crypto_free( );
600 return( status );
601}
602
603static void usage( void )
604{
Jaeden Amerofa30c332018-12-21 18:42:18 +0000605 printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
606 printf( "Demonstrate the usage of a key derivation ladder.\n" );
607 printf( "\n" );
608 printf( "Modes:\n" );
609 printf( " generate Generate the master key\n" );
610 printf( " save Save the derived key\n" );
611 printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
612 printf( " wrap Wrap (encrypt) input with the derived key\n" );
613 printf( "\n" );
614 printf( "Options:\n" );
615 printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
616 printf( " master=FILENAME File containing the master key (default: master.key)\n" );
617 printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
618 printf( " label=TEXT Label for the key derivation.\n" );
619 printf( " This may be repeated multiple times.\n" );
620 printf( " To get the same key, you must use the same master key\n" );
621 printf( " and the same sequence of labels.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200622}
623
624int main( int argc, char *argv[] )
625{
Gilles Peskine738f0172019-01-02 17:25:16 +0100626 const char *key_file_name = "master.key";
627 const char *input_file_name = NULL;
628 const char *output_file_name = NULL;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200629 const char *ladder[MAX_LADDER_DEPTH];
630 size_t ladder_depth = 0;
631 int i;
632 enum program_mode mode;
633 psa_status_t status;
634
635 if( argc <= 1 ||
636 strcmp( argv[1], "help" ) == 0 ||
637 strcmp( argv[1], "-help" ) == 0 ||
638 strcmp( argv[1], "--help" ) == 0 )
639 {
640 usage( );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000641 return( EXIT_SUCCESS );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200642 }
643
644 for( i = 2; i < argc; i++ )
645 {
646 char *q = strchr( argv[i], '=' );
647 if( q == NULL )
648 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000649 printf( "Missing argument to option %s\n", argv[i] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200650 goto usage_failure;
651 }
652 *q = 0;
653 ++q;
654 if( strcmp( argv[i], "input" ) == 0 )
655 input_file_name = q;
656 else if( strcmp( argv[i], "label" ) == 0 )
657 {
658 if( ladder_depth == MAX_LADDER_DEPTH )
659 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000660 printf( "Maximum ladder depth %u exceeded.\n",
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200661 (unsigned) MAX_LADDER_DEPTH );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000662 return( EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200663 }
664 ladder[ladder_depth] = q;
665 ++ladder_depth;
666 }
667 else if( strcmp( argv[i], "master" ) == 0 )
668 key_file_name = q;
669 else if( strcmp( argv[i], "output" ) == 0 )
670 output_file_name = q;
671 else
672 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000673 printf( "Unknown option: %s\n", argv[i] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200674 goto usage_failure;
675 }
676 }
677
678 if( strcmp( argv[1], "generate" ) == 0 )
679 mode = MODE_GENERATE;
680 else if( strcmp( argv[1], "save" ) == 0 )
681 mode = MODE_SAVE;
682 else if( strcmp( argv[1], "unwrap" ) == 0 )
683 mode = MODE_UNWRAP;
684 else if( strcmp( argv[1], "wrap" ) == 0 )
685 mode = MODE_WRAP;
686 else
687 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000688 printf( "Unknown action: %s\n", argv[1] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200689 goto usage_failure;
690 }
691
692 if( input_file_name == NULL &&
693 ( mode == MODE_WRAP || mode == MODE_UNWRAP ) )
694 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000695 printf( "Required argument missing: input\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200696 return( DEMO_ERROR );
697 }
698 if( output_file_name == NULL &&
699 ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) )
700 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000701 printf( "Required argument missing: output\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200702 return( DEMO_ERROR );
703 }
704
705 status = run( mode, key_file_name,
706 ladder, ladder_depth,
707 input_file_name, output_file_name );
708 return( status == PSA_SUCCESS ?
Jaeden Amerofa30c332018-12-21 18:42:18 +0000709 EXIT_SUCCESS :
710 EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200711
712usage_failure:
713 usage( );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000714 return( EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200715}
716#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */