blob: ae2442e23daec67dd6f54abaa2c5ba5a3282fcaf [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
Bence Szépkúti86974652020-06-15 11:59:37 +020033/*
Bence Szépkúti1e148272020-08-07 13:07:28 +020034 * Copyright The Mbed TLS Contributors
Gilles Peskinef0fa4362018-07-16 17:08:43 +020035 * SPDX-License-Identifier: Apache-2.0
36 *
37 * Licensed under the Apache License, Version 2.0 (the "License"); you may
38 * not use this file except in compliance with the License.
39 * You may obtain a copy of the License at
40 *
41 * http://www.apache.org/licenses/LICENSE-2.0
42 *
43 * Unless required by applicable law or agreed to in writing, software
44 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
45 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
46 * See the License for the specific language governing permissions and
47 * limitations under the License.
Gilles Peskinef0fa4362018-07-16 17:08:43 +020048 */
49
50/* First include Mbed TLS headers to get the Mbed TLS configuration and
51 * platform definitions that we'll use in this program. Also include
52 * standard C headers for functions we'll use here. */
53#if !defined(MBEDTLS_CONFIG_FILE)
54#include "mbedtls/config.h"
55#else
56#include MBEDTLS_CONFIG_FILE
57#endif
58
Gilles Peskinef0fa4362018-07-16 17:08:43 +020059#include <stdlib.h>
Gilles Peskinef0fa4362018-07-16 17:08:43 +020060#include <stdio.h>
61#include <string.h>
62
63#include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
64
Gilles Peskine4e2cc532019-05-29 14:30:27 +020065#include <psa/crypto.h>
66
Gilles Peskinef0fa4362018-07-16 17:08:43 +020067/* If the build options we need are not enabled, compile a placeholder. */
68#if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
69 !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
k-stachowiak012dcc42019-08-13 14:55:03 +020070 !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO)
Gilles Peskinef0fa4362018-07-16 17:08:43 +020071int main( void )
72{
Jaeden Amerofa30c332018-12-21 18:42:18 +000073 printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
74 "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
k-stachowiak012dcc42019-08-13 14:55:03 +020075 "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
76 "not defined.\n");
Gilles Peskinef0fa4362018-07-16 17:08:43 +020077 return( 0 );
78}
79#else
80
81/* The real program starts here. */
82
Gilles Peskinef0fa4362018-07-16 17:08:43 +020083/* Run a system function and bail out if it fails. */
84#define SYS_CHECK( expr ) \
85 do \
86 { \
87 if( ! ( expr ) ) \
88 { \
89 perror( #expr ); \
90 status = DEMO_ERROR; \
91 goto exit; \
92 } \
93 } \
94 while( 0 )
95
96/* Run a PSA function and bail out if it fails. */
97#define PSA_CHECK( expr ) \
98 do \
99 { \
100 status = ( expr ); \
101 if( status != PSA_SUCCESS ) \
102 { \
Kenneth Soerensen518d4352020-04-01 17:22:45 +0200103 printf( "Error %d at line %d: %s\n", \
Jaeden Amerofa30c332018-12-21 18:42:18 +0000104 (int) status, \
105 __LINE__, \
106 #expr ); \
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200107 goto exit; \
108 } \
109 } \
110 while( 0 )
111
112/* To report operational errors in this program, use an error code that is
113 * different from every PSA error code. */
114#define DEMO_ERROR 120
115
116/* The maximum supported key ladder depth. */
117#define MAX_LADDER_DEPTH 10
118
119/* Salt to use when deriving an intermediate key. */
120#define DERIVE_KEY_SALT ( (uint8_t *) "key_ladder_demo.derive" )
121#define DERIVE_KEY_SALT_LENGTH ( strlen( (const char*) DERIVE_KEY_SALT ) )
122
123/* Salt to use when deriving a wrapping key. */
124#define WRAPPING_KEY_SALT ( (uint8_t *) "key_ladder_demo.wrap" )
125#define WRAPPING_KEY_SALT_LENGTH ( strlen( (const char*) WRAPPING_KEY_SALT ) )
126
127/* Size of the key derivation keys (applies both to the master key and
128 * to intermediate keys). */
129#define KEY_SIZE_BYTES 40
130
131/* Algorithm for key derivation. */
132#define KDF_ALG PSA_ALG_HKDF( PSA_ALG_SHA_256 )
133
134/* Type and size of the key used to wrap data. */
135#define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
136#define WRAPPING_KEY_BITS 128
137
138/* Cipher mode used to wrap data. */
139#define WRAPPING_ALG PSA_ALG_CCM
140
141/* Nonce size used to wrap data. */
142#define WRAPPING_IV_SIZE 13
143
144/* Header used in files containing wrapped data. We'll save this header
145 * directly without worrying about data representation issues such as
146 * integer sizes and endianness, because the data is meant to be read
147 * back by the same program on the same machine. */
148#define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
149#define WRAPPED_DATA_MAGIC_LENGTH ( sizeof( WRAPPED_DATA_MAGIC ) )
150typedef struct
151{
152 char magic[WRAPPED_DATA_MAGIC_LENGTH];
153 size_t ad_size; /* Size of the additional data, which is this header. */
154 size_t payload_size; /* Size of the encrypted data. */
155 /* Store the IV inside the additional data. It's convenient. */
156 uint8_t iv[WRAPPING_IV_SIZE];
157} wrapped_data_header_t;
158
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200159/* The modes that this program can operate in (see usage). */
160enum program_mode
161{
162 MODE_GENERATE,
163 MODE_SAVE,
164 MODE_UNWRAP,
165 MODE_WRAP
166};
167
168/* Save a key to a file. In the real world, you may want to export a derived
169 * key sometimes, to share it with another party. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100170static psa_status_t save_key( psa_key_handle_t key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200171 const char *output_file_name )
172{
173 psa_status_t status = PSA_SUCCESS;
174 uint8_t key_data[KEY_SIZE_BYTES];
175 size_t key_size;
176 FILE *key_file = NULL;
177
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100178 PSA_CHECK( psa_export_key( key_handle,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200179 key_data, sizeof( key_data ),
180 &key_size ) );
181 SYS_CHECK( ( key_file = fopen( output_file_name, "wb" ) ) != NULL );
182 SYS_CHECK( fwrite( key_data, 1, key_size, key_file ) == key_size );
183 SYS_CHECK( fclose( key_file ) == 0 );
184 key_file = NULL;
185
186exit:
187 if( key_file != NULL)
188 fclose( key_file );
189 return( status );
190}
191
192/* Generate a master key for use in this demo.
193 *
194 * Normally a master key would be non-exportable. For the purpose of this
195 * demo, we want to save it to a file, to avoid relying on the keystore
196 * capability of the PSA crypto library. */
197static psa_status_t generate( const char *key_file_name )
198{
199 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100200 psa_key_handle_t key_handle = 0;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200201 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200202
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200203 psa_set_key_usage_flags( &attributes,
204 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
205 psa_set_key_algorithm( &attributes, KDF_ALG );
206 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine3a4f1f82019-04-26 13:49:28 +0200207 psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200208
Gilles Peskine35ef36b2019-05-16 19:42:05 +0200209 PSA_CHECK( psa_generate_key( &attributes, &key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200210
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100211 PSA_CHECK( save_key( key_handle, key_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200212
213exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100214 (void) psa_destroy_key( key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200215 return( status );
216}
217
218/* Load the master key from a file.
219 *
220 * In the real world, this master key would be stored in an internal memory
221 * and the storage would be managed by the keystore capability of the PSA
222 * crypto library. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100223static psa_status_t import_key_from_file( psa_key_usage_t usage,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200224 psa_algorithm_t alg,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100225 const char *key_file_name,
226 psa_key_handle_t *master_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200227{
228 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200229 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200230 uint8_t key_data[KEY_SIZE_BYTES];
231 size_t key_size;
232 FILE *key_file = NULL;
233 unsigned char extra_byte;
234
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100235 *master_key_handle = 0;
236
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200237 SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
238 SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
239 key_file ) ) != 0 );
240 if( fread( &extra_byte, 1, 1, key_file ) != 0 )
241 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000242 printf( "Key file too large (max: %u).\n",
243 (unsigned) sizeof( key_data ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200244 status = DEMO_ERROR;
245 goto exit;
246 }
247 SYS_CHECK( fclose( key_file ) == 0 );
248 key_file = NULL;
249
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200250 psa_set_key_usage_flags( &attributes, usage );
251 psa_set_key_algorithm( &attributes, alg );
252 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine73676cb2019-05-15 20:15:10 +0200253 PSA_CHECK( psa_import_key( &attributes, key_data, key_size,
254 master_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200255exit:
256 if( key_file != NULL )
257 fclose( key_file );
258 mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100259 if( status != PSA_SUCCESS )
260 {
Gilles Peskine5163a922019-05-27 14:52:34 +0200261 /* If the key creation hasn't happened yet or has failed,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100262 * *master_key_handle is 0. psa_destroy_key(0) is guaranteed to do
263 * nothing and return PSA_ERROR_INVALID_HANDLE. */
264 (void) psa_destroy_key( *master_key_handle );
265 *master_key_handle = 0;
266 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200267 return( status );
268}
269
270/* Derive the intermediate keys, using the list of labels provided on
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100271 * the command line. On input, *key_handle is a handle to the master key.
272 * This function closes the master key. On successful output, *key_handle
273 * is a handle to the final derived key. */
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200274static psa_status_t derive_key_ladder( const char *ladder[],
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100275 size_t ladder_depth,
276 psa_key_handle_t *key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200277{
278 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200279 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200280 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200281 size_t i;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200282
283 psa_set_key_usage_flags( &attributes,
284 PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
285 psa_set_key_algorithm( &attributes, KDF_ALG );
286 psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
Gilles Peskine3a4f1f82019-04-26 13:49:28 +0200287 psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200288
289 /* For each label in turn, ... */
290 for( i = 0; i < ladder_depth; i++ )
291 {
292 /* Start deriving material from the master key (if i=0) or from
293 * the current intermediate key (if i>0). */
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200294 PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
295 PSA_CHECK( psa_key_derivation_input_bytes(
296 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
297 DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH ) );
298 PSA_CHECK( psa_key_derivation_input_key(
299 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
300 *key_handle ) );
301 PSA_CHECK( psa_key_derivation_input_bytes(
302 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
303 (uint8_t*) ladder[i], strlen( ladder[i] ) ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200304 /* 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 Peskine4e2cc532019-05-29 14:30:27 +0200308 /* Derive the next intermediate key from the parent key. */
309 PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
310 key_handle ) );
311 PSA_CHECK( psa_key_derivation_abort( &operation ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200312 }
313
314exit:
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200315 psa_key_derivation_abort( &operation );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100316 if( status != PSA_SUCCESS )
317 {
318 psa_close_key( *key_handle );
319 *key_handle = 0;
320 }
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200321 return( status );
322}
323
324/* Derive a wrapping key from the last intermediate key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100325static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
326 psa_key_handle_t derived_key_handle,
327 psa_key_handle_t *wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200328{
329 psa_status_t status = PSA_SUCCESS;
Gilles Peskinedfea0a252019-04-18 13:39:40 +0200330 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200331 psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200332
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100333 *wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200334
Gilles Peskine2a38e242019-05-29 14:33:00 +0200335 /* Set up a key derivation operation from the key derived from
336 * the master key. */
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200337 PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
338 PSA_CHECK( psa_key_derivation_input_bytes(
339 &operation, PSA_KEY_DERIVATION_INPUT_SALT,
340 WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH ) );
341 PSA_CHECK( psa_key_derivation_input_key(
342 &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
343 derived_key_handle ) );
344 PSA_CHECK( psa_key_derivation_input_bytes(
345 &operation, PSA_KEY_DERIVATION_INPUT_INFO,
346 NULL, 0 ) );
Gilles Peskine2a38e242019-05-29 14:33:00 +0200347
348 /* Create the wrapping key. */
349 psa_set_key_usage_flags( &attributes, usage );
350 psa_set_key_algorithm( &attributes, WRAPPING_ALG );
351 psa_set_key_type( &attributes, PSA_KEY_TYPE_AES );
352 psa_set_key_bits( &attributes, WRAPPING_KEY_BITS );
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200353 PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
354 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200355
356exit:
Gilles Peskine4e2cc532019-05-29 14:30:27 +0200357 psa_key_derivation_abort( &operation );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200358 return( status );
359}
360
361static psa_status_t wrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100362 const char *output_file_name,
363 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200364{
365 psa_status_t status;
366 FILE *input_file = NULL;
367 FILE *output_file = NULL;
368 long input_position;
369 size_t input_size;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100370 size_t buffer_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200371 unsigned char *buffer = NULL;
372 size_t ciphertext_size;
373 wrapped_data_header_t header;
374
375 /* Find the size of the data to wrap. */
376 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
377 SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
378 SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
379#if LONG_MAX > SIZE_MAX
380 if( input_position > SIZE_MAX )
381 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000382 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200383 status = DEMO_ERROR;
384 goto exit;
385 }
386#endif
387 input_size = input_position;
388 buffer_size = PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, input_size );
389 /* Check for integer overflow. */
390 if( buffer_size < input_size )
391 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000392 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200393 status = DEMO_ERROR;
394 goto exit;
395 }
396
397 /* Load the data to wrap. */
398 SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000399 SYS_CHECK( ( buffer = calloc( 1, buffer_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200400 SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
401 SYS_CHECK( fclose( input_file ) == 0 );
402 input_file = NULL;
403
404 /* Construct a header. */
405 memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
406 header.ad_size = sizeof( header );
407 header.payload_size = input_size;
408
409 /* Wrap the data. */
410 PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100411 PSA_CHECK( psa_aead_encrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200412 header.iv, WRAPPING_IV_SIZE,
413 (uint8_t *) &header, sizeof( header ),
414 buffer, input_size,
415 buffer, buffer_size,
416 &ciphertext_size ) );
417
418 /* Write the output. */
419 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
420 SYS_CHECK( fwrite( &header, 1, sizeof( header ),
421 output_file ) == sizeof( header ) );
422 SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
423 output_file ) == ciphertext_size );
424 SYS_CHECK( fclose( output_file ) == 0 );
425 output_file = NULL;
426
427exit:
428 if( input_file != NULL )
429 fclose( input_file );
430 if( output_file != NULL )
431 fclose( output_file );
432 if( buffer != NULL )
433 mbedtls_platform_zeroize( buffer, buffer_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000434 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200435 return( status );
436}
437
438static psa_status_t unwrap_data( const char *input_file_name,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100439 const char *output_file_name,
440 psa_key_handle_t wrapping_key_handle )
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200441{
442 psa_status_t status;
443 FILE *input_file = NULL;
444 FILE *output_file = NULL;
445 unsigned char *buffer = NULL;
Gilles Peskine5e09bc72018-12-21 12:06:15 +0100446 size_t ciphertext_size = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200447 size_t plaintext_size;
448 wrapped_data_header_t header;
449 unsigned char extra_byte;
450
451 /* Load and validate the header. */
452 SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
453 SYS_CHECK( fread( &header, 1, sizeof( header ),
454 input_file ) == sizeof( header ) );
455 if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
456 WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
457 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000458 printf( "The input does not start with a valid magic header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200459 status = DEMO_ERROR;
460 goto exit;
461 }
462 if( header.ad_size != sizeof( header ) )
463 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000464 printf( "The header size is not correct.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200465 status = DEMO_ERROR;
466 goto exit;
467 }
468 ciphertext_size =
469 PSA_AEAD_ENCRYPT_OUTPUT_SIZE( WRAPPING_ALG, header.payload_size );
470 /* Check for integer overflow. */
471 if( ciphertext_size < header.payload_size )
472 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000473 printf( "Input file too large.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200474 status = DEMO_ERROR;
475 goto exit;
476 }
477
478 /* Load the payload data. */
Jaeden Amerofa30c332018-12-21 18:42:18 +0000479 SYS_CHECK( ( buffer = calloc( 1, ciphertext_size ) ) != NULL );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200480 SYS_CHECK( fread( buffer, 1, ciphertext_size,
481 input_file ) == ciphertext_size );
482 if( fread( &extra_byte, 1, 1, input_file ) != 0 )
483 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000484 printf( "Extra garbage after ciphertext\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200485 status = DEMO_ERROR;
486 goto exit;
487 }
488 SYS_CHECK( fclose( input_file ) == 0 );
489 input_file = NULL;
490
491 /* Unwrap the data. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100492 PSA_CHECK( psa_aead_decrypt( wrapping_key_handle, WRAPPING_ALG,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200493 header.iv, WRAPPING_IV_SIZE,
494 (uint8_t *) &header, sizeof( header ),
495 buffer, ciphertext_size,
496 buffer, ciphertext_size,
497 &plaintext_size ) );
498 if( plaintext_size != header.payload_size )
499 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000500 printf( "Incorrect payload size in the header.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200501 status = DEMO_ERROR;
502 goto exit;
503 }
504
505 /* Write the output. */
506 SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
507 SYS_CHECK( fwrite( buffer, 1, plaintext_size,
508 output_file ) == plaintext_size );
509 SYS_CHECK( fclose( output_file ) == 0 );
510 output_file = NULL;
511
512exit:
513 if( input_file != NULL )
514 fclose( input_file );
515 if( output_file != NULL )
516 fclose( output_file );
517 if( buffer != NULL )
518 mbedtls_platform_zeroize( buffer, ciphertext_size );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000519 free( buffer );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200520 return( status );
521}
522
523static psa_status_t run( enum program_mode mode,
524 const char *key_file_name,
525 const char *ladder[], size_t ladder_depth,
526 const char *input_file_name,
527 const char *output_file_name )
528{
529 psa_status_t status = PSA_SUCCESS;
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100530 psa_key_handle_t derivation_key_handle = 0;
531 psa_key_handle_t wrapping_key_handle = 0;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200532
533 /* Initialize the PSA crypto library. */
534 PSA_CHECK( psa_crypto_init( ) );
535
536 /* Generate mode is unlike the others. Generate the master key and exit. */
537 if( mode == MODE_GENERATE )
538 return( generate( key_file_name ) );
539
540 /* Read the master key. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100541 PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200542 KDF_ALG,
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100543 key_file_name,
544 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200545
546 /* Calculate the derived key for this session. */
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100547 PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
548 &derivation_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200549
550 switch( mode )
551 {
552 case MODE_SAVE:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100553 PSA_CHECK( save_key( derivation_key_handle, output_file_name ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200554 break;
555 case MODE_UNWRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100556 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
557 derivation_key_handle,
558 &wrapping_key_handle ) );
559 PSA_CHECK( unwrap_data( input_file_name, output_file_name,
560 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200561 break;
562 case MODE_WRAP:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100563 PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
564 derivation_key_handle,
565 &wrapping_key_handle ) );
566 PSA_CHECK( wrap_data( input_file_name, output_file_name,
567 wrapping_key_handle ) );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200568 break;
569 default:
570 /* Unreachable but some compilers don't realize it. */
571 break;
572 }
573
574exit:
Gilles Peskineb0edfb52018-12-03 16:24:51 +0100575 /* Close any remaining key. Deinitializing the crypto library would do
576 * this anyway, but explicitly closing handles makes the code easier
577 * to reuse. */
578 (void) psa_close_key( derivation_key_handle );
579 (void) psa_close_key( wrapping_key_handle );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200580 /* Deinitialize the PSA crypto library. */
581 mbedtls_psa_crypto_free( );
582 return( status );
583}
584
585static void usage( void )
586{
Jaeden Amerofa30c332018-12-21 18:42:18 +0000587 printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
588 printf( "Demonstrate the usage of a key derivation ladder.\n" );
589 printf( "\n" );
590 printf( "Modes:\n" );
591 printf( " generate Generate the master key\n" );
592 printf( " save Save the derived key\n" );
593 printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
594 printf( " wrap Wrap (encrypt) input with the derived key\n" );
595 printf( "\n" );
596 printf( "Options:\n" );
597 printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
598 printf( " master=FILENAME File containing the master key (default: master.key)\n" );
599 printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
600 printf( " label=TEXT Label for the key derivation.\n" );
601 printf( " This may be repeated multiple times.\n" );
602 printf( " To get the same key, you must use the same master key\n" );
603 printf( " and the same sequence of labels.\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200604}
605
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000606#if defined(MBEDTLS_CHECK_PARAMS)
607#include "mbedtls/platform_util.h"
608void mbedtls_param_failed( const char *failure_condition,
609 const char *file,
610 int line )
611{
Jaeden Amerofa30c332018-12-21 18:42:18 +0000612 printf( "%s:%i: Input param failed - %s\n",
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000613 file, line, failure_condition );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000614 exit( EXIT_FAILURE );
Jaeden Amero44a59ab2019-02-11 13:24:47 +0000615}
616#endif
617
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200618int main( int argc, char *argv[] )
619{
Gilles Peskine738f0172019-01-02 17:25:16 +0100620 const char *key_file_name = "master.key";
621 const char *input_file_name = NULL;
622 const char *output_file_name = NULL;
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200623 const char *ladder[MAX_LADDER_DEPTH];
624 size_t ladder_depth = 0;
625 int i;
626 enum program_mode mode;
627 psa_status_t status;
628
629 if( argc <= 1 ||
630 strcmp( argv[1], "help" ) == 0 ||
631 strcmp( argv[1], "-help" ) == 0 ||
632 strcmp( argv[1], "--help" ) == 0 )
633 {
634 usage( );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000635 return( EXIT_SUCCESS );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200636 }
637
638 for( i = 2; i < argc; i++ )
639 {
640 char *q = strchr( argv[i], '=' );
641 if( q == NULL )
642 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000643 printf( "Missing argument to option %s\n", argv[i] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200644 goto usage_failure;
645 }
646 *q = 0;
647 ++q;
648 if( strcmp( argv[i], "input" ) == 0 )
649 input_file_name = q;
650 else if( strcmp( argv[i], "label" ) == 0 )
651 {
652 if( ladder_depth == MAX_LADDER_DEPTH )
653 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000654 printf( "Maximum ladder depth %u exceeded.\n",
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200655 (unsigned) MAX_LADDER_DEPTH );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000656 return( EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200657 }
658 ladder[ladder_depth] = q;
659 ++ladder_depth;
660 }
661 else if( strcmp( argv[i], "master" ) == 0 )
662 key_file_name = q;
663 else if( strcmp( argv[i], "output" ) == 0 )
664 output_file_name = q;
665 else
666 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000667 printf( "Unknown option: %s\n", argv[i] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200668 goto usage_failure;
669 }
670 }
671
672 if( strcmp( argv[1], "generate" ) == 0 )
673 mode = MODE_GENERATE;
674 else if( strcmp( argv[1], "save" ) == 0 )
675 mode = MODE_SAVE;
676 else if( strcmp( argv[1], "unwrap" ) == 0 )
677 mode = MODE_UNWRAP;
678 else if( strcmp( argv[1], "wrap" ) == 0 )
679 mode = MODE_WRAP;
680 else
681 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000682 printf( "Unknown action: %s\n", argv[1] );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200683 goto usage_failure;
684 }
685
686 if( input_file_name == NULL &&
687 ( mode == MODE_WRAP || mode == MODE_UNWRAP ) )
688 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000689 printf( "Required argument missing: input\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200690 return( DEMO_ERROR );
691 }
692 if( output_file_name == NULL &&
693 ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) )
694 {
Jaeden Amerofa30c332018-12-21 18:42:18 +0000695 printf( "Required argument missing: output\n" );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200696 return( DEMO_ERROR );
697 }
698
699 status = run( mode, key_file_name,
700 ladder, ladder_depth,
701 input_file_name, output_file_name );
702 return( status == PSA_SUCCESS ?
Jaeden Amerofa30c332018-12-21 18:42:18 +0000703 EXIT_SUCCESS :
704 EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200705
706usage_failure:
707 usage( );
Jaeden Amerofa30c332018-12-21 18:42:18 +0000708 return( EXIT_FAILURE );
Gilles Peskinef0fa4362018-07-16 17:08:43 +0200709}
710#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */