1 /* 2 * CDDL HEADER START 3 * 4 * This file and its contents are supplied under the terms of the 5 * Common Development and Distribution License ("CDDL"), version 1.0. 6 * You may only use this file in accordance with the terms of version 7 * 1.0 of the CDDL. 8 * 9 * A full copy of the text of the CDDL should have accompanied this 10 * source. A copy of the CDDL is also available via the Internet at 11 * http://www.illumos.org/license/CDDL. 12 * 13 * CDDL HEADER END 14 */ 15 16 /* 17 * Copyright (c) 2017, Datto, Inc. All rights reserved. 18 */ 19 20 #include <sys/dmu.h> 21 #include <sys/hkdf.h> 22 #include <sys/freebsd_crypto.h> 23 #include <sys/hkdf.h> 24 25 static int 26 hkdf_sha512_extract(uint8_t *salt, uint_t salt_len, uint8_t *key_material, 27 uint_t km_len, uint8_t *out_buf) 28 { 29 crypto_key_t key; 30 31 /* initialize the salt as a crypto key */ 32 key.ck_format = CRYPTO_KEY_RAW; 33 key.ck_length = CRYPTO_BYTES2BITS(salt_len); 34 key.ck_data = salt; 35 36 crypto_mac(&key, key_material, km_len, out_buf, SHA512_DIGEST_LENGTH); 37 38 return (0); 39 } 40 41 static int 42 hkdf_sha512_expand(uint8_t *extract_key, uint8_t *info, uint_t info_len, 43 uint8_t *out_buf, uint_t out_len) 44 { 45 struct hmac_ctx ctx; 46 crypto_key_t key; 47 uint_t i, T_len = 0, pos = 0; 48 uint8_t c; 49 uint_t N = (out_len + SHA512_DIGEST_LENGTH) / SHA512_DIGEST_LENGTH; 50 uint8_t T[SHA512_DIGEST_LENGTH]; 51 52 if (N > 255) 53 return (SET_ERROR(EINVAL)); 54 55 /* initialize the salt as a crypto key */ 56 key.ck_format = CRYPTO_KEY_RAW; 57 key.ck_length = CRYPTO_BYTES2BITS(SHA512_DIGEST_LENGTH); 58 key.ck_data = extract_key; 59 60 for (i = 1; i <= N; i++) { 61 c = i; 62 63 crypto_mac_init(&ctx, &key); 64 crypto_mac_update(&ctx, T, T_len); 65 crypto_mac_update(&ctx, info, info_len); 66 crypto_mac_update(&ctx, &c, 1); 67 crypto_mac_final(&ctx, T, SHA512_DIGEST_LENGTH); 68 bcopy(T, out_buf + pos, 69 (i != N) ? SHA512_DIGEST_LENGTH : (out_len - pos)); 70 pos += SHA512_DIGEST_LENGTH; 71 } 72 73 return (0); 74 } 75 76 /* 77 * HKDF is designed to be a relatively fast function for deriving keys from a 78 * master key + a salt. We use this function to generate new encryption keys 79 * so as to avoid hitting the cryptographic limits of the underlying 80 * encryption modes. Note that, for the sake of deriving encryption keys, the 81 * info parameter is called the "salt" everywhere else in the code. 82 */ 83 int 84 hkdf_sha512(uint8_t *key_material, uint_t km_len, uint8_t *salt, 85 uint_t salt_len, uint8_t *info, uint_t info_len, uint8_t *output_key, 86 uint_t out_len) 87 { 88 int ret; 89 uint8_t extract_key[SHA512_DIGEST_LENGTH]; 90 91 ret = hkdf_sha512_extract(salt, salt_len, key_material, km_len, 92 extract_key); 93 if (ret != 0) 94 return (ret); 95 96 ret = hkdf_sha512_expand(extract_key, info, info_len, output_key, 97 out_len); 98 if (ret != 0) 99 return (ret); 100 101 return (0); 102 } 103