blob: 66f66fc2e5f2ffa4992876986ca42c84f9e7ebd7 [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 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_set_usage( &policy,
218 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
219 KDF_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100220 PSA_CHECK( psa_set_key_policy( key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200221
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100222 PSA_CHECK( psa_generate_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200223 PSA_KEY_TYPE_DERIVE,
224 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
225 NULL, 0 ) );
226
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100227 PSA_CHECK( save_key( key_handle, key_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200228
229exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100230 (void) psa_destroy_key( key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200231 return( status );
232}
233
234/* Load the master key from a file.
235 *
236 * In the real world, this master key would be stored in an internal memory
237 * and the storage would be managed by the keystore capability of the PSA
238 * crypto library. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100239static psa_status_t import_key_from_file( psa_key_usage_t usage,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200240 psa_algorithm_t alg,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100241 const char *key_file_name,
242 psa_key_handle_t *master_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200243{
244 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000245 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200246 uint8_t key_data[KEY_SIZE_BYTES];
247 size_t key_size;
248 FILE *key_file = NULL;
249 unsigned char extra_byte;
250
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100251 *master_key_handle = 0;
252
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200253 SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
254 SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
255 key_file ) ) != 0 );
256 if( fread( &extra_byte, 1, 1, key_file ) != 0 )
257 {
258 mbedtls_printf( "Key file too large (max: %u).\n",
259 (unsigned) sizeof( key_data ) );
260 status = DEMO_ERROR;
261 goto exit;
262 }
263 SYS_CHECK( fclose( key_file ) == 0 );
264 key_file = NULL;
265
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100266 PSA_CHECK( psa_allocate_key( PSA_KEY_TYPE_DERIVE,
267 PSA_BYTES_TO_BITS( key_size ),
268 master_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200269 psa_key_policy_set_usage( &policy, usage, alg );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100270 PSA_CHECK( psa_set_key_policy( *master_key_handle, &policy ) );
271 PSA_CHECK( psa_import_key( *master_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200272 PSA_KEY_TYPE_DERIVE,
273 key_data, key_size ) );
274exit:
275 if( key_file != NULL )
276 fclose( key_file );
277 mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100278 if( status != PSA_SUCCESS )
279 {
280 /* If psa_allocate_key hasn't been called yet or has failed,
281 * *master_key_handle is 0. psa_destroy_key(0) is guaranteed to do
282 * nothing and return PSA_ERROR_INVALID_HANDLE. */
283 (void) psa_destroy_key( *master_key_handle );
284 *master_key_handle = 0;
285 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200286 return( status );
287}
288
289/* Derive the intermediate keys, using the list of labels provided on
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100290 * the command line. On input, *key_handle is a handle to the master key.
291 * This function closes the master key. On successful output, *key_handle
292 * is a handle to the final derived key. */
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200293static psa_status_t derive_key_ladder( const char *ladder[],
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100294 size_t ladder_depth,
295 psa_key_handle_t *key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200296{
297 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000298 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200299 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200300 size_t i;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200301 psa_key_policy_set_usage( &policy,
302 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
303 KDF_ALG );
304
305 /* For each label in turn, ... */
306 for( i = 0; i < ladder_depth; i++ )
307 {
308 /* Start deriving material from the master key (if i=0) or from
309 * the current intermediate key (if i>0). */
310 PSA_CHECK( psa_key_derivation(
311 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100312 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200313 KDF_ALG,
314 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH,
315 (uint8_t*) ladder[i], strlen( ladder[i] ),
316 KEY_SIZE_BYTES ) );
317 /* When the parent key is not the master key, destroy it,
318 * since it is no longer needed. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100319 PSA_CHECK( psa_close_key( *key_handle ) );
320 *key_handle = 0;
321 PSA_CHECK( psa_allocate_key( PSA_KEY_TYPE_DERIVE,
322 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
323 key_handle ) );
324 PSA_CHECK( psa_set_key_policy( *key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200325 /* Use the generator obtained from the parent key to create
326 * the next intermediate key. */
327 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100328 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200329 PSA_KEY_TYPE_DERIVE,
330 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
331 &generator ) );
332 PSA_CHECK( psa_generator_abort( &generator ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200333 }
334
335exit:
336 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100337 if( status != PSA_SUCCESS )
338 {
339 psa_close_key( *key_handle );
340 *key_handle = 0;
341 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200342 return( status );
343}
344
345/* Derive a wrapping key from the last intermediate key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100346static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
347 psa_key_handle_t derived_key_handle,
348 psa_key_handle_t *wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200349{
350 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000351 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200352 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
353
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100354 *wrapping_key_handle = 0;
355 PSA_CHECK( psa_allocate_key( PSA_KEY_TYPE_AES, WRAPPING_KEY_BITS,
356 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200357 psa_key_policy_set_usage( &policy, usage, WRAPPING_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100358 PSA_CHECK( psa_set_key_policy( *wrapping_key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200359
360 PSA_CHECK( psa_key_derivation(
361 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100362 derived_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200363 KDF_ALG,
364 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH,
365 NULL, 0,
366 PSA_BITS_TO_BYTES( WRAPPING_KEY_BITS ) ) );
367 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100368 *wrapping_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200369 PSA_KEY_TYPE_AES,
370 WRAPPING_KEY_BITS,
371 &generator ) );
372
373exit:
374 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100375 if( status != PSA_SUCCESS )
376 {
377 psa_close_key( *wrapping_key_handle );
378 *wrapping_key_handle = 0;
379 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200380 return( status );
381}
382
383static psa_status_t wrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100384 const char *output_file_name,
385 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200386{
387 psa_status_t status;
388 FILE *input_file = NULL;
389 FILE *output_file = NULL;
390 long input_position;
391 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100392 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200393 unsigned char *buffer = NULL;
394 size_t ciphertext_size;
395 wrapped_data_header_t header;
396
397 /* Find the size of the data to wrap. */
398 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
399 SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
400 SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
401#if LONG_MAX > SIZE_MAX
402 if( input_position > SIZE_MAX )
403 {
404 mbedtls_printf( "Input file too large.\n" );
405 status = DEMO_ERROR;
406 goto exit;
407 }
408#endif
409 input_size = input_position;
410 buffer_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, input_size );
411 /* Check for integer overflow. */
412 if( buffer_size < input_size )
413 {
414 mbedtls_printf( "Input file too large.\n" );
415 status = DEMO_ERROR;
416 goto exit;
417 }
418
419 /* Load the data to wrap. */
420 SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
421 SYS_CHECK( ( buffer = mbedtls_calloc( 1, buffer_size ) ) != NULL );
422 SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
423 SYS_CHECK( fclose( input_file ) == 0 );
424 input_file = NULL;
425
426 /* Construct a header. */
427 memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
428 header.ad_size = sizeof( header );
429 header.payload_size = input_size;
430
431 /* Wrap the data. */
432 PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100433 PSA_CHECK( psa_aead_encrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200434 header.iv, WRAPPING_IV_SIZE,
435 (uint8_t *) &header, sizeof( header ),
436 buffer, input_size,
437 buffer, buffer_size,
438 &ciphertext_size ) );
439
440 /* Write the output. */
441 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
442 SYS_CHECK( fwrite( &header, 1, sizeof( header ),
443 output_file ) == sizeof( header ) );
444 SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
445 output_file ) == ciphertext_size );
446 SYS_CHECK( fclose( output_file ) == 0 );
447 output_file = NULL;
448
449exit:
450 if( input_file != NULL )
451 fclose( input_file );
452 if( output_file != NULL )
453 fclose( output_file );
454 if( buffer != NULL )
455 mbedtls_platform_zeroize( buffer, buffer_size );
456 mbedtls_free( buffer );
457 return( status );
458}
459
460static psa_status_t unwrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100461 const char *output_file_name,
462 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200463{
464 psa_status_t status;
465 FILE *input_file = NULL;
466 FILE *output_file = NULL;
467 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100468 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200469 size_t plaintext_size;
470 wrapped_data_header_t header;
471 unsigned char extra_byte;
472
473 /* Load and validate the header. */
474 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
475 SYS_CHECK( fread( &header, 1, sizeof( header ),
476 input_file ) == sizeof( header ) );
477 if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
478 WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
479 {
480 mbedtls_printf( "The input does not start with a valid magic header.\n" );
481 status = DEMO_ERROR;
482 goto exit;
483 }
484 if( header.ad_size != sizeof( header ) )
485 {
486 mbedtls_printf( "The header size is not correct.\n" );
487 status = DEMO_ERROR;
488 goto exit;
489 }
490 ciphertext_size =
491 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, header.payload_size );
492 /* Check for integer overflow. */
493 if( ciphertext_size < header.payload_size )
494 {
495 mbedtls_printf( "Input file too large.\n" );
496 status = DEMO_ERROR;
497 goto exit;
498 }
499
500 /* Load the payload data. */
501 SYS_CHECK( ( buffer = mbedtls_calloc( 1, ciphertext_size ) ) != NULL );
502 SYS_CHECK( fread( buffer, 1, ciphertext_size,
503 input_file ) == ciphertext_size );
504 if( fread( &extra_byte, 1, 1, input_file ) != 0 )
505 {
506 mbedtls_printf( "Extra garbage after ciphertext\n" );
507 status = DEMO_ERROR;
508 goto exit;
509 }
510 SYS_CHECK( fclose( input_file ) == 0 );
511 input_file = NULL;
512
513 /* Unwrap the data. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100514 PSA_CHECK( psa_aead_decrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200515 header.iv, WRAPPING_IV_SIZE,
516 (uint8_t *) &header, sizeof( header ),
517 buffer, ciphertext_size,
518 buffer, ciphertext_size,
519 &plaintext_size ) );
520 if( plaintext_size != header.payload_size )
521 {
522 mbedtls_printf( "Incorrect payload size in the header.\n" );
523 status = DEMO_ERROR;
524 goto exit;
525 }
526
527 /* Write the output. */
528 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
529 SYS_CHECK( fwrite( buffer, 1, plaintext_size,
530 output_file ) == plaintext_size );
531 SYS_CHECK( fclose( output_file ) == 0 );
532 output_file = NULL;
533
534exit:
535 if( input_file != NULL )
536 fclose( input_file );
537 if( output_file != NULL )
538 fclose( output_file );
539 if( buffer != NULL )
540 mbedtls_platform_zeroize( buffer, ciphertext_size );
541 mbedtls_free( buffer );
542 return( status );
543}
544
545static psa_status_t run( enum program_mode mode,
546 const char *key_file_name,
547 const char *ladder[], size_t ladder_depth,
548 const char *input_file_name,
549 const char *output_file_name )
550{
551 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100552 psa_key_handle_t derivation_key_handle = 0;
553 psa_key_handle_t wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200554
555 /* Initialize the PSA crypto library. */
556 PSA_CHECK( psa_crypto_init( ) );
557
558 /* Generate mode is unlike the others. Generate the master key and exit. */
559 if( mode == MODE_GENERATE )
560 return( generate( key_file_name ) );
561
562 /* Read the master key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100563 PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200564 KDF_ALG,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100565 key_file_name,
566 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200567
568 /* Calculate the derived key for this session. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100569 PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
570 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200571
572 switch( mode )
573 {
574 case MODE_SAVE:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100575 PSA_CHECK( save_key( derivation_key_handle, output_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200576 break;
577 case MODE_UNWRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100578 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
579 derivation_key_handle,
580 &wrapping_key_handle ) );
581 PSA_CHECK( unwrap_data( input_file_name, output_file_name,
582 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200583 break;
584 case MODE_WRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100585 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
586 derivation_key_handle,
587 &wrapping_key_handle ) );
588 PSA_CHECK( wrap_data( input_file_name, output_file_name,
589 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200590 break;
591 default:
592 /* Unreachable but some compilers don't realize it. */
593 break;
594 }
595
596exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100597 /* Close any remaining key. Deinitializing the crypto library would do
598 * this anyway, but explicitly closing handles makes the code easier
599 * to reuse. */
600 (void) psa_close_key( derivation_key_handle );
601 (void) psa_close_key( wrapping_key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200602 /* Deinitialize the PSA crypto library. */
603 mbedtls_psa_crypto_free( );
604 return( status );
605}
606
607static void usage( void )
608{
609 mbedtls_printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
610 mbedtls_printf( "Demonstrate the usage of a key derivation ladder.\n" );
611 mbedtls_printf( "\n" );
612 mbedtls_printf( "Modes:\n" );
613 mbedtls_printf( " generate Generate the master key\n" );
614 mbedtls_printf( " save Save the derived key\n" );
615 mbedtls_printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
616 mbedtls_printf( " wrap Wrap (encrypt) input with the derived key\n" );
617 mbedtls_printf( "\n" );
618 mbedtls_printf( "Options:\n" );
619 mbedtls_printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
620 mbedtls_printf( " master=FILENAME File containing the master key (default: master.key)\n" );
621 mbedtls_printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
622 mbedtls_printf( " label=TEXT Label for the key derivation.\n" );
623 mbedtls_printf( " This may be repeated multiple times.\n" );
624 mbedtls_printf( " To get the same key, you must use the same master key\n" );
625 mbedtls_printf( " and the same sequence of labels.\n" );
626}
627
628int main( int argc, char *argv[] )
629{
630 char *key_file_name = "master.key";
631 char *input_file_name = NULL;
632 char *output_file_name = NULL;
633 const char *ladder[MAX_LADDER_DEPTH];
634 size_t ladder_depth = 0;
635 int i;
636 enum program_mode mode;
637 psa_status_t status;
638
639 if( argc <= 1 ||
640 strcmp( argv[1], "help" ) == 0 ||
641 strcmp( argv[1], "-help" ) == 0 ||
642 strcmp( argv[1], "--help" ) == 0 )
643 {
644 usage( );
645 return( MBEDTLS_EXIT_SUCCESS );
646 }
647
648 for( i = 2; i < argc; i++ )
649 {
650 char *q = strchr( argv[i], '=' );
651 if( q == NULL )
652 {
653 mbedtls_printf( "Missing argument to option %s\n", argv[i] );
654 goto usage_failure;
655 }
656 *q = 0;
657 ++q;
658 if( strcmp( argv[i], "input" ) == 0 )
659 input_file_name = q;
660 else if( strcmp( argv[i], "label" ) == 0 )
661 {
662 if( ladder_depth == MAX_LADDER_DEPTH )
663 {
664 mbedtls_printf( "Maximum ladder depth %u exceeded.\n",
665 (unsigned) MAX_LADDER_DEPTH );
666 return( MBEDTLS_EXIT_FAILURE );
667 }
668 ladder[ladder_depth] = q;
669 ++ladder_depth;
670 }
671 else if( strcmp( argv[i], "master" ) == 0 )
672 key_file_name = q;
673 else if( strcmp( argv[i], "output" ) == 0 )
674 output_file_name = q;
675 else
676 {
677 mbedtls_printf( "Unknown option: %s\n", argv[i] );
678 goto usage_failure;
679 }
680 }
681
682 if( strcmp( argv[1], "generate" ) == 0 )
683 mode = MODE_GENERATE;
684 else if( strcmp( argv[1], "save" ) == 0 )
685 mode = MODE_SAVE;
686 else if( strcmp( argv[1], "unwrap" ) == 0 )
687 mode = MODE_UNWRAP;
688 else if( strcmp( argv[1], "wrap" ) == 0 )
689 mode = MODE_WRAP;
690 else
691 {
692 mbedtls_printf( "Unknown action: %s\n", argv[1] );
693 goto usage_failure;
694 }
695
696 if( input_file_name == NULL &&
697 ( mode == MODE_WRAP || mode == MODE_UNWRAP ) )
698 {
699 mbedtls_printf( "Required argument missing: input\n" );
700 return( DEMO_ERROR );
701 }
702 if( output_file_name == NULL &&
703 ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) )
704 {
705 mbedtls_printf( "Required argument missing: output\n" );
706 return( DEMO_ERROR );
707 }
708
709 status = run( mode, key_file_name,
710 ladder, ladder_depth,
711 input_file_name, output_file_name );
712 return( status == PSA_SUCCESS ?
713 MBEDTLS_EXIT_SUCCESS :
714 MBEDTLS_EXIT_FAILURE );
715
716usage_failure:
717 usage( );
718 return( MBEDTLS_EXIT_FAILURE );
719}
720#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */