blob: 23c23475365b2a885f670c911b26b2a7d7c22e42 [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
Gilles Peskinef0fa4362018-07-16 17:08:43 +020060#include <stdlib.h>
Gilles Peskinef0fa4362018-07-16 17:08:43 +020061#include <stdio.h>
62#include <string.h>
63
64#include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
65
66/* If the build options we need are not enabled, compile a placeholder. */
67#if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
68 !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
69 !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO)
70int main( void )
71{
Jaeden Amerofa30c332018-12-21 18:42:18 +000072 printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
73 "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
74 "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO not defined.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +020075 return( 0 );
76}
77#else
78
79/* The real program starts here. */
80
81
82
83#include <psa/crypto.h>
84
85/* Run a system function and bail out if it fails. */
86#define SYS_CHECK( expr ) \
87 do \
88 { \
89 if( ! ( expr ) ) \
90 { \
91 perror( #expr ); \
92 status = DEMO_ERROR; \
93 goto exit; \
94 } \
95 } \
96 while( 0 )
97
98/* Run a PSA function and bail out if it fails. */
99#define PSA_CHECK( expr ) \
100 do \
101 { \
102 status = ( expr ); \
103 if( status != PSA_SUCCESS ) \
104 { \
Jaeden Amerofa30c332018-12-21 18:42:18 +0000105 printf( "Error %d at line %u: %s\n", \
106 (int) status, \
107 __LINE__, \
108 #expr ); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200109 goto exit; \
110 } \
111 } \
112 while( 0 )
113
114/* To report operational errors in this program, use an error code that is
115 * different from every PSA error code. */
116#define DEMO_ERROR 120
117
118/* The maximum supported key ladder depth. */
119#define MAX_LADDER_DEPTH 10
120
121/* Salt to use when deriving an intermediate key. */
122#define DERIVE_KEY_SALT ( (uint8_t *) "key_ladder_demo.derive" )
123#define DERIVE_KEY_SALT_LENGTH ( strlen( (const char*) DERIVE_KEY_SALT ) )
124
125/* Salt to use when deriving a wrapping key. */
126#define WRAPPING_KEY_SALT ( (uint8_t *) "key_ladder_demo.wrap" )
127#define WRAPPING_KEY_SALT_LENGTH ( strlen( (const char*) WRAPPING_KEY_SALT ) )
128
129/* Size of the key derivation keys (applies both to the master key and
130 * to intermediate keys). */
131#define KEY_SIZE_BYTES 40
132
133/* Algorithm for key derivation. */
134#define KDF_ALG PSA_ALG_HKDF( PSA_ALG_SHA_256 )
135
136/* Type and size of the key used to wrap data. */
137#define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
138#define WRAPPING_KEY_BITS 128
139
140/* Cipher mode used to wrap data. */
141#define WRAPPING_ALG PSA_ALG_CCM
142
143/* Nonce size used to wrap data. */
144#define WRAPPING_IV_SIZE 13
145
146/* Header used in files containing wrapped data. We'll save this header
147 * directly without worrying about data representation issues such as
148 * integer sizes and endianness, because the data is meant to be read
149 * back by the same program on the same machine. */
150#define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
151#define WRAPPED_DATA_MAGIC_LENGTH ( sizeof( WRAPPED_DATA_MAGIC ) )
152typedef struct
153{
154 char magic[WRAPPED_DATA_MAGIC_LENGTH];
155 size_t ad_size; /* Size of the additional data, which is this header. */
156 size_t payload_size; /* Size of the encrypted data. */
157 /* Store the IV inside the additional data. It's convenient. */
158 uint8_t iv[WRAPPING_IV_SIZE];
159} wrapped_data_header_t;
160
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200161/* The modes that this program can operate in (see usage). */
162enum program_mode
163{
164 MODE_GENERATE,
165 MODE_SAVE,
166 MODE_UNWRAP,
167 MODE_WRAP
168};
169
170/* Save a key to a file. In the real world, you may want to export a derived
171 * key sometimes, to share it with another party. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100172static psa_status_t save_key( psa_key_handle_t key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200173 const char *output_file_name )
174{
175 psa_status_t status = PSA_SUCCESS;
176 uint8_t key_data[KEY_SIZE_BYTES];
177 size_t key_size;
178 FILE *key_file = NULL;
179
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100180 PSA_CHECK( psa_export_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200181 key_data, sizeof( key_data ),
182 &key_size ) );
183 SYS_CHECK( ( key_file = fopen( output_file_name, "wb" ) ) != NULL );
184 SYS_CHECK( fwrite( key_data, 1, key_size, key_file ) == key_size );
185 SYS_CHECK( fclose( key_file ) == 0 );
186 key_file = NULL;
187
188exit:
189 if( key_file != NULL)
190 fclose( key_file );
191 return( status );
192}
193
194/* Generate a master key for use in this demo.
195 *
196 * Normally a master key would be non-exportable. For the purpose of this
197 * demo, we want to save it to a file, to avoid relying on the keystore
198 * capability of the PSA crypto library. */
199static psa_status_t generate( const char *key_file_name )
200{
201 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100202 psa_key_handle_t key_handle = 0;
Jaeden Amero70261c52019-01-04 11:47:20 +0000203 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200204
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100205 PSA_CHECK( psa_allocate_key( &key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200206 psa_key_policy_set_usage( &policy,
207 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
208 KDF_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100209 PSA_CHECK( psa_set_key_policy( key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200210
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100211 PSA_CHECK( psa_generate_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200212 PSA_KEY_TYPE_DERIVE,
213 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
214 NULL, 0 ) );
215
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100216 PSA_CHECK( save_key( key_handle, key_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200217
218exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100219 (void) psa_destroy_key( key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200220 return( status );
221}
222
223/* Load the master key from a file.
224 *
225 * In the real world, this master key would be stored in an internal memory
226 * and the storage would be managed by the keystore capability of the PSA
227 * crypto library. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100228static psa_status_t import_key_from_file( psa_key_usage_t usage,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200229 psa_algorithm_t alg,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100230 const char *key_file_name,
231 psa_key_handle_t *master_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200232{
233 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000234 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200235 uint8_t key_data[KEY_SIZE_BYTES];
236 size_t key_size;
237 FILE *key_file = NULL;
238 unsigned char extra_byte;
239
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100240 *master_key_handle = 0;
241
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200242 SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
243 SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
244 key_file ) ) != 0 );
245 if( fread( &extra_byte, 1, 1, key_file ) != 0 )
246 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000247 printf( "Key file too large (max: %u).\n",
248 (unsigned) sizeof( key_data ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200249 status = DEMO_ERROR;
250 goto exit;
251 }
252 SYS_CHECK( fclose( key_file ) == 0 );
253 key_file = NULL;
254
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100255 PSA_CHECK( psa_allocate_key( master_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200256 psa_key_policy_set_usage( &policy, usage, alg );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100257 PSA_CHECK( psa_set_key_policy( *master_key_handle, &policy ) );
258 PSA_CHECK( psa_import_key( *master_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200259 PSA_KEY_TYPE_DERIVE,
260 key_data, key_size ) );
261exit:
262 if( key_file != NULL )
263 fclose( key_file );
264 mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100265 if( status != PSA_SUCCESS )
266 {
267 /* If psa_allocate_key hasn't been called yet or has failed,
268 * *master_key_handle is 0. psa_destroy_key(0) is guaranteed to do
269 * nothing and return PSA_ERROR_INVALID_HANDLE. */
270 (void) psa_destroy_key( *master_key_handle );
271 *master_key_handle = 0;
272 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200273 return( status );
274}
275
276/* Derive the intermediate keys, using the list of labels provided on
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100277 * the command line. On input, *key_handle is a handle to the master key.
278 * This function closes the master key. On successful output, *key_handle
279 * is a handle to the final derived key. */
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200280static psa_status_t derive_key_ladder( const char *ladder[],
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100281 size_t ladder_depth,
282 psa_key_handle_t *key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200283{
284 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000285 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200286 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200287 size_t i;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200288 psa_key_policy_set_usage( &policy,
289 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
290 KDF_ALG );
291
292 /* For each label in turn, ... */
293 for( i = 0; i < ladder_depth; i++ )
294 {
295 /* Start deriving material from the master key (if i=0) or from
296 * the current intermediate key (if i>0). */
297 PSA_CHECK( psa_key_derivation(
298 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100299 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200300 KDF_ALG,
301 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH,
302 (uint8_t*) ladder[i], strlen( ladder[i] ),
303 KEY_SIZE_BYTES ) );
304 /* When the parent key is not the master key, destroy it,
305 * since it is no longer needed. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100306 PSA_CHECK( psa_close_key( *key_handle ) );
307 *key_handle = 0;
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100308 PSA_CHECK( psa_allocate_key( key_handle ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100309 PSA_CHECK( psa_set_key_policy( *key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200310 /* Use the generator obtained from the parent key to create
311 * the next intermediate key. */
312 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100313 *key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200314 PSA_KEY_TYPE_DERIVE,
315 PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ),
316 &generator ) );
317 PSA_CHECK( psa_generator_abort( &generator ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200318 }
319
320exit:
321 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100322 if( status != PSA_SUCCESS )
323 {
324 psa_close_key( *key_handle );
325 *key_handle = 0;
326 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200327 return( status );
328}
329
330/* Derive a wrapping key from the last intermediate key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100331static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
332 psa_key_handle_t derived_key_handle,
333 psa_key_handle_t *wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200334{
335 psa_status_t status = PSA_SUCCESS;
Jaeden Amero70261c52019-01-04 11:47:20 +0000336 psa_key_policy_t policy = PSA_KEY_POLICY_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200337 psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT;
338
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100339 *wrapping_key_handle = 0;
Gilles Peskined40c1fb2019-01-19 12:20:52 +0100340 PSA_CHECK( psa_allocate_key( wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200341 psa_key_policy_set_usage( &policy, usage, WRAPPING_ALG );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100342 PSA_CHECK( psa_set_key_policy( *wrapping_key_handle, &policy ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200343
344 PSA_CHECK( psa_key_derivation(
345 &generator,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100346 derived_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200347 KDF_ALG,
348 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH,
349 NULL, 0,
350 PSA_BITS_TO_BYTES( WRAPPING_KEY_BITS ) ) );
351 PSA_CHECK( psa_generator_import_key(
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100352 *wrapping_key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200353 PSA_KEY_TYPE_AES,
354 WRAPPING_KEY_BITS,
355 &generator ) );
356
357exit:
358 psa_generator_abort( &generator );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100359 if( status != PSA_SUCCESS )
360 {
361 psa_close_key( *wrapping_key_handle );
362 *wrapping_key_handle = 0;
363 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200364 return( status );
365}
366
367static psa_status_t wrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100368 const char *output_file_name,
369 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200370{
371 psa_status_t status;
372 FILE *input_file = NULL;
373 FILE *output_file = NULL;
374 long input_position;
375 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100376 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200377 unsigned char *buffer = NULL;
378 size_t ciphertext_size;
379 wrapped_data_header_t header;
380
381 /* Find the size of the data to wrap. */
382 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
383 SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
384 SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
385#if LONG_MAX > SIZE_MAX
386 if( input_position > SIZE_MAX )
387 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000388 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200389 status = DEMO_ERROR;
390 goto exit;
391 }
392#endif
393 input_size = input_position;
394 buffer_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, input_size );
395 /* Check for integer overflow. */
396 if( buffer_size < input_size )
397 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000398 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200399 status = DEMO_ERROR;
400 goto exit;
401 }
402
403 /* Load the data to wrap. */
404 SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000405 SYS_CHECK( ( buffer = calloc( 1, buffer_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200406 SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
407 SYS_CHECK( fclose( input_file ) == 0 );
408 input_file = NULL;
409
410 /* Construct a header. */
411 memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
412 header.ad_size = sizeof( header );
413 header.payload_size = input_size;
414
415 /* Wrap the data. */
416 PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100417 PSA_CHECK( psa_aead_encrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200418 header.iv, WRAPPING_IV_SIZE,
419 (uint8_t *) &header, sizeof( header ),
420 buffer, input_size,
421 buffer, buffer_size,
422 &ciphertext_size ) );
423
424 /* Write the output. */
425 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
426 SYS_CHECK( fwrite( &header, 1, sizeof( header ),
427 output_file ) == sizeof( header ) );
428 SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
429 output_file ) == ciphertext_size );
430 SYS_CHECK( fclose( output_file ) == 0 );
431 output_file = NULL;
432
433exit:
434 if( input_file != NULL )
435 fclose( input_file );
436 if( output_file != NULL )
437 fclose( output_file );
438 if( buffer != NULL )
439 mbedtls_platform_zeroize( buffer, buffer_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000440 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200441 return( status );
442}
443
444static psa_status_t unwrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100445 const char *output_file_name,
446 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200447{
448 psa_status_t status;
449 FILE *input_file = NULL;
450 FILE *output_file = NULL;
451 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100452 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200453 size_t plaintext_size;
454 wrapped_data_header_t header;
455 unsigned char extra_byte;
456
457 /* Load and validate the header. */
458 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
459 SYS_CHECK( fread( &header, 1, sizeof( header ),
460 input_file ) == sizeof( header ) );
461 if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
462 WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
463 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000464 printf( "The input does not start with a valid magic header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200465 status = DEMO_ERROR;
466 goto exit;
467 }
468 if( header.ad_size != sizeof( header ) )
469 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000470 printf( "The header size is not correct.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200471 status = DEMO_ERROR;
472 goto exit;
473 }
474 ciphertext_size =
475 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, header.payload_size );
476 /* Check for integer overflow. */
477 if( ciphertext_size < header.payload_size )
478 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000479 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200480 status = DEMO_ERROR;
481 goto exit;
482 }
483
484 /* Load the payload data. */
Jaeden Amerofa30c332018-12-21 18:42:18 +0000485 SYS_CHECK( ( buffer = calloc( 1, ciphertext_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200486 SYS_CHECK( fread( buffer, 1, ciphertext_size,
487 input_file ) == ciphertext_size );
488 if( fread( &extra_byte, 1, 1, input_file ) != 0 )
489 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000490 printf( "Extra garbage after ciphertext\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200491 status = DEMO_ERROR;
492 goto exit;
493 }
494 SYS_CHECK( fclose( input_file ) == 0 );
495 input_file = NULL;
496
497 /* Unwrap the data. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100498 PSA_CHECK( psa_aead_decrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200499 header.iv, WRAPPING_IV_SIZE,
500 (uint8_t *) &header, sizeof( header ),
501 buffer, ciphertext_size,
502 buffer, ciphertext_size,
503 &plaintext_size ) );
504 if( plaintext_size != header.payload_size )
505 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000506 printf( "Incorrect payload size in the header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200507 status = DEMO_ERROR;
508 goto exit;
509 }
510
511 /* Write the output. */
512 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
513 SYS_CHECK( fwrite( buffer, 1, plaintext_size,
514 output_file ) == plaintext_size );
515 SYS_CHECK( fclose( output_file ) == 0 );
516 output_file = NULL;
517
518exit:
519 if( input_file != NULL )
520 fclose( input_file );
521 if( output_file != NULL )
522 fclose( output_file );
523 if( buffer != NULL )
524 mbedtls_platform_zeroize( buffer, ciphertext_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000525 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200526 return( status );
527}
528
529static psa_status_t run( enum program_mode mode,
530 const char *key_file_name,
531 const char *ladder[], size_t ladder_depth,
532 const char *input_file_name,
533 const char *output_file_name )
534{
535 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100536 psa_key_handle_t derivation_key_handle = 0;
537 psa_key_handle_t wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200538
539 /* Initialize the PSA crypto library. */
540 PSA_CHECK( psa_crypto_init( ) );
541
542 /* Generate mode is unlike the others. Generate the master key and exit. */
543 if( mode == MODE_GENERATE )
544 return( generate( key_file_name ) );
545
546 /* Read the master key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100547 PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200548 KDF_ALG,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100549 key_file_name,
550 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200551
552 /* Calculate the derived key for this session. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100553 PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
554 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200555
556 switch( mode )
557 {
558 case MODE_SAVE:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100559 PSA_CHECK( save_key( derivation_key_handle, output_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200560 break;
561 case MODE_UNWRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100562 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
563 derivation_key_handle,
564 &wrapping_key_handle ) );
565 PSA_CHECK( unwrap_data( input_file_name, output_file_name,
566 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200567 break;
568 case MODE_WRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100569 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
570 derivation_key_handle,
571 &wrapping_key_handle ) );
572 PSA_CHECK( wrap_data( input_file_name, output_file_name,
573 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200574 break;
575 default:
576 /* Unreachable but some compilers don't realize it. */
577 break;
578 }
579
580exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100581 /* Close any remaining key. Deinitializing the crypto library would do
582 * this anyway, but explicitly closing handles makes the code easier
583 * to reuse. */
584 (void) psa_close_key( derivation_key_handle );
585 (void) psa_close_key( wrapping_key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200586 /* Deinitialize the PSA crypto library. */
587 mbedtls_psa_crypto_free( );
588 return( status );
589}
590
591static void usage( void )
592{
Jaeden Amerofa30c332018-12-21 18:42:18 +0000593 printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
594 printf( "Demonstrate the usage of a key derivation ladder.\n" );
595 printf( "\n" );
596 printf( "Modes:\n" );
597 printf( " generate Generate the master key\n" );
598 printf( " save Save the derived key\n" );
599 printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
600 printf( " wrap Wrap (encrypt) input with the derived key\n" );
601 printf( "\n" );
602 printf( "Options:\n" );
603 printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
604 printf( " master=FILENAME File containing the master key (default: master.key)\n" );
605 printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
606 printf( " label=TEXT Label for the key derivation.\n" );
607 printf( " This may be repeated multiple times.\n" );
608 printf( " To get the same key, you must use the same master key\n" );
609 printf( " and the same sequence of labels.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200610}
611
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000612#if defined(MBEDTLS_CHECK_PARAMS)
613#include "mbedtls/platform_util.h"
614void mbedtls_param_failed( const char *failure_condition,
615 const char *file,
616 int line )
617{
Jaeden Amerofa30c332018-12-21 18:42:18 +0000618 printf( "%s:%i: Input param failed - %s\n",
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000619 file, line, failure_condition );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000620 exit( EXIT_FAILURE );
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000621}
622#endif
623
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200624int 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 */