key_ladder_demo.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /**
  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 The Mbed TLS Contributors
  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. /* First include Mbed TLS headers to get the Mbed TLS configuration and
  49. * platform definitions that we'll use in this program. Also include
  50. * standard C headers for functions we'll use here. */
  51. #include "mbedtls/build_info.h"
  52. #include <stdlib.h>
  53. #include <stdio.h>
  54. #include <string.h>
  55. #include "mbedtls/platform.h" // for mbedtls_setbuf
  56. #include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
  57. #include <psa/crypto.h>
  58. /* If the build options we need are not enabled, compile a placeholder. */
  59. #if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
  60. !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
  61. !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO) || \
  62. defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
  63. int main(void)
  64. {
  65. printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
  66. "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
  67. "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
  68. "not defined and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER "
  69. "defined.\n");
  70. return 0;
  71. }
  72. #else
  73. /* The real program starts here. */
  74. /* Run a system function and bail out if it fails. */
  75. #define SYS_CHECK(expr) \
  76. do \
  77. { \
  78. if (!(expr)) \
  79. { \
  80. perror( #expr); \
  81. status = DEMO_ERROR; \
  82. goto exit; \
  83. } \
  84. } \
  85. while (0)
  86. /* Run a PSA function and bail out if it fails. */
  87. #define PSA_CHECK(expr) \
  88. do \
  89. { \
  90. status = (expr); \
  91. if (status != PSA_SUCCESS) \
  92. { \
  93. printf("Error %d at line %d: %s\n", \
  94. (int) status, \
  95. __LINE__, \
  96. #expr); \
  97. goto exit; \
  98. } \
  99. } \
  100. while (0)
  101. /* To report operational errors in this program, use an error code that is
  102. * different from every PSA error code. */
  103. #define DEMO_ERROR 120
  104. /* The maximum supported key ladder depth. */
  105. #define MAX_LADDER_DEPTH 10
  106. /* Salt to use when deriving an intermediate key. */
  107. #define DERIVE_KEY_SALT ((uint8_t *) "key_ladder_demo.derive")
  108. #define DERIVE_KEY_SALT_LENGTH (strlen((const char *) DERIVE_KEY_SALT))
  109. /* Salt to use when deriving a wrapping key. */
  110. #define WRAPPING_KEY_SALT ((uint8_t *) "key_ladder_demo.wrap")
  111. #define WRAPPING_KEY_SALT_LENGTH (strlen((const char *) WRAPPING_KEY_SALT))
  112. /* Size of the key derivation keys (applies both to the master key and
  113. * to intermediate keys). */
  114. #define KEY_SIZE_BYTES 40
  115. /* Algorithm for key derivation. */
  116. #define KDF_ALG PSA_ALG_HKDF(PSA_ALG_SHA_256)
  117. /* Type and size of the key used to wrap data. */
  118. #define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
  119. #define WRAPPING_KEY_BITS 128
  120. /* Cipher mode used to wrap data. */
  121. #define WRAPPING_ALG PSA_ALG_CCM
  122. /* Nonce size used to wrap data. */
  123. #define WRAPPING_IV_SIZE 13
  124. /* Header used in files containing wrapped data. We'll save this header
  125. * directly without worrying about data representation issues such as
  126. * integer sizes and endianness, because the data is meant to be read
  127. * back by the same program on the same machine. */
  128. #define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
  129. #define WRAPPED_DATA_MAGIC_LENGTH (sizeof(WRAPPED_DATA_MAGIC))
  130. typedef struct {
  131. char magic[WRAPPED_DATA_MAGIC_LENGTH];
  132. size_t ad_size; /* Size of the additional data, which is this header. */
  133. size_t payload_size; /* Size of the encrypted data. */
  134. /* Store the IV inside the additional data. It's convenient. */
  135. uint8_t iv[WRAPPING_IV_SIZE];
  136. } wrapped_data_header_t;
  137. /* The modes that this program can operate in (see usage). */
  138. enum program_mode {
  139. MODE_GENERATE,
  140. MODE_SAVE,
  141. MODE_UNWRAP,
  142. MODE_WRAP
  143. };
  144. /* Save a key to a file. In the real world, you may want to export a derived
  145. * key sometimes, to share it with another party. */
  146. static psa_status_t save_key(psa_key_id_t key,
  147. const char *output_file_name)
  148. {
  149. psa_status_t status = PSA_SUCCESS;
  150. uint8_t key_data[KEY_SIZE_BYTES];
  151. size_t key_size;
  152. FILE *key_file = NULL;
  153. PSA_CHECK(psa_export_key(key,
  154. key_data, sizeof(key_data),
  155. &key_size));
  156. SYS_CHECK((key_file = fopen(output_file_name, "wb")) != NULL);
  157. /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
  158. mbedtls_setbuf(key_file, NULL);
  159. SYS_CHECK(fwrite(key_data, 1, key_size, key_file) == key_size);
  160. SYS_CHECK(fclose(key_file) == 0);
  161. key_file = NULL;
  162. exit:
  163. if (key_file != NULL) {
  164. fclose(key_file);
  165. }
  166. return status;
  167. }
  168. /* Generate a master key for use in this demo.
  169. *
  170. * Normally a master key would be non-exportable. For the purpose of this
  171. * demo, we want to save it to a file, to avoid relying on the keystore
  172. * capability of the PSA crypto library. */
  173. static psa_status_t generate(const char *key_file_name)
  174. {
  175. psa_status_t status = PSA_SUCCESS;
  176. psa_key_id_t key = 0;
  177. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  178. psa_set_key_usage_flags(&attributes,
  179. PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
  180. psa_set_key_algorithm(&attributes, KDF_ALG);
  181. psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
  182. psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(KEY_SIZE_BYTES));
  183. PSA_CHECK(psa_generate_key(&attributes, &key));
  184. PSA_CHECK(save_key(key, key_file_name));
  185. exit:
  186. (void) psa_destroy_key(key);
  187. return status;
  188. }
  189. /* Load the master key from a file.
  190. *
  191. * In the real world, this master key would be stored in an internal memory
  192. * and the storage would be managed by the keystore capability of the PSA
  193. * crypto library. */
  194. static psa_status_t import_key_from_file(psa_key_usage_t usage,
  195. psa_algorithm_t alg,
  196. const char *key_file_name,
  197. psa_key_id_t *master_key)
  198. {
  199. psa_status_t status = PSA_SUCCESS;
  200. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  201. uint8_t key_data[KEY_SIZE_BYTES];
  202. size_t key_size;
  203. FILE *key_file = NULL;
  204. unsigned char extra_byte;
  205. SYS_CHECK((key_file = fopen(key_file_name, "rb")) != NULL);
  206. /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
  207. mbedtls_setbuf(key_file, NULL);
  208. SYS_CHECK((key_size = fread(key_data, 1, sizeof(key_data),
  209. key_file)) != 0);
  210. if (fread(&extra_byte, 1, 1, key_file) != 0) {
  211. printf("Key file too large (max: %u).\n",
  212. (unsigned) sizeof(key_data));
  213. status = DEMO_ERROR;
  214. goto exit;
  215. }
  216. SYS_CHECK(fclose(key_file) == 0);
  217. key_file = NULL;
  218. psa_set_key_usage_flags(&attributes, usage);
  219. psa_set_key_algorithm(&attributes, alg);
  220. psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
  221. PSA_CHECK(psa_import_key(&attributes, key_data, key_size, master_key));
  222. exit:
  223. if (key_file != NULL) {
  224. fclose(key_file);
  225. }
  226. mbedtls_platform_zeroize(key_data, sizeof(key_data));
  227. if (status != PSA_SUCCESS) {
  228. /* If the key creation hasn't happened yet or has failed,
  229. * *master_key is null. psa_destroy_key( 0 ) is
  230. * guaranteed to do nothing and return PSA_SUCCESS. */
  231. (void) psa_destroy_key(*master_key);
  232. *master_key = 0;
  233. }
  234. return status;
  235. }
  236. /* Derive the intermediate keys, using the list of labels provided on
  237. * the command line. On input, *key is the master key identifier.
  238. * This function destroys the master key. On successful output, *key
  239. * is the identifier of the final derived key.
  240. */
  241. static psa_status_t derive_key_ladder(const char *ladder[],
  242. size_t ladder_depth,
  243. psa_key_id_t *key)
  244. {
  245. psa_status_t status = PSA_SUCCESS;
  246. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  247. psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
  248. size_t i;
  249. psa_set_key_usage_flags(&attributes,
  250. PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
  251. psa_set_key_algorithm(&attributes, KDF_ALG);
  252. psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
  253. psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(KEY_SIZE_BYTES));
  254. /* For each label in turn, ... */
  255. for (i = 0; i < ladder_depth; i++) {
  256. /* Start deriving material from the master key (if i=0) or from
  257. * the current intermediate key (if i>0). */
  258. PSA_CHECK(psa_key_derivation_setup(&operation, KDF_ALG));
  259. PSA_CHECK(psa_key_derivation_input_bytes(
  260. &operation, PSA_KEY_DERIVATION_INPUT_SALT,
  261. DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH));
  262. PSA_CHECK(psa_key_derivation_input_key(
  263. &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
  264. *key));
  265. PSA_CHECK(psa_key_derivation_input_bytes(
  266. &operation, PSA_KEY_DERIVATION_INPUT_INFO,
  267. (uint8_t *) ladder[i], strlen(ladder[i])));
  268. /* When the parent key is not the master key, destroy it,
  269. * since it is no longer needed. */
  270. PSA_CHECK(psa_destroy_key(*key));
  271. *key = 0;
  272. /* Derive the next intermediate key from the parent key. */
  273. PSA_CHECK(psa_key_derivation_output_key(&attributes, &operation,
  274. key));
  275. PSA_CHECK(psa_key_derivation_abort(&operation));
  276. }
  277. exit:
  278. psa_key_derivation_abort(&operation);
  279. if (status != PSA_SUCCESS) {
  280. psa_destroy_key(*key);
  281. *key = 0;
  282. }
  283. return status;
  284. }
  285. /* Derive a wrapping key from the last intermediate key. */
  286. static psa_status_t derive_wrapping_key(psa_key_usage_t usage,
  287. psa_key_id_t derived_key,
  288. psa_key_id_t *wrapping_key)
  289. {
  290. psa_status_t status = PSA_SUCCESS;
  291. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  292. psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
  293. *wrapping_key = 0;
  294. /* Set up a key derivation operation from the key derived from
  295. * the master key. */
  296. PSA_CHECK(psa_key_derivation_setup(&operation, KDF_ALG));
  297. PSA_CHECK(psa_key_derivation_input_bytes(
  298. &operation, PSA_KEY_DERIVATION_INPUT_SALT,
  299. WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH));
  300. PSA_CHECK(psa_key_derivation_input_key(
  301. &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
  302. derived_key));
  303. PSA_CHECK(psa_key_derivation_input_bytes(
  304. &operation, PSA_KEY_DERIVATION_INPUT_INFO,
  305. NULL, 0));
  306. /* Create the wrapping key. */
  307. psa_set_key_usage_flags(&attributes, usage);
  308. psa_set_key_algorithm(&attributes, WRAPPING_ALG);
  309. psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
  310. psa_set_key_bits(&attributes, WRAPPING_KEY_BITS);
  311. PSA_CHECK(psa_key_derivation_output_key(&attributes, &operation,
  312. wrapping_key));
  313. exit:
  314. psa_key_derivation_abort(&operation);
  315. return status;
  316. }
  317. static psa_status_t wrap_data(const char *input_file_name,
  318. const char *output_file_name,
  319. psa_key_id_t wrapping_key)
  320. {
  321. psa_status_t status;
  322. FILE *input_file = NULL;
  323. FILE *output_file = NULL;
  324. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  325. psa_key_type_t key_type;
  326. long input_position;
  327. size_t input_size;
  328. size_t buffer_size = 0;
  329. unsigned char *buffer = NULL;
  330. size_t ciphertext_size;
  331. wrapped_data_header_t header;
  332. /* Find the size of the data to wrap. */
  333. SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
  334. /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
  335. mbedtls_setbuf(input_file, NULL);
  336. SYS_CHECK(fseek(input_file, 0, SEEK_END) == 0);
  337. SYS_CHECK((input_position = ftell(input_file)) != -1);
  338. #if LONG_MAX > SIZE_MAX
  339. if (input_position > SIZE_MAX) {
  340. printf("Input file too large.\n");
  341. status = DEMO_ERROR;
  342. goto exit;
  343. }
  344. #endif
  345. input_size = input_position;
  346. PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
  347. key_type = psa_get_key_type(&attributes);
  348. buffer_size =
  349. PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, input_size);
  350. /* Check for integer overflow. */
  351. if (buffer_size < input_size) {
  352. printf("Input file too large.\n");
  353. status = DEMO_ERROR;
  354. goto exit;
  355. }
  356. /* Load the data to wrap. */
  357. SYS_CHECK(fseek(input_file, 0, SEEK_SET) == 0);
  358. SYS_CHECK((buffer = calloc(1, buffer_size)) != NULL);
  359. SYS_CHECK(fread(buffer, 1, input_size, input_file) == input_size);
  360. SYS_CHECK(fclose(input_file) == 0);
  361. input_file = NULL;
  362. /* Construct a header. */
  363. memcpy(&header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH);
  364. header.ad_size = sizeof(header);
  365. header.payload_size = input_size;
  366. /* Wrap the data. */
  367. PSA_CHECK(psa_generate_random(header.iv, WRAPPING_IV_SIZE));
  368. PSA_CHECK(psa_aead_encrypt(wrapping_key, WRAPPING_ALG,
  369. header.iv, WRAPPING_IV_SIZE,
  370. (uint8_t *) &header, sizeof(header),
  371. buffer, input_size,
  372. buffer, buffer_size,
  373. &ciphertext_size));
  374. /* Write the output. */
  375. SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
  376. /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
  377. mbedtls_setbuf(output_file, NULL);
  378. SYS_CHECK(fwrite(&header, 1, sizeof(header),
  379. output_file) == sizeof(header));
  380. SYS_CHECK(fwrite(buffer, 1, ciphertext_size,
  381. output_file) == ciphertext_size);
  382. SYS_CHECK(fclose(output_file) == 0);
  383. output_file = NULL;
  384. exit:
  385. if (input_file != NULL) {
  386. fclose(input_file);
  387. }
  388. if (output_file != NULL) {
  389. fclose(output_file);
  390. }
  391. if (buffer != NULL) {
  392. mbedtls_platform_zeroize(buffer, buffer_size);
  393. }
  394. free(buffer);
  395. return status;
  396. }
  397. static psa_status_t unwrap_data(const char *input_file_name,
  398. const char *output_file_name,
  399. psa_key_id_t wrapping_key)
  400. {
  401. psa_status_t status;
  402. FILE *input_file = NULL;
  403. FILE *output_file = NULL;
  404. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  405. psa_key_type_t key_type;
  406. unsigned char *buffer = NULL;
  407. size_t ciphertext_size = 0;
  408. size_t plaintext_size;
  409. wrapped_data_header_t header;
  410. unsigned char extra_byte;
  411. /* Load and validate the header. */
  412. SYS_CHECK((input_file = fopen(input_file_name, "rb")) != NULL);
  413. /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
  414. mbedtls_setbuf(input_file, NULL);
  415. SYS_CHECK(fread(&header, 1, sizeof(header),
  416. input_file) == sizeof(header));
  417. if (memcmp(&header.magic, WRAPPED_DATA_MAGIC,
  418. WRAPPED_DATA_MAGIC_LENGTH) != 0) {
  419. printf("The input does not start with a valid magic header.\n");
  420. status = DEMO_ERROR;
  421. goto exit;
  422. }
  423. if (header.ad_size != sizeof(header)) {
  424. printf("The header size is not correct.\n");
  425. status = DEMO_ERROR;
  426. goto exit;
  427. }
  428. PSA_CHECK(psa_get_key_attributes(wrapping_key, &attributes));
  429. key_type = psa_get_key_type(&attributes);
  430. ciphertext_size =
  431. PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, WRAPPING_ALG, header.payload_size);
  432. /* Check for integer overflow. */
  433. if (ciphertext_size < header.payload_size) {
  434. printf("Input file too large.\n");
  435. status = DEMO_ERROR;
  436. goto exit;
  437. }
  438. /* Load the payload data. */
  439. SYS_CHECK((buffer = calloc(1, ciphertext_size)) != NULL);
  440. SYS_CHECK(fread(buffer, 1, ciphertext_size,
  441. input_file) == ciphertext_size);
  442. if (fread(&extra_byte, 1, 1, input_file) != 0) {
  443. printf("Extra garbage after ciphertext\n");
  444. status = DEMO_ERROR;
  445. goto exit;
  446. }
  447. SYS_CHECK(fclose(input_file) == 0);
  448. input_file = NULL;
  449. /* Unwrap the data. */
  450. PSA_CHECK(psa_aead_decrypt(wrapping_key, WRAPPING_ALG,
  451. header.iv, WRAPPING_IV_SIZE,
  452. (uint8_t *) &header, sizeof(header),
  453. buffer, ciphertext_size,
  454. buffer, ciphertext_size,
  455. &plaintext_size));
  456. if (plaintext_size != header.payload_size) {
  457. printf("Incorrect payload size in the header.\n");
  458. status = DEMO_ERROR;
  459. goto exit;
  460. }
  461. /* Write the output. */
  462. SYS_CHECK((output_file = fopen(output_file_name, "wb")) != NULL);
  463. /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
  464. mbedtls_setbuf(output_file, NULL);
  465. SYS_CHECK(fwrite(buffer, 1, plaintext_size,
  466. output_file) == plaintext_size);
  467. SYS_CHECK(fclose(output_file) == 0);
  468. output_file = NULL;
  469. exit:
  470. if (input_file != NULL) {
  471. fclose(input_file);
  472. }
  473. if (output_file != NULL) {
  474. fclose(output_file);
  475. }
  476. if (buffer != NULL) {
  477. mbedtls_platform_zeroize(buffer, ciphertext_size);
  478. }
  479. free(buffer);
  480. return status;
  481. }
  482. static psa_status_t run(enum program_mode mode,
  483. const char *key_file_name,
  484. const char *ladder[], size_t ladder_depth,
  485. const char *input_file_name,
  486. const char *output_file_name)
  487. {
  488. psa_status_t status = PSA_SUCCESS;
  489. psa_key_id_t derivation_key = 0;
  490. psa_key_id_t wrapping_key = 0;
  491. /* Initialize the PSA crypto library. */
  492. PSA_CHECK(psa_crypto_init());
  493. /* Generate mode is unlike the others. Generate the master key and exit. */
  494. if (mode == MODE_GENERATE) {
  495. return generate(key_file_name);
  496. }
  497. /* Read the master key. */
  498. PSA_CHECK(import_key_from_file(PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
  499. KDF_ALG,
  500. key_file_name,
  501. &derivation_key));
  502. /* Calculate the derived key for this session. */
  503. PSA_CHECK(derive_key_ladder(ladder, ladder_depth,
  504. &derivation_key));
  505. switch (mode) {
  506. case MODE_SAVE:
  507. PSA_CHECK(save_key(derivation_key, output_file_name));
  508. break;
  509. case MODE_UNWRAP:
  510. PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_DECRYPT,
  511. derivation_key,
  512. &wrapping_key));
  513. PSA_CHECK(unwrap_data(input_file_name, output_file_name,
  514. wrapping_key));
  515. break;
  516. case MODE_WRAP:
  517. PSA_CHECK(derive_wrapping_key(PSA_KEY_USAGE_ENCRYPT,
  518. derivation_key,
  519. &wrapping_key));
  520. PSA_CHECK(wrap_data(input_file_name, output_file_name,
  521. wrapping_key));
  522. break;
  523. default:
  524. /* Unreachable but some compilers don't realize it. */
  525. break;
  526. }
  527. exit:
  528. /* Destroy any remaining key. Deinitializing the crypto library would do
  529. * this anyway since they are volatile keys, but explicitly destroying
  530. * keys makes the code easier to reuse. */
  531. (void) psa_destroy_key(derivation_key);
  532. (void) psa_destroy_key(wrapping_key);
  533. /* Deinitialize the PSA crypto library. */
  534. mbedtls_psa_crypto_free();
  535. return status;
  536. }
  537. static void usage(void)
  538. {
  539. printf("Usage: key_ladder_demo MODE [OPTION=VALUE]...\n");
  540. printf("Demonstrate the usage of a key derivation ladder.\n");
  541. printf("\n");
  542. printf("Modes:\n");
  543. printf(" generate Generate the master key\n");
  544. printf(" save Save the derived key\n");
  545. printf(" unwrap Unwrap (decrypt) input with the derived key\n");
  546. printf(" wrap Wrap (encrypt) input with the derived key\n");
  547. printf("\n");
  548. printf("Options:\n");
  549. printf(" input=FILENAME Input file (required for wrap/unwrap)\n");
  550. printf(" master=FILENAME File containing the master key (default: master.key)\n");
  551. printf(" output=FILENAME Output file (required for save/wrap/unwrap)\n");
  552. printf(" label=TEXT Label for the key derivation.\n");
  553. printf(" This may be repeated multiple times.\n");
  554. printf(" To get the same key, you must use the same master key\n");
  555. printf(" and the same sequence of labels.\n");
  556. }
  557. int main(int argc, char *argv[])
  558. {
  559. const char *key_file_name = "master.key";
  560. const char *input_file_name = NULL;
  561. const char *output_file_name = NULL;
  562. const char *ladder[MAX_LADDER_DEPTH];
  563. size_t ladder_depth = 0;
  564. int i;
  565. enum program_mode mode;
  566. psa_status_t status;
  567. if (argc <= 1 ||
  568. strcmp(argv[1], "help") == 0 ||
  569. strcmp(argv[1], "-help") == 0 ||
  570. strcmp(argv[1], "--help") == 0) {
  571. usage();
  572. return EXIT_SUCCESS;
  573. }
  574. for (i = 2; i < argc; i++) {
  575. char *q = strchr(argv[i], '=');
  576. if (q == NULL) {
  577. printf("Missing argument to option %s\n", argv[i]);
  578. goto usage_failure;
  579. }
  580. *q = 0;
  581. ++q;
  582. if (strcmp(argv[i], "input") == 0) {
  583. input_file_name = q;
  584. } else if (strcmp(argv[i], "label") == 0) {
  585. if (ladder_depth == MAX_LADDER_DEPTH) {
  586. printf("Maximum ladder depth %u exceeded.\n",
  587. (unsigned) MAX_LADDER_DEPTH);
  588. return EXIT_FAILURE;
  589. }
  590. ladder[ladder_depth] = q;
  591. ++ladder_depth;
  592. } else if (strcmp(argv[i], "master") == 0) {
  593. key_file_name = q;
  594. } else if (strcmp(argv[i], "output") == 0) {
  595. output_file_name = q;
  596. } else {
  597. printf("Unknown option: %s\n", argv[i]);
  598. goto usage_failure;
  599. }
  600. }
  601. if (strcmp(argv[1], "generate") == 0) {
  602. mode = MODE_GENERATE;
  603. } else if (strcmp(argv[1], "save") == 0) {
  604. mode = MODE_SAVE;
  605. } else if (strcmp(argv[1], "unwrap") == 0) {
  606. mode = MODE_UNWRAP;
  607. } else if (strcmp(argv[1], "wrap") == 0) {
  608. mode = MODE_WRAP;
  609. } else {
  610. printf("Unknown action: %s\n", argv[1]);
  611. goto usage_failure;
  612. }
  613. if (input_file_name == NULL &&
  614. (mode == MODE_WRAP || mode == MODE_UNWRAP)) {
  615. printf("Required argument missing: input\n");
  616. return DEMO_ERROR;
  617. }
  618. if (output_file_name == NULL &&
  619. (mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP)) {
  620. printf("Required argument missing: output\n");
  621. return DEMO_ERROR;
  622. }
  623. status = run(mode, key_file_name,
  624. ladder, ladder_depth,
  625. input_file_name, output_file_name);
  626. return status == PSA_SUCCESS ?
  627. EXIT_SUCCESS :
  628. EXIT_FAILURE;
  629. usage_failure:
  630. usage();
  631. return EXIT_FAILURE;
  632. }
  633. #endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C &&
  634. MBEDTLS_AES_C && MBEDTLS_CCM_C &&
  635. MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */