blob: f492e0e5d54688586cc01e7c87f546b5843aa35e [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
Gilles Peskine4e2cc532019-05-29 14:30:27 +020066#include <psa/crypto.h>
67
Gilles Peskinef0fa4362018-07-16 17:08:43 +020068/* If the build options we need are not enabled, compile a placeholder. */
69#if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
70 !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
k-stachowiak012dcc42019-08-13 14:55:03 +020071 !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020072int main( void )
73{
Jaeden Amerofa30c332018-12-21 18:42:18 +000074 printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
75 "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
k-stachowiak012dcc42019-08-13 14:55:03 +020076 "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
77 "not defined.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +020078 return( 0 );
79}
80#else
81
82/* The real program starts here. */
83
Gilles Peskinef0fa4362018-07-16 17:08:43 +020084/* Run a system function and bail out if it fails. */
85#define SYS_CHECK( expr ) \
86 do \
87 { \
88 if( ! ( expr ) ) \
89 { \
90 perror( #expr ); \
91 status = DEMO_ERROR; \
92 goto exit; \
93 } \
94 } \
95 while( 0 )
96
97/* Run a PSA function and bail out if it fails. */
98#define PSA_CHECK( expr ) \
99 do \
100 { \
101 status = ( expr ); \
102 if( status != PSA_SUCCESS ) \
103 { \
Jaeden Amerofa30c332018-12-21 18:42:18 +0000104 printf( "Error %d at line %u: %s\n", \
105 (int) status, \
106 __LINE__, \
107 #expr ); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200108 goto exit; \
109 } \
110 } \
111 while( 0 )
112
113/* To report operational errors in this program, use an error code that is
114 * different from every PSA error code. */
115#define DEMO_ERROR 120
116
117/* The maximum supported key ladder depth. */
118#define MAX_LADDER_DEPTH 10
119
120/* Salt to use when deriving an intermediate key. */
121#define DERIVE_KEY_SALT ( (uint8_t *) "key_ladder_demo.derive" )
122#define DERIVE_KEY_SALT_LENGTH ( strlen( (const char*) DERIVE_KEY_SALT ) )
123
124/* Salt to use when deriving a wrapping key. */
125#define WRAPPING_KEY_SALT ( (uint8_t *) "key_ladder_demo.wrap" )
126#define WRAPPING_KEY_SALT_LENGTH ( strlen( (const char*) WRAPPING_KEY_SALT ) )
127
128/* Size of the key derivation keys (applies both to the master key and
129 * to intermediate keys). */
130#define KEY_SIZE_BYTES 40
131
132/* Algorithm for key derivation. */
133#define KDF_ALG PSA_ALG_HKDF( PSA_ALG_SHA_256 )
134
135/* Type and size of the key used to wrap data. */
136#define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
137#define WRAPPING_KEY_BITS 128
138
139/* Cipher mode used to wrap data. */
140#define WRAPPING_ALG PSA_ALG_CCM
141
142/* Nonce size used to wrap data. */
143#define WRAPPING_IV_SIZE 13
144
145/* Header used in files containing wrapped data. We'll save this header
146 * directly without worrying about data representation issues such as
147 * integer sizes and endianness, because the data is meant to be read
148 * back by the same program on the same machine. */
149#define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
150#define WRAPPED_DATA_MAGIC_LENGTH ( sizeof( WRAPPED_DATA_MAGIC ) )
151typedef struct
152{
153 char magic[WRAPPED_DATA_MAGIC_LENGTH];
154 size_t ad_size; /* Size of the additional data, which is this header. */
155 size_t payload_size; /* Size of the encrypted data. */
156 /* Store the IV inside the additional data. It's convenient. */
157 uint8_t iv[WRAPPING_IV_SIZE];
158} wrapped_data_header_t;
159
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200160/* The modes that this program can operate in (see usage). */
161enum program_mode
162{
163 MODE_GENERATE,
164 MODE_SAVE,
165 MODE_UNWRAP,
166 MODE_WRAP
167};
168
169/* Save a key to a file. In the real world, you may want to export a derived
170 * key sometimes, to share it with another party. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100171static psa_status_t save_key( psa_key_handle_t key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200172 const char *output_file_name )
173{
174 psa_status_t status = PSA_SUCCESS;
175 uint8_t key_data[KEY_SIZE_BYTES];
176 size_t key_size;
177 FILE *key_file = NULL;
178
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100179 PSA_CHECK( psa_export_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200180 key_data, sizeof( key_data ),
181 &key_size ) );
182 SYS_CHECK( ( key_file = fopen( output_file_name, "wb" ) ) != NULL );
183 SYS_CHECK( fwrite( key_data, 1, key_size, key_file ) == key_size );
184 SYS_CHECK( fclose( key_file ) == 0 );
185 key_file = NULL;
186
187exit:
188 if( key_file != NULL)
189 fclose( key_file );
190 return( status );
191}
192
193/* Generate a master key for use in this demo.
194 *
195 * Normally a master key would be non-exportable. For the purpose of this
196 * demo, we want to save it to a file, to avoid relying on the keystore
197 * capability of the PSA crypto library. */
198static psa_status_t generate( const char *key_file_name )
199{
200 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100201 psa_key_handle_t key_handle = 0;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200202 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200203
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200204 psa_set_key_usage_flags( &attributes,
205 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
206 psa_set_key_algorithm( &attributes, KDF_ALG );
207 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine3a4f1f82019-04-26 13:49:28 +0200208 psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200209
Gilles Peskine35ef36b2019-05-16 19:42:05 +0200210 PSA_CHECK( psa_generate_key( &attributes, &key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200211
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100212 PSA_CHECK( save_key( key_handle, key_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200213
214exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100215 (void) psa_destroy_key( key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200216 return( status );
217}
218
219/* Load the master key from a file.
220 *
221 * In the real world, this master key would be stored in an internal memory
222 * and the storage would be managed by the keystore capability of the PSA
223 * crypto library. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100224static psa_status_t import_key_from_file( psa_key_usage_t usage,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200225 psa_algorithm_t alg,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100226 const char *key_file_name,
227 psa_key_handle_t *master_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200228{
229 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200230 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200231 uint8_t key_data[KEY_SIZE_BYTES];
232 size_t key_size;
233 FILE *key_file = NULL;
234 unsigned char extra_byte;
235
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100236 *master_key_handle = 0;
237
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200238 SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
239 SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
240 key_file ) ) != 0 );
241 if( fread( &extra_byte, 1, 1, key_file ) != 0 )
242 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000243 printf( "Key file too large (max: %u).\n",
244 (unsigned) sizeof( key_data ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200245 status = DEMO_ERROR;
246 goto exit;
247 }
248 SYS_CHECK( fclose( key_file ) == 0 );
249 key_file = NULL;
250
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200251 psa_set_key_usage_flags( &attributes, usage );
252 psa_set_key_algorithm( &attributes, alg );
253 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine73676cb2019-05-15 20:15:10 +0200254 PSA_CHECK( psa_import_key( &attributes, key_data, key_size,
255 master_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200256exit:
257 if( key_file != NULL )
258 fclose( key_file );
259 mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100260 if( status != PSA_SUCCESS )
261 {
Gilles Peskine5163a922019-05-27 14:52:34 +0200262 /* If the key creation hasn't happened yet or has failed,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100263 * *master_key_handle is 0. psa_destroy_key(0) is guaranteed to do
264 * nothing and return PSA_ERROR_INVALID_HANDLE. */
265 (void) psa_destroy_key( *master_key_handle );
266 *master_key_handle = 0;
267 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200268 return( status );
269}
270
271/* Derive the intermediate keys, using the list of labels provided on
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100272 * the command line. On input, *key_handle is a handle to the master key.
273 * This function closes the master key. On successful output, *key_handle
274 * is a handle to the final derived key. */
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200275static psa_status_t derive_key_ladder( const char *ladder[],
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100276 size_t ladder_depth,
277 psa_key_handle_t *key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200278{
279 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200280 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200281 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200282 size_t i;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200283
284 psa_set_key_usage_flags( &attributes,
285 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
286 psa_set_key_algorithm( &attributes, KDF_ALG );
287 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine3a4f1f82019-04-26 13:49:28 +0200288 psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200289
290 /* For each label in turn, ... */
291 for( i = 0; i < ladder_depth; i++ )
292 {
293 /* Start deriving material from the master key (if i=0) or from
294 * the current intermediate key (if i>0). */
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200295 PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
296 PSA_CHECK( psa_key_derivation_input_bytes(
297 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
298 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH ) );
299 PSA_CHECK( psa_key_derivation_input_key(
300 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
301 *key_handle ) );
302 PSA_CHECK( psa_key_derivation_input_bytes(
303 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
304 (uint8_t*) ladder[i], strlen( ladder[i] ) ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200305 /* When the parent key is not the master key, destroy it,
306 * since it is no longer needed. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100307 PSA_CHECK( psa_close_key( *key_handle ) );
308 *key_handle = 0;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200309 /* Derive the next intermediate key from the parent key. */
310 PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
311 key_handle ) );
312 PSA_CHECK( psa_key_derivation_abort( &operation ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200313 }
314
315exit:
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200316 psa_key_derivation_abort( &operation );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100317 if( status != PSA_SUCCESS )
318 {
319 psa_close_key( *key_handle );
320 *key_handle = 0;
321 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200322 return( status );
323}
324
325/* Derive a wrapping key from the last intermediate key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100326static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
327 psa_key_handle_t derived_key_handle,
328 psa_key_handle_t *wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200329{
330 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200331 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200332 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200333
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100334 *wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200335
Gilles Peskine2a38e242019-05-29 14:33:00 +0200336 /* Set up a key derivation operation from the key derived from
337 * the master key. */
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200338 PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
339 PSA_CHECK( psa_key_derivation_input_bytes(
340 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
341 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH ) );
342 PSA_CHECK( psa_key_derivation_input_key(
343 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
344 derived_key_handle ) );
345 PSA_CHECK( psa_key_derivation_input_bytes(
346 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
347 NULL, 0 ) );
Gilles Peskine2a38e242019-05-29 14:33:00 +0200348
349 /* Create the wrapping key. */
350 psa_set_key_usage_flags( &attributes, usage );
351 psa_set_key_algorithm( &attributes, WRAPPING_ALG );
352 psa_set_key_type( &attributes, PSA_KEY_TYPE_AES );
353 psa_set_key_bits( &attributes, WRAPPING_KEY_BITS );
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200354 PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
355 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200356
357exit:
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200358 psa_key_derivation_abort( &operation );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200359 return( status );
360}
361
362static psa_status_t wrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100363 const char *output_file_name,
364 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200365{
366 psa_status_t status;
367 FILE *input_file = NULL;
368 FILE *output_file = NULL;
369 long input_position;
370 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100371 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200372 unsigned char *buffer = NULL;
373 size_t ciphertext_size;
374 wrapped_data_header_t header;
375
376 /* Find the size of the data to wrap. */
377 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
378 SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
379 SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
380#if LONG_MAX > SIZE_MAX
381 if( input_position > SIZE_MAX )
382 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000383 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200384 status = DEMO_ERROR;
385 goto exit;
386 }
387#endif
388 input_size = input_position;
389 buffer_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, input_size );
390 /* Check for integer overflow. */
391 if( buffer_size < input_size )
392 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000393 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200394 status = DEMO_ERROR;
395 goto exit;
396 }
397
398 /* Load the data to wrap. */
399 SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000400 SYS_CHECK( ( buffer = calloc( 1, buffer_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200401 SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
402 SYS_CHECK( fclose( input_file ) == 0 );
403 input_file = NULL;
404
405 /* Construct a header. */
406 memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
407 header.ad_size = sizeof( header );
408 header.payload_size = input_size;
409
410 /* Wrap the data. */
411 PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100412 PSA_CHECK( psa_aead_encrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200413 header.iv, WRAPPING_IV_SIZE,
414 (uint8_t *) &header, sizeof( header ),
415 buffer, input_size,
416 buffer, buffer_size,
417 &ciphertext_size ) );
418
419 /* Write the output. */
420 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
421 SYS_CHECK( fwrite( &header, 1, sizeof( header ),
422 output_file ) == sizeof( header ) );
423 SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
424 output_file ) == ciphertext_size );
425 SYS_CHECK( fclose( output_file ) == 0 );
426 output_file = NULL;
427
428exit:
429 if( input_file != NULL )
430 fclose( input_file );
431 if( output_file != NULL )
432 fclose( output_file );
433 if( buffer != NULL )
434 mbedtls_platform_zeroize( buffer, buffer_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000435 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200436 return( status );
437}
438
439static psa_status_t unwrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100440 const char *output_file_name,
441 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200442{
443 psa_status_t status;
444 FILE *input_file = NULL;
445 FILE *output_file = NULL;
446 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100447 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200448 size_t plaintext_size;
449 wrapped_data_header_t header;
450 unsigned char extra_byte;
451
452 /* Load and validate the header. */
453 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
454 SYS_CHECK( fread( &header, 1, sizeof( header ),
455 input_file ) == sizeof( header ) );
456 if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
457 WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
458 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000459 printf( "The input does not start with a valid magic header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200460 status = DEMO_ERROR;
461 goto exit;
462 }
463 if( header.ad_size != sizeof( header ) )
464 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000465 printf( "The header size is not correct.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200466 status = DEMO_ERROR;
467 goto exit;
468 }
469 ciphertext_size =
470 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, header.payload_size );
471 /* Check for integer overflow. */
472 if( ciphertext_size < header.payload_size )
473 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000474 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200475 status = DEMO_ERROR;
476 goto exit;
477 }
478
479 /* Load the payload data. */
Jaeden Amerofa30c332018-12-21 18:42:18 +0000480 SYS_CHECK( ( buffer = calloc( 1, ciphertext_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200481 SYS_CHECK( fread( buffer, 1, ciphertext_size,
482 input_file ) == ciphertext_size );
483 if( fread( &extra_byte, 1, 1, input_file ) != 0 )
484 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000485 printf( "Extra garbage after ciphertext\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200486 status = DEMO_ERROR;
487 goto exit;
488 }
489 SYS_CHECK( fclose( input_file ) == 0 );
490 input_file = NULL;
491
492 /* Unwrap the data. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100493 PSA_CHECK( psa_aead_decrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200494 header.iv, WRAPPING_IV_SIZE,
495 (uint8_t *) &header, sizeof( header ),
496 buffer, ciphertext_size,
497 buffer, ciphertext_size,
498 &plaintext_size ) );
499 if( plaintext_size != header.payload_size )
500 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000501 printf( "Incorrect payload size in the header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200502 status = DEMO_ERROR;
503 goto exit;
504 }
505
506 /* Write the output. */
507 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
508 SYS_CHECK( fwrite( buffer, 1, plaintext_size,
509 output_file ) == plaintext_size );
510 SYS_CHECK( fclose( output_file ) == 0 );
511 output_file = NULL;
512
513exit:
514 if( input_file != NULL )
515 fclose( input_file );
516 if( output_file != NULL )
517 fclose( output_file );
518 if( buffer != NULL )
519 mbedtls_platform_zeroize( buffer, ciphertext_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000520 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200521 return( status );
522}
523
524static psa_status_t run( enum program_mode mode,
525 const char *key_file_name,
526 const char *ladder[], size_t ladder_depth,
527 const char *input_file_name,
528 const char *output_file_name )
529{
530 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100531 psa_key_handle_t derivation_key_handle = 0;
532 psa_key_handle_t wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200533
534 /* Initialize the PSA crypto library. */
535 PSA_CHECK( psa_crypto_init( ) );
536
537 /* Generate mode is unlike the others. Generate the master key and exit. */
538 if( mode == MODE_GENERATE )
539 return( generate( key_file_name ) );
540
541 /* Read the master key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100542 PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200543 KDF_ALG,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100544 key_file_name,
545 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200546
547 /* Calculate the derived key for this session. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100548 PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
549 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200550
551 switch( mode )
552 {
553 case MODE_SAVE:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100554 PSA_CHECK( save_key( derivation_key_handle, output_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200555 break;
556 case MODE_UNWRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100557 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
558 derivation_key_handle,
559 &wrapping_key_handle ) );
560 PSA_CHECK( unwrap_data( input_file_name, output_file_name,
561 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200562 break;
563 case MODE_WRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100564 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
565 derivation_key_handle,
566 &wrapping_key_handle ) );
567 PSA_CHECK( wrap_data( input_file_name, output_file_name,
568 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200569 break;
570 default:
571 /* Unreachable but some compilers don't realize it. */
572 break;
573 }
574
575exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100576 /* Close any remaining key. Deinitializing the crypto library would do
577 * this anyway, but explicitly closing handles makes the code easier
578 * to reuse. */
579 (void) psa_close_key( derivation_key_handle );
580 (void) psa_close_key( wrapping_key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200581 /* Deinitialize the PSA crypto library. */
582 mbedtls_psa_crypto_free( );
583 return( status );
584}
585
586static void usage( void )
587{
Jaeden Amerofa30c332018-12-21 18:42:18 +0000588 printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
589 printf( "Demonstrate the usage of a key derivation ladder.\n" );
590 printf( "\n" );
591 printf( "Modes:\n" );
592 printf( " generate Generate the master key\n" );
593 printf( " save Save the derived key\n" );
594 printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
595 printf( " wrap Wrap (encrypt) input with the derived key\n" );
596 printf( "\n" );
597 printf( "Options:\n" );
598 printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
599 printf( " master=FILENAME File containing the master key (default: master.key)\n" );
600 printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
601 printf( " label=TEXT Label for the key derivation.\n" );
602 printf( " This may be repeated multiple times.\n" );
603 printf( " To get the same key, you must use the same master key\n" );
604 printf( " and the same sequence of labels.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200605}
606
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000607#if defined(MBEDTLS_CHECK_PARAMS)
608#include "mbedtls/platform_util.h"
609void mbedtls_param_failed( const char *failure_condition,
610 const char *file,
611 int line )
612{
Jaeden Amerofa30c332018-12-21 18:42:18 +0000613 printf( "%s:%i: Input param failed - %s\n",
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000614 file, line, failure_condition );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000615 exit( EXIT_FAILURE );
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000616}
617#endif
618
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200619int main( int argc, char *argv[] )
620{
Gilles Peskine738f0172019-01-02 17:25:16 +0100621 const char *key_file_name = "master.key";
622 const char *input_file_name = NULL;
623 const char *output_file_name = NULL;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200624 const char *ladder[MAX_LADDER_DEPTH];
625 size_t ladder_depth = 0;
626 int i;
627 enum program_mode mode;
628 psa_status_t status;
629
630 if( argc <= 1 ||
631 strcmp( argv[1], "help" ) == 0 ||
632 strcmp( argv[1], "-help" ) == 0 ||
633 strcmp( argv[1], "--help" ) == 0 )
634 {
635 usage( );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000636 return( EXIT_SUCCESS );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200637 }
638
639 for( i = 2; i < argc; i++ )
640 {
641 char *q = strchr( argv[i], '=' );
642 if( q == NULL )
643 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000644 printf( "Missing argument to option %s\n", argv[i] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200645 goto usage_failure;
646 }
647 *q = 0;
648 ++q;
649 if( strcmp( argv[i], "input" ) == 0 )
650 input_file_name = q;
651 else if( strcmp( argv[i], "label" ) == 0 )
652 {
653 if( ladder_depth == MAX_LADDER_DEPTH )
654 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000655 printf( "Maximum ladder depth %u exceeded.\n",
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200656 (unsigned) MAX_LADDER_DEPTH );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000657 return( EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200658 }
659 ladder[ladder_depth] = q;
660 ++ladder_depth;
661 }
662 else if( strcmp( argv[i], "master" ) == 0 )
663 key_file_name = q;
664 else if( strcmp( argv[i], "output" ) == 0 )
665 output_file_name = q;
666 else
667 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000668 printf( "Unknown option: %s\n", argv[i] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200669 goto usage_failure;
670 }
671 }
672
673 if( strcmp( argv[1], "generate" ) == 0 )
674 mode = MODE_GENERATE;
675 else if( strcmp( argv[1], "save" ) == 0 )
676 mode = MODE_SAVE;
677 else if( strcmp( argv[1], "unwrap" ) == 0 )
678 mode = MODE_UNWRAP;
679 else if( strcmp( argv[1], "wrap" ) == 0 )
680 mode = MODE_WRAP;
681 else
682 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000683 printf( "Unknown action: %s\n", argv[1] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200684 goto usage_failure;
685 }
686
687 if( input_file_name == NULL &&
688 ( mode == MODE_WRAP || mode == MODE_UNWRAP ) )
689 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000690 printf( "Required argument missing: input\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200691 return( DEMO_ERROR );
692 }
693 if( output_file_name == NULL &&
694 ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) )
695 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000696 printf( "Required argument missing: output\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200697 return( DEMO_ERROR );
698 }
699
700 status = run( mode, key_file_name,
701 ladder, ladder_depth,
702 input_file_name, output_file_name );
703 return( status == PSA_SUCCESS ?
Jaeden Amerofa30c332018-12-21 18:42:18 +0000704 EXIT_SUCCESS :
705 EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200706
707usage_failure:
708 usage( );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000709 return( EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200710}
711#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */