blob: 0943bf53ce01ad7714463954fa1b30ccc1e2256c [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
33/* Copyright (C) 2018, ARM Limited, All Rights Reserved
34 * SPDX-License-Identifier: Apache-2.0
35 *
36 * Licensed under the Apache License, Version 2.0 (the "License"); you may
37 * not use this file except in compliance with the License.
38 * You may obtain a copy of the License at
39 *
40 * http://www.apache.org/licenses/LICENSE-2.0
41 *
42 * Unless required by applicable law or agreed to in writing, software
43 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
44 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45 * See the License for the specific language governing permissions and
46 * limitations under the License.
47 *
48 * This file is part of mbed TLS (https://tls.mbed.org)
49 */
50
51/* First include Mbed TLS headers to get the Mbed TLS configuration and
52 * platform definitions that we'll use in this program. Also include
53 * standard C headers for functions we'll use here. */
54#if !defined(MBEDTLS_CONFIG_FILE)
55#include "mbedtls/config.h"
56#else
57#include MBEDTLS_CONFIG_FILE
58#endif
59
60#if defined(MBEDTLS_PLATFORM_C)
61#include "mbedtls/platform.h"
62#else
63#include <stdlib.h>
64#define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
65#define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
66#define mbedtls_calloc calloc
67#define mbedtls_free free
68#define mbedtls_printf printf
69#endif
70#include <stdio.h>
71#include <string.h>
72
73#include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
74
75/* If the build options we need are not enabled, compile a placeholder. */
76#if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
77 !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
78 !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO)
79int main( void )
80{
81 mbedtls_printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
82 "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
83 "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO not defined.\n");
84 return( 0 );
85}
86#else
87
88/* The real program starts here. */
89
90
91
92#include <psa/crypto.h>
93
94/* Run a system function and bail out if it fails. */
95#define SYS_CHECK( expr ) \
96 do \
97 { \
98 if( ! ( expr ) ) \
99 { \
100 perror( #expr ); \
101 status = DEMO_ERROR; \
102 goto exit; \
103 } \
104 } \
105 while( 0 )
106
107/* Run a PSA function and bail out if it fails. */
108#define PSA_CHECK( expr ) \
109 do \
110 { \
111 status = ( expr ); \
112 if( status != PSA_SUCCESS ) \
113 { \
114 mbedtls_printf( "Error %d at line %u: %s\n", \
115 (int) status, \
116 __LINE__, \
117 #expr ); \
118 goto exit; \
119 } \
120 } \
121 while( 0 )
122
123/* To report operational errors in this program, use an error code that is
124 * different from every PSA error code. */
125#define DEMO_ERROR 120
126
127/* The maximum supported key ladder depth. */
128#define MAX_LADDER_DEPTH 10
129
130/* Salt to use when deriving an intermediate key. */
131#define DERIVE_KEY_SALT ( (uint8_t *) "key_ladder_demo.derive" )
132#define DERIVE_KEY_SALT_LENGTH ( strlen( (const char*) DERIVE_KEY_SALT ) )
133
134/* Salt to use when deriving a wrapping key. */
135#define WRAPPING_KEY_SALT ( (uint8_t *) "key_ladder_demo.wrap" )
136#define WRAPPING_KEY_SALT_LENGTH ( strlen( (const char*) WRAPPING_KEY_SALT ) )
137
138/* Size of the key derivation keys (applies both to the master key and
139 * to intermediate keys). */
140#define KEY_SIZE_BYTES 40
141
142/* Algorithm for key derivation. */
143#define KDF_ALG PSA_ALG_HKDF( PSA_ALG_SHA_256 )
144
145/* Type and size of the key used to wrap data. */
146#define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
147#define WRAPPING_KEY_BITS 128
148
149/* Cipher mode used to wrap data. */
150#define WRAPPING_ALG PSA_ALG_CCM
151
152/* Nonce size used to wrap data. */
153#define WRAPPING_IV_SIZE 13
154
155/* Header used in files containing wrapped data. We'll save this header
156 * directly without worrying about data representation issues such as
157 * integer sizes and endianness, because the data is meant to be read
158 * back by the same program on the same machine. */
159#define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
160#define WRAPPED_DATA_MAGIC_LENGTH ( sizeof( WRAPPED_DATA_MAGIC ) )
161typedef struct
162{
163 char magic[WRAPPED_DATA_MAGIC_LENGTH];
164 size_t ad_size; /* Size of the additional data, which is this header. */
165 size_t payload_size; /* Size of the encrypted data. */
166 /* Store the IV inside the additional data. It's convenient. */
167 uint8_t iv[WRAPPING_IV_SIZE];
168} wrapped_data_header_t;
169
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200170/* The modes that this program can operate in (see usage). */
171enum program_mode
172{
173 MODE_GENERATE,
174 MODE_SAVE,
175 MODE_UNWRAP,
176 MODE_WRAP
177};
178
179/* Save a key to a file. In the real world, you may want to export a derived
180 * key sometimes, to share it with another party. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100181static psa_status_t save_key( psa_key_handle_t key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200182 const char *output_file_name )
183{
184 psa_status_t status = PSA_SUCCESS;
185 uint8_t key_data[KEY_SIZE_BYTES];
186 size_t key_size;
187 FILE *key_file = NULL;
188
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100189 PSA_CHECK( psa_export_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200190 key_data, sizeof( key_data ),
191 &key_size ) );
192 SYS_CHECK( ( key_file = fopen( output_file_name, "wb" ) ) != NULL );
193 SYS_CHECK( fwrite( key_data, 1, key_size, key_file ) == key_size );
194 SYS_CHECK( fclose( key_file ) == 0 );
195 key_file = NULL;
196
197exit:
198 if( key_file != NULL)
199 fclose( key_file );
200 return( status );
201}
202
203/* Generate a master key for use in this demo.
204 *
205 * Normally a master key would be non-exportable. For the purpose of this
206 * demo, we want to save it to a file, to avoid relying on the keystore
207 * capability of the PSA crypto library. */
208static psa_status_t generate( const char *key_file_name )
209{
210 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100211 psa_key_handle_t key_handle = 0;
Jaeden Amero70261c52019-01-04 11:47:20 +0000212 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200213
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100214 PSA_CHECK( psa_allocate_key( &key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200215 psa_key_policy_set_usage( &policy,
216 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
217 KDF_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100218 PSA_CHECK( psa_set_key_policy( key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200219
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100220 PSA_CHECK( psa_generate_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200221 PSA_KEY_TYPE_DERIVE,
222 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
223 NULL, 0 ) );
224
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100225 PSA_CHECK( save_key( key_handle, key_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200226
227exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100228 (void) psa_destroy_key( key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200229 return( status );
230}
231
232/* Load the master key from a file.
233 *
234 * In the real world, this master key would be stored in an internal memory
235 * and the storage would be managed by the keystore capability of the PSA
236 * crypto library. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100237static psa_status_t import_key_from_file( psa_key_usage_t usage,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200238 psa_algorithm_t alg,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100239 const char *key_file_name,
240 psa_key_handle_t *master_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200241{
242 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000243 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200244 uint8_t key_data[KEY_SIZE_BYTES];
245 size_t key_size;
246 FILE *key_file = NULL;
247 unsigned char extra_byte;
248
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100249 *master_key_handle = 0;
250
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200251 SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
252 SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
253 key_file ) ) != 0 );
254 if( fread( &extra_byte, 1, 1, key_file ) != 0 )
255 {
256 mbedtls_printf( "Key file too large (max: %u).\n",
257 (unsigned) sizeof( key_data ) );
258 status = DEMO_ERROR;
259 goto exit;
260 }
261 SYS_CHECK( fclose( key_file ) == 0 );
262 key_file = NULL;
263
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100264 PSA_CHECK( psa_allocate_key( master_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200265 psa_key_policy_set_usage( &policy, usage, alg );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100266 PSA_CHECK( psa_set_key_policy( *master_key_handle, &policy ) );
267 PSA_CHECK( psa_import_key( *master_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200268 PSA_KEY_TYPE_DERIVE,
269 key_data, key_size ) );
270exit:
271 if( key_file != NULL )
272 fclose( key_file );
273 mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100274 if( status != PSA_SUCCESS )
275 {
276 /* If psa_allocate_key hasn't been called yet or has failed,
277 * *master_key_handle is 0. psa_destroy_key(0) is guaranteed to do
278 * nothing and return PSA_ERROR_INVALID_HANDLE. */
279 (void) psa_destroy_key( *master_key_handle );
280 *master_key_handle = 0;
281 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200282 return( status );
283}
284
285/* Derive the intermediate keys, using the list of labels provided on
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100286 * the command line. On input, *key_handle is a handle to the master key.
287 * This function closes the master key. On successful output, *key_handle
288 * is a handle to the final derived key. */
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200289static psa_status_t derive_key_ladder( const char *ladder[],
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100290 size_t ladder_depth,
291 psa_key_handle_t *key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200292{
293 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000294 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200295 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200296 size_t i;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200297 psa_key_policy_set_usage( &policy,
298 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
299 KDF_ALG );
300
301 /* For each label in turn, ... */
302 for( i = 0; i < ladder_depth; i++ )
303 {
304 /* Start deriving material from the master key (if i=0) or from
305 * the current intermediate key (if i>0). */
306 PSA_CHECK( psa_key_derivation(
307 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100308 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200309 KDF_ALG,
310 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH,
311 (uint8_t*) ladder[i], strlen( ladder[i] ),
312 KEY_SIZE_BYTES ) );
313 /* When the parent key is not the master key, destroy it,
314 * since it is no longer needed. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100315 PSA_CHECK( psa_close_key( *key_handle ) );
316 *key_handle = 0;
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100317 PSA_CHECK( psa_allocate_key( key_handle ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100318 PSA_CHECK( psa_set_key_policy( *key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200319 /* Use the generator obtained from the parent key to create
320 * the next intermediate key. */
321 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100322 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200323 PSA_KEY_TYPE_DERIVE,
324 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
325 &generator ) );
326 PSA_CHECK( psa_generator_abort( &generator ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200327 }
328
329exit:
330 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100331 if( status != PSA_SUCCESS )
332 {
333 psa_close_key( *key_handle );
334 *key_handle = 0;
335 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200336 return( status );
337}
338
339/* Derive a wrapping key from the last intermediate key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100340static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
341 psa_key_handle_t derived_key_handle,
342 psa_key_handle_t *wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200343{
344 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000345 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200346 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
347
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100348 *wrapping_key_handle = 0;
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100349 PSA_CHECK( psa_allocate_key( wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200350 psa_key_policy_set_usage( &policy, usage, WRAPPING_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100351 PSA_CHECK( psa_set_key_policy( *wrapping_key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200352
353 PSA_CHECK( psa_key_derivation(
354 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100355 derived_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200356 KDF_ALG,
357 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH,
358 NULL, 0,
359 PSA_BITS_TO_BYTES( WRAPPING_KEY_BITS ) ) );
360 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100361 *wrapping_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200362 PSA_KEY_TYPE_AES,
363 WRAPPING_KEY_BITS,
364 &generator ) );
365
366exit:
367 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100368 if( status != PSA_SUCCESS )
369 {
370 psa_close_key( *wrapping_key_handle );
371 *wrapping_key_handle = 0;
372 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200373 return( status );
374}
375
376static psa_status_t wrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100377 const char *output_file_name,
378 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200379{
380 psa_status_t status;
381 FILE *input_file = NULL;
382 FILE *output_file = NULL;
383 long input_position;
384 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100385 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200386 unsigned char *buffer = NULL;
387 size_t ciphertext_size;
388 wrapped_data_header_t header;
389
390 /* Find the size of the data to wrap. */
391 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
392 SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
393 SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
394#if LONG_MAX > SIZE_MAX
395 if( input_position > SIZE_MAX )
396 {
397 mbedtls_printf( "Input file too large.\n" );
398 status = DEMO_ERROR;
399 goto exit;
400 }
401#endif
402 input_size = input_position;
403 buffer_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, input_size );
404 /* Check for integer overflow. */
405 if( buffer_size < input_size )
406 {
407 mbedtls_printf( "Input file too large.\n" );
408 status = DEMO_ERROR;
409 goto exit;
410 }
411
412 /* Load the data to wrap. */
413 SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
414 SYS_CHECK( ( buffer = mbedtls_calloc( 1, buffer_size ) ) != NULL );
415 SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
416 SYS_CHECK( fclose( input_file ) == 0 );
417 input_file = NULL;
418
419 /* Construct a header. */
420 memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
421 header.ad_size = sizeof( header );
422 header.payload_size = input_size;
423
424 /* Wrap the data. */
425 PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100426 PSA_CHECK( psa_aead_encrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200427 header.iv, WRAPPING_IV_SIZE,
428 (uint8_t *) &header, sizeof( header ),
429 buffer, input_size,
430 buffer, buffer_size,
431 &ciphertext_size ) );
432
433 /* Write the output. */
434 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
435 SYS_CHECK( fwrite( &header, 1, sizeof( header ),
436 output_file ) == sizeof( header ) );
437 SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
438 output_file ) == ciphertext_size );
439 SYS_CHECK( fclose( output_file ) == 0 );
440 output_file = NULL;
441
442exit:
443 if( input_file != NULL )
444 fclose( input_file );
445 if( output_file != NULL )
446 fclose( output_file );
447 if( buffer != NULL )
448 mbedtls_platform_zeroize( buffer, buffer_size );
449 mbedtls_free( buffer );
450 return( status );
451}
452
453static psa_status_t unwrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100454 const char *output_file_name,
455 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200456{
457 psa_status_t status;
458 FILE *input_file = NULL;
459 FILE *output_file = NULL;
460 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100461 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200462 size_t plaintext_size;
463 wrapped_data_header_t header;
464 unsigned char extra_byte;
465
466 /* Load and validate the header. */
467 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
468 SYS_CHECK( fread( &header, 1, sizeof( header ),
469 input_file ) == sizeof( header ) );
470 if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
471 WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
472 {
473 mbedtls_printf( "The input does not start with a valid magic header.\n" );
474 status = DEMO_ERROR;
475 goto exit;
476 }
477 if( header.ad_size != sizeof( header ) )
478 {
479 mbedtls_printf( "The header size is not correct.\n" );
480 status = DEMO_ERROR;
481 goto exit;
482 }
483 ciphertext_size =
484 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, header.payload_size );
485 /* Check for integer overflow. */
486 if( ciphertext_size < header.payload_size )
487 {
488 mbedtls_printf( "Input file too large.\n" );
489 status = DEMO_ERROR;
490 goto exit;
491 }
492
493 /* Load the payload data. */
494 SYS_CHECK( ( buffer = mbedtls_calloc( 1, ciphertext_size ) ) != NULL );
495 SYS_CHECK( fread( buffer, 1, ciphertext_size,
496 input_file ) == ciphertext_size );
497 if( fread( &extra_byte, 1, 1, input_file ) != 0 )
498 {
499 mbedtls_printf( "Extra garbage after ciphertext\n" );
500 status = DEMO_ERROR;
501 goto exit;
502 }
503 SYS_CHECK( fclose( input_file ) == 0 );
504 input_file = NULL;
505
506 /* Unwrap the data. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100507 PSA_CHECK( psa_aead_decrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200508 header.iv, WRAPPING_IV_SIZE,
509 (uint8_t *) &header, sizeof( header ),
510 buffer, ciphertext_size,
511 buffer, ciphertext_size,
512 &plaintext_size ) );
513 if( plaintext_size != header.payload_size )
514 {
515 mbedtls_printf( "Incorrect payload size in the header.\n" );
516 status = DEMO_ERROR;
517 goto exit;
518 }
519
520 /* Write the output. */
521 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
522 SYS_CHECK( fwrite( buffer, 1, plaintext_size,
523 output_file ) == plaintext_size );
524 SYS_CHECK( fclose( output_file ) == 0 );
525 output_file = NULL;
526
527exit:
528 if( input_file != NULL )
529 fclose( input_file );
530 if( output_file != NULL )
531 fclose( output_file );
532 if( buffer != NULL )
533 mbedtls_platform_zeroize( buffer, ciphertext_size );
534 mbedtls_free( buffer );
535 return( status );
536}
537
538static psa_status_t run( enum program_mode mode,
539 const char *key_file_name,
540 const char *ladder[], size_t ladder_depth,
541 const char *input_file_name,
542 const char *output_file_name )
543{
544 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100545 psa_key_handle_t derivation_key_handle = 0;
546 psa_key_handle_t wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200547
548 /* Initialize the PSA crypto library. */
549 PSA_CHECK( psa_crypto_init( ) );
550
551 /* Generate mode is unlike the others. Generate the master key and exit. */
552 if( mode == MODE_GENERATE )
553 return( generate( key_file_name ) );
554
555 /* Read the master key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100556 PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200557 KDF_ALG,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100558 key_file_name,
559 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200560
561 /* Calculate the derived key for this session. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100562 PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
563 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200564
565 switch( mode )
566 {
567 case MODE_SAVE:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100568 PSA_CHECK( save_key( derivation_key_handle, output_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200569 break;
570 case MODE_UNWRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100571 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
572 derivation_key_handle,
573 &wrapping_key_handle ) );
574 PSA_CHECK( unwrap_data( input_file_name, output_file_name,
575 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200576 break;
577 case MODE_WRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100578 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
579 derivation_key_handle,
580 &wrapping_key_handle ) );
581 PSA_CHECK( wrap_data( input_file_name, output_file_name,
582 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200583 break;
584 default:
585 /* Unreachable but some compilers don't realize it. */
586 break;
587 }
588
589exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100590 /* Close any remaining key. Deinitializing the crypto library would do
591 * this anyway, but explicitly closing handles makes the code easier
592 * to reuse. */
593 (void) psa_close_key( derivation_key_handle );
594 (void) psa_close_key( wrapping_key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200595 /* Deinitialize the PSA crypto library. */
596 mbedtls_psa_crypto_free( );
597 return( status );
598}
599
600static void usage( void )
601{
602 mbedtls_printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
603 mbedtls_printf( "Demonstrate the usage of a key derivation ladder.\n" );
604 mbedtls_printf( "\n" );
605 mbedtls_printf( "Modes:\n" );
606 mbedtls_printf( " generate Generate the master key\n" );
607 mbedtls_printf( " save Save the derived key\n" );
608 mbedtls_printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
609 mbedtls_printf( " wrap Wrap (encrypt) input with the derived key\n" );
610 mbedtls_printf( "\n" );
611 mbedtls_printf( "Options:\n" );
612 mbedtls_printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
613 mbedtls_printf( " master=FILENAME File containing the master key (default: master.key)\n" );
614 mbedtls_printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
615 mbedtls_printf( " label=TEXT Label for the key derivation.\n" );
616 mbedtls_printf( " This may be repeated multiple times.\n" );
617 mbedtls_printf( " To get the same key, you must use the same master key\n" );
618 mbedtls_printf( " and the same sequence of labels.\n" );
619}
620
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000621#if defined(MBEDTLS_CHECK_PARAMS)
622#include "mbedtls/platform_util.h"
623void mbedtls_param_failed( const char *failure_condition,
624 const char *file,
625 int line )
626{
627 mbedtls_printf( "%s:%i: Input param failed - %s\n",
628 file, line, failure_condition );
629 mbedtls_exit( MBEDTLS_EXIT_FAILURE );
630}
631#endif
632
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200633int main( int argc, char *argv[] )
634{
Gilles Peskine738f0172019-01-02 17:25:16 +0100635 const char *key_file_name = "master.key";
636 const char *input_file_name = NULL;
637 const char *output_file_name = NULL;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200638 const char *ladder[MAX_LADDER_DEPTH];
639 size_t ladder_depth = 0;
640 int i;
641 enum program_mode mode;
642 psa_status_t status;
643
644 if( argc <= 1 ||
645 strcmp( argv[1], "help" ) == 0 ||
646 strcmp( argv[1], "-help" ) == 0 ||
647 strcmp( argv[1], "--help" ) == 0 )
648 {
649 usage( );
650 return( MBEDTLS_EXIT_SUCCESS );
651 }
652
653 for( i = 2; i < argc; i++ )
654 {
655 char *q = strchr( argv[i], '=' );
656 if( q == NULL )
657 {
658 mbedtls_printf( "Missing argument to option %s\n", argv[i] );
659 goto usage_failure;
660 }
661 *q = 0;
662 ++q;
663 if( strcmp( argv[i], "input" ) == 0 )
664 input_file_name = q;
665 else if( strcmp( argv[i], "label" ) == 0 )
666 {
667 if( ladder_depth == MAX_LADDER_DEPTH )
668 {
669 mbedtls_printf( "Maximum ladder depth %u exceeded.\n",
670 (unsigned) MAX_LADDER_DEPTH );
671 return( MBEDTLS_EXIT_FAILURE );
672 }
673 ladder[ladder_depth] = q;
674 ++ladder_depth;
675 }
676 else if( strcmp( argv[i], "master" ) == 0 )
677 key_file_name = q;
678 else if( strcmp( argv[i], "output" ) == 0 )
679 output_file_name = q;
680 else
681 {
682 mbedtls_printf( "Unknown option: %s\n", argv[i] );
683 goto usage_failure;
684 }
685 }
686
687 if( strcmp( argv[1], "generate" ) == 0 )
688 mode = MODE_GENERATE;
689 else if( strcmp( argv[1], "save" ) == 0 )
690 mode = MODE_SAVE;
691 else if( strcmp( argv[1], "unwrap" ) == 0 )
692 mode = MODE_UNWRAP;
693 else if( strcmp( argv[1], "wrap" ) == 0 )
694 mode = MODE_WRAP;
695 else
696 {
697 mbedtls_printf( "Unknown action: %s\n", argv[1] );
698 goto usage_failure;
699 }
700
701 if( input_file_name == NULL &&
702 ( mode == MODE_WRAP || mode == MODE_UNWRAP ) )
703 {
704 mbedtls_printf( "Required argument missing: input\n" );
705 return( DEMO_ERROR );
706 }
707 if( output_file_name == NULL &&
708 ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) )
709 {
710 mbedtls_printf( "Required argument missing: output\n" );
711 return( DEMO_ERROR );
712 }
713
714 status = run( mode, key_file_name,
715 ladder, ladder_depth,
716 input_file_name, output_file_name );
717 return( status == PSA_SUCCESS ?
718 MBEDTLS_EXIT_SUCCESS :
719 MBEDTLS_EXIT_FAILURE );
720
721usage_failure:
722 usage( );
723 return( MBEDTLS_EXIT_FAILURE );
724}
725#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */