blob: 470b1fce4a784a8c2f3971ae42664d2441b5c22b [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;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200212 psa_key_policy_t policy;
213
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100214 PSA_CHECK( psa_allocate_key( PSA_KEY_TYPE_DERIVE,
215 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
216 &key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200217 psa_key_policy_init( &policy );
218 psa_key_policy_set_usage( &policy,
219 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
220 KDF_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100221 PSA_CHECK( psa_set_key_policy( key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200222
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100223 PSA_CHECK( psa_generate_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200224 PSA_KEY_TYPE_DERIVE,
225 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
226 NULL, 0 ) );
227
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100228 PSA_CHECK( save_key( key_handle, key_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200229
230exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100231 (void) psa_destroy_key( key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200232 return( status );
233}
234
235/* Load the master key from a file.
236 *
237 * In the real world, this master key would be stored in an internal memory
238 * and the storage would be managed by the keystore capability of the PSA
239 * crypto library. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100240static psa_status_t import_key_from_file( psa_key_usage_t usage,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200241 psa_algorithm_t alg,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100242 const char *key_file_name,
243 psa_key_handle_t *master_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200244{
245 psa_status_t status = PSA_SUCCESS;
246 psa_key_policy_t policy;
247 uint8_t key_data[KEY_SIZE_BYTES];
248 size_t key_size;
249 FILE *key_file = NULL;
250 unsigned char extra_byte;
251
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100252 *master_key_handle = 0;
253
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200254 SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
255 SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
256 key_file ) ) != 0 );
257 if( fread( &extra_byte, 1, 1, key_file ) != 0 )
258 {
259 mbedtls_printf( "Key file too large (max: %u).\n",
260 (unsigned) sizeof( key_data ) );
261 status = DEMO_ERROR;
262 goto exit;
263 }
264 SYS_CHECK( fclose( key_file ) == 0 );
265 key_file = NULL;
266
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100267 PSA_CHECK( psa_allocate_key( PSA_KEY_TYPE_DERIVE,
268 PSA_BYTES_TO_BITS( key_size ),
269 master_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200270 psa_key_policy_init( &policy );
271 psa_key_policy_set_usage( &policy, usage, alg );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100272 PSA_CHECK( psa_set_key_policy( *master_key_handle, &policy ) );
273 PSA_CHECK( psa_import_key( *master_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200274 PSA_KEY_TYPE_DERIVE,
275 key_data, key_size ) );
276exit:
277 if( key_file != NULL )
278 fclose( key_file );
279 mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100280 if( status != PSA_SUCCESS )
281 {
282 /* If psa_allocate_key hasn't been called yet or has failed,
283 * *master_key_handle is 0. psa_destroy_key(0) is guaranteed to do
284 * nothing and return PSA_ERROR_INVALID_HANDLE. */
285 (void) psa_destroy_key( *master_key_handle );
286 *master_key_handle = 0;
287 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200288 return( status );
289}
290
291/* Derive the intermediate keys, using the list of labels provided on
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100292 * the command line. On input, *key_handle is a handle to the master key.
293 * This function closes the master key. On successful output, *key_handle
294 * is a handle to the final derived key. */
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200295static psa_status_t derive_key_ladder( const char *ladder[],
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100296 size_t ladder_depth,
297 psa_key_handle_t *key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200298{
299 psa_status_t status = PSA_SUCCESS;
300 psa_key_policy_t policy;
301 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200302 size_t i;
303 psa_key_policy_init( &policy );
304 psa_key_policy_set_usage( &policy,
305 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
306 KDF_ALG );
307
308 /* For each label in turn, ... */
309 for( i = 0; i < ladder_depth; i++ )
310 {
311 /* Start deriving material from the master key (if i=0) or from
312 * the current intermediate key (if i>0). */
313 PSA_CHECK( psa_key_derivation(
314 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100315 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200316 KDF_ALG,
317 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH,
318 (uint8_t*) ladder[i], strlen( ladder[i] ),
319 KEY_SIZE_BYTES ) );
320 /* When the parent key is not the master key, destroy it,
321 * since it is no longer needed. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100322 PSA_CHECK( psa_close_key( *key_handle ) );
323 *key_handle = 0;
324 PSA_CHECK( psa_allocate_key( PSA_KEY_TYPE_DERIVE,
325 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
326 key_handle ) );
327 PSA_CHECK( psa_set_key_policy( *key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200328 /* Use the generator obtained from the parent key to create
329 * the next intermediate key. */
330 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100331 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200332 PSA_KEY_TYPE_DERIVE,
333 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
334 &generator ) );
335 PSA_CHECK( psa_generator_abort( &generator ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200336 }
337
338exit:
339 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100340 if( status != PSA_SUCCESS )
341 {
342 psa_close_key( *key_handle );
343 *key_handle = 0;
344 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200345 return( status );
346}
347
348/* Derive a wrapping key from the last intermediate key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100349static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
350 psa_key_handle_t derived_key_handle,
351 psa_key_handle_t *wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200352{
353 psa_status_t status = PSA_SUCCESS;
354 psa_key_policy_t policy;
355 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
356
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100357 *wrapping_key_handle = 0;
358 PSA_CHECK( psa_allocate_key( PSA_KEY_TYPE_AES, WRAPPING_KEY_BITS,
359 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200360 psa_key_policy_init( &policy );
361 psa_key_policy_set_usage( &policy, usage, WRAPPING_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100362 PSA_CHECK( psa_set_key_policy( *wrapping_key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200363
364 PSA_CHECK( psa_key_derivation(
365 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100366 derived_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200367 KDF_ALG,
368 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH,
369 NULL, 0,
370 PSA_BITS_TO_BYTES( WRAPPING_KEY_BITS ) ) );
371 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100372 *wrapping_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200373 PSA_KEY_TYPE_AES,
374 WRAPPING_KEY_BITS,
375 &generator ) );
376
377exit:
378 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100379 if( status != PSA_SUCCESS )
380 {
381 psa_close_key( *wrapping_key_handle );
382 *wrapping_key_handle = 0;
383 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200384 return( status );
385}
386
387static psa_status_t wrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100388 const char *output_file_name,
389 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200390{
391 psa_status_t status;
392 FILE *input_file = NULL;
393 FILE *output_file = NULL;
394 long input_position;
395 size_t input_size;
396 size_t buffer_size;
397 unsigned char *buffer = NULL;
398 size_t ciphertext_size;
399 wrapped_data_header_t header;
400
401 /* Find the size of the data to wrap. */
402 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
403 SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
404 SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
405#if LONG_MAX > SIZE_MAX
406 if( input_position > SIZE_MAX )
407 {
408 mbedtls_printf( "Input file too large.\n" );
409 status = DEMO_ERROR;
410 goto exit;
411 }
412#endif
413 input_size = input_position;
414 buffer_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, input_size );
415 /* Check for integer overflow. */
416 if( buffer_size < input_size )
417 {
418 mbedtls_printf( "Input file too large.\n" );
419 status = DEMO_ERROR;
420 goto exit;
421 }
422
423 /* Load the data to wrap. */
424 SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
425 SYS_CHECK( ( buffer = mbedtls_calloc( 1, buffer_size ) ) != NULL );
426 SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
427 SYS_CHECK( fclose( input_file ) == 0 );
428 input_file = NULL;
429
430 /* Construct a header. */
431 memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
432 header.ad_size = sizeof( header );
433 header.payload_size = input_size;
434
435 /* Wrap the data. */
436 PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100437 PSA_CHECK( psa_aead_encrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200438 header.iv, WRAPPING_IV_SIZE,
439 (uint8_t *) &header, sizeof( header ),
440 buffer, input_size,
441 buffer, buffer_size,
442 &ciphertext_size ) );
443
444 /* Write the output. */
445 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
446 SYS_CHECK( fwrite( &header, 1, sizeof( header ),
447 output_file ) == sizeof( header ) );
448 SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
449 output_file ) == ciphertext_size );
450 SYS_CHECK( fclose( output_file ) == 0 );
451 output_file = NULL;
452
453exit:
454 if( input_file != NULL )
455 fclose( input_file );
456 if( output_file != NULL )
457 fclose( output_file );
458 if( buffer != NULL )
459 mbedtls_platform_zeroize( buffer, buffer_size );
460 mbedtls_free( buffer );
461 return( status );
462}
463
464static psa_status_t unwrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100465 const char *output_file_name,
466 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200467{
468 psa_status_t status;
469 FILE *input_file = NULL;
470 FILE *output_file = NULL;
471 unsigned char *buffer = NULL;
472 size_t ciphertext_size;
473 size_t plaintext_size;
474 wrapped_data_header_t header;
475 unsigned char extra_byte;
476
477 /* Load and validate the header. */
478 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
479 SYS_CHECK( fread( &header, 1, sizeof( header ),
480 input_file ) == sizeof( header ) );
481 if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
482 WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
483 {
484 mbedtls_printf( "The input does not start with a valid magic header.\n" );
485 status = DEMO_ERROR;
486 goto exit;
487 }
488 if( header.ad_size != sizeof( header ) )
489 {
490 mbedtls_printf( "The header size is not correct.\n" );
491 status = DEMO_ERROR;
492 goto exit;
493 }
494 ciphertext_size =
495 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, header.payload_size );
496 /* Check for integer overflow. */
497 if( ciphertext_size < header.payload_size )
498 {
499 mbedtls_printf( "Input file too large.\n" );
500 status = DEMO_ERROR;
501 goto exit;
502 }
503
504 /* Load the payload data. */
505 SYS_CHECK( ( buffer = mbedtls_calloc( 1, ciphertext_size ) ) != NULL );
506 SYS_CHECK( fread( buffer, 1, ciphertext_size,
507 input_file ) == ciphertext_size );
508 if( fread( &extra_byte, 1, 1, input_file ) != 0 )
509 {
510 mbedtls_printf( "Extra garbage after ciphertext\n" );
511 status = DEMO_ERROR;
512 goto exit;
513 }
514 SYS_CHECK( fclose( input_file ) == 0 );
515 input_file = NULL;
516
517 /* Unwrap the data. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100518 PSA_CHECK( psa_aead_decrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200519 header.iv, WRAPPING_IV_SIZE,
520 (uint8_t *) &header, sizeof( header ),
521 buffer, ciphertext_size,
522 buffer, ciphertext_size,
523 &plaintext_size ) );
524 if( plaintext_size != header.payload_size )
525 {
526 mbedtls_printf( "Incorrect payload size in the header.\n" );
527 status = DEMO_ERROR;
528 goto exit;
529 }
530
531 /* Write the output. */
532 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
533 SYS_CHECK( fwrite( buffer, 1, plaintext_size,
534 output_file ) == plaintext_size );
535 SYS_CHECK( fclose( output_file ) == 0 );
536 output_file = NULL;
537
538exit:
539 if( input_file != NULL )
540 fclose( input_file );
541 if( output_file != NULL )
542 fclose( output_file );
543 if( buffer != NULL )
544 mbedtls_platform_zeroize( buffer, ciphertext_size );
545 mbedtls_free( buffer );
546 return( status );
547}
548
549static psa_status_t run( enum program_mode mode,
550 const char *key_file_name,
551 const char *ladder[], size_t ladder_depth,
552 const char *input_file_name,
553 const char *output_file_name )
554{
555 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100556 psa_key_handle_t derivation_key_handle = 0;
557 psa_key_handle_t wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200558
559 /* Initialize the PSA crypto library. */
560 PSA_CHECK( psa_crypto_init( ) );
561
562 /* Generate mode is unlike the others. Generate the master key and exit. */
563 if( mode == MODE_GENERATE )
564 return( generate( key_file_name ) );
565
566 /* Read the master key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100567 PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200568 KDF_ALG,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100569 key_file_name,
570 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200571
572 /* Calculate the derived key for this session. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100573 PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
574 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200575
576 switch( mode )
577 {
578 case MODE_SAVE:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100579 PSA_CHECK( save_key( derivation_key_handle, output_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200580 break;
581 case MODE_UNWRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100582 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
583 derivation_key_handle,
584 &wrapping_key_handle ) );
585 PSA_CHECK( unwrap_data( input_file_name, output_file_name,
586 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200587 break;
588 case MODE_WRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100589 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
590 derivation_key_handle,
591 &wrapping_key_handle ) );
592 PSA_CHECK( wrap_data( input_file_name, output_file_name,
593 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200594 break;
595 default:
596 /* Unreachable but some compilers don't realize it. */
597 break;
598 }
599
600exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100601 /* Close any remaining key. Deinitializing the crypto library would do
602 * this anyway, but explicitly closing handles makes the code easier
603 * to reuse. */
604 (void) psa_close_key( derivation_key_handle );
605 (void) psa_close_key( wrapping_key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200606 /* Deinitialize the PSA crypto library. */
607 mbedtls_psa_crypto_free( );
608 return( status );
609}
610
611static void usage( void )
612{
613 mbedtls_printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
614 mbedtls_printf( "Demonstrate the usage of a key derivation ladder.\n" );
615 mbedtls_printf( "\n" );
616 mbedtls_printf( "Modes:\n" );
617 mbedtls_printf( " generate Generate the master key\n" );
618 mbedtls_printf( " save Save the derived key\n" );
619 mbedtls_printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
620 mbedtls_printf( " wrap Wrap (encrypt) input with the derived key\n" );
621 mbedtls_printf( "\n" );
622 mbedtls_printf( "Options:\n" );
623 mbedtls_printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
624 mbedtls_printf( " master=FILENAME File containing the master key (default: master.key)\n" );
625 mbedtls_printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
626 mbedtls_printf( " label=TEXT Label for the key derivation.\n" );
627 mbedtls_printf( " This may be repeated multiple times.\n" );
628 mbedtls_printf( " To get the same key, you must use the same master key\n" );
629 mbedtls_printf( " and the same sequence of labels.\n" );
630}
631
632int main( int argc, char *argv[] )
633{
634 char *key_file_name = "master.key";
635 char *input_file_name = NULL;
636 char *output_file_name = NULL;
637 const char *ladder[MAX_LADDER_DEPTH];
638 size_t ladder_depth = 0;
639 int i;
640 enum program_mode mode;
641 psa_status_t status;
642
643 if( argc <= 1 ||
644 strcmp( argv[1], "help" ) == 0 ||
645 strcmp( argv[1], "-help" ) == 0 ||
646 strcmp( argv[1], "--help" ) == 0 )
647 {
648 usage( );
649 return( MBEDTLS_EXIT_SUCCESS );
650 }
651
652 for( i = 2; i < argc; i++ )
653 {
654 char *q = strchr( argv[i], '=' );
655 if( q == NULL )
656 {
657 mbedtls_printf( "Missing argument to option %s\n", argv[i] );
658 goto usage_failure;
659 }
660 *q = 0;
661 ++q;
662 if( strcmp( argv[i], "input" ) == 0 )
663 input_file_name = q;
664 else if( strcmp( argv[i], "label" ) == 0 )
665 {
666 if( ladder_depth == MAX_LADDER_DEPTH )
667 {
668 mbedtls_printf( "Maximum ladder depth %u exceeded.\n",
669 (unsigned) MAX_LADDER_DEPTH );
670 return( MBEDTLS_EXIT_FAILURE );
671 }
672 ladder[ladder_depth] = q;
673 ++ladder_depth;
674 }
675 else if( strcmp( argv[i], "master" ) == 0 )
676 key_file_name = q;
677 else if( strcmp( argv[i], "output" ) == 0 )
678 output_file_name = q;
679 else
680 {
681 mbedtls_printf( "Unknown option: %s\n", argv[i] );
682 goto usage_failure;
683 }
684 }
685
686 if( strcmp( argv[1], "generate" ) == 0 )
687 mode = MODE_GENERATE;
688 else if( strcmp( argv[1], "save" ) == 0 )
689 mode = MODE_SAVE;
690 else if( strcmp( argv[1], "unwrap" ) == 0 )
691 mode = MODE_UNWRAP;
692 else if( strcmp( argv[1], "wrap" ) == 0 )
693 mode = MODE_WRAP;
694 else
695 {
696 mbedtls_printf( "Unknown action: %s\n", argv[1] );
697 goto usage_failure;
698 }
699
700 if( input_file_name == NULL &&
701 ( mode == MODE_WRAP || mode == MODE_UNWRAP ) )
702 {
703 mbedtls_printf( "Required argument missing: input\n" );
704 return( DEMO_ERROR );
705 }
706 if( output_file_name == NULL &&
707 ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) )
708 {
709 mbedtls_printf( "Required argument missing: output\n" );
710 return( DEMO_ERROR );
711 }
712
713 status = run( mode, key_file_name,
714 ladder, ladder_depth,
715 input_file_name, output_file_name );
716 return( status == PSA_SUCCESS ?
717 MBEDTLS_EXIT_SUCCESS :
718 MBEDTLS_EXIT_FAILURE );
719
720usage_failure:
721 usage( );
722 return( MBEDTLS_EXIT_FAILURE );
723}
724#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */