xref: /freebsd/sys/contrib/openzfs/module/zfs/zio_crypt.c (revision 34f9f5680c9d5d5138e427ba3aeab0138cec3882)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2017, Datto, Inc. All rights reserved.
15  * Copyright (c) 2026, TrueNAS.
16  */
17 
18 #include <sys/zio_crypt.h>
19 #include <sys/dmu.h>
20 #include <sys/dmu_objset.h>
21 #include <sys/dnode.h>
22 #include <sys/fs/zfs.h>
23 #include <sys/zio.h>
24 #include <sys/zil.h>
25 #include <sys/sha2.h>
26 #include <sys/hkdf.h>
27 #include <sys/qat.h>
28 
29 /*
30  * This file is responsible for handling all of the details of generating
31  * encryption parameters and performing encryption and authentication.
32  *
33  * BLOCK ENCRYPTION PARAMETERS:
34  * Encryption /Authentication Algorithm Suite (crypt):
35  * The encryption algorithm, mode, and key length we are going to use. We
36  * currently support AES in either GCM or CCM modes with 128, 192, and 256 bit
37  * keys. All authentication is currently done with SHA512-HMAC.
38  *
39  * Plaintext:
40  * The unencrypted data that we want to encrypt.
41  *
42  * Initialization Vector (IV):
43  * An initialization vector for the encryption algorithms. This is used to
44  * "tweak" the encryption algorithms so that two blocks of the same data are
45  * encrypted into different ciphertext outputs, thus obfuscating block patterns.
46  * The supported encryption modes (AES-GCM and AES-CCM) require that an IV is
47  * never reused with the same encryption key. This value is stored unencrypted
48  * and must simply be provided to the decryption function. We use a 96 bit IV
49  * (as recommended by NIST) for all block encryption. For non-dedup blocks we
50  * derive the IV randomly. The first 64 bits of the IV are stored in the second
51  * word of DVA[2] and the remaining 32 bits are stored in the upper 32 bits of
52  * blk_fill. This is safe because encrypted blocks can't use the upper 32 bits
53  * of blk_fill. We only encrypt level 0 blocks, which normally have a fill count
54  * of 1. The only exception is for DMU_OT_DNODE objects, where the fill count of
55  * level 0 blocks is the number of allocated dnodes in that block. The on-disk
56  * format supports at most 2^15 slots per L0 dnode block, because the maximum
57  * block size is 16MB (2^24). In either case, for level 0 blocks this number
58  * will still be smaller than UINT32_MAX so it is safe to store the IV in the
59  * top 32 bits of blk_fill, while leaving the bottom 32 bits of the fill count
60  * for the dnode code.
61  *
62  * Master key:
63  * This is the most important secret data of an encrypted dataset. It is used
64  * along with the salt to generate that actual encryption keys via HKDF. We
65  * do not use the master key to directly encrypt any data because there are
66  * theoretical limits on how much data can actually be safely encrypted with
67  * any encryption mode. The master key is stored encrypted on disk with the
68  * user's wrapping key. Its length is determined by the encryption algorithm.
69  * For details on how this is stored see the block comment in dsl_crypt.c
70  *
71  * Salt:
72  * Used as an input to the HKDF function, along with the master key. We use a
73  * 64 bit salt, stored unencrypted in the first word of DVA[2]. Any given salt
74  * can be used for encrypting many blocks, so we cache the current salt and the
75  * associated derived key in zio_crypt_t so we do not need to derive it again
76  * needlessly.
77  *
78  * Encryption Key:
79  * A secret binary key, generated from an HKDF function used to encrypt and
80  * decrypt data.
81  *
82  * Message Authentication Code (MAC)
83  * The MAC is an output of authenticated encryption modes such as AES-GCM and
84  * AES-CCM. Its purpose is to ensure that an attacker cannot modify encrypted
85  * data on disk and return garbage to the application. Effectively, it is a
86  * checksum that can not be reproduced by an attacker. We store the MAC in the
87  * second 128 bits of blk_cksum, leaving the first 128 bits for a truncated
88  * regular checksum of the ciphertext which can be used for scrubbing.
89  *
90  * OBJECT AUTHENTICATION:
91  * Some object types, such as DMU_OT_MASTER_NODE cannot be encrypted because
92  * they contain some info that always needs to be readable. To prevent this
93  * data from being altered, we authenticate this data using SHA512-HMAC. This
94  * will produce a MAC (similar to the one produced via encryption) which can
95  * be used to verify the object was not modified. HMACs do not require key
96  * rotation or IVs, so we can keep up to the full 3 copies of authenticated
97  * data.
98  *
99  * ZIL ENCRYPTION:
100  * ZIL blocks have their bp written to disk ahead of the associated data, so we
101  * cannot store the MAC there as we normally do. For these blocks the MAC is
102  * stored in the embedded checksum within the zil_chain_t header. The salt and
103  * IV are generated for the block on bp allocation instead of at encryption
104  * time. In addition, ZIL blocks have some pieces that must be left in plaintext
105  * for claiming even though all of the sensitive user data still needs to be
106  * encrypted. The function zio_crypt_init_uios_zil() handles parsing which
107  * pieces of the block need to be encrypted. All data that is not encrypted is
108  * authenticated using the AAD mechanisms that the supported encryption modes
109  * provide for. In order to preserve the semantics of the ZIL for encrypted
110  * datasets, the ZIL is not protected at the objset level as described below.
111  *
112  * DNODE ENCRYPTION:
113  * Similarly to ZIL blocks, the core part of each dnode_phys_t needs to be left
114  * in plaintext for scrubbing and claiming, but the bonus buffers might contain
115  * sensitive user data. The function zio_crypt_init_uios_dnode() handles parsing
116  * which pieces of the block need to be encrypted. For more details about
117  * dnode authentication and encryption, see zio_crypt_init_uios_dnode().
118  *
119  * OBJECT SET AUTHENTICATION:
120  * Up to this point, everything we have encrypted and authenticated has been
121  * at level 0 (or -2 for the ZIL). If we did not do any further work the
122  * on-disk format would be susceptible to attacks that deleted or rearranged
123  * the order of level 0 blocks. Ideally, the cleanest solution would be to
124  * maintain a tree of authentication MACs going up the bp tree. However, this
125  * presents a problem for raw sends. Send files do not send information about
126  * indirect blocks so there would be no convenient way to transfer the MACs and
127  * they cannot be recalculated on the receive side without the master key which
128  * would defeat one of the purposes of raw sends in the first place. Instead,
129  * for the indirect levels of the bp tree, we use a regular SHA512 of the MACs
130  * from the level below. We also include some portable fields from blk_prop such
131  * as the lsize and compression algorithm to prevent the data from being
132  * misinterpreted.
133  *
134  * At the objset level, we maintain 2 separate 256 bit MACs in the
135  * objset_phys_t. The first one is "portable" and is the logical root of the
136  * MAC tree maintained in the metadnode's bps. The second, is "local" and is
137  * used as the root MAC for the user accounting objects, which are also not
138  * transferred via "zfs send". The portable MAC is sent in the DRR_BEGIN payload
139  * of the send file. The useraccounting code ensures that the useraccounting
140  * info is not present upon a receive, so the local MAC can simply be cleared
141  * out at that time. For more info about objset_phys_t authentication, see
142  * zio_crypt_do_objset_hmacs().
143  *
144  * CONSIDERATIONS FOR DEDUP:
145  * In order for dedup to work, blocks that we want to dedup with one another
146  * need to use the same IV and encryption key, so that they will have the same
147  * ciphertext. Normally, one should never reuse an IV with the same encryption
148  * key or else AES-GCM and AES-CCM can both actually leak the plaintext of both
149  * blocks. In this case, however, since we are using the same plaintext as
150  * well all that we end up with is a duplicate of the original ciphertext we
151  * already had. As a result, an attacker with read access to the raw disk will
152  * be able to tell which blocks are the same but this information is given away
153  * by dedup anyway. In order to get the same IVs and encryption keys for
154  * equivalent blocks of data we use an HMAC of the plaintext. We use an HMAC
155  * here so that a reproducible checksum of the plaintext is never available to
156  * the attacker. The HMAC key is kept alongside the master key, encrypted on
157  * disk. The first 64 bits of the HMAC are used in place of the random salt, and
158  * the next 96 bits are used as the IV. As a result of this mechanism, dedup
159  * will only work within a clone family since encrypted dedup requires use of
160  * the same master and HMAC keys.
161  */
162 
163 /*
164  * After encrypting many blocks with the same key we may start to run up
165  * against the theoretical limits of how much data can securely be encrypted
166  * with a single key using the supported encryption modes. The most obvious
167  * limitation is that our risk of generating 2 equivalent 96 bit IVs increases
168  * the more IVs we generate (which both GCM and CCM modes strictly forbid).
169  * This risk actually grows surprisingly quickly over time according to the
170  * Birthday Problem. With a total IV space of 2^(96 bits), and assuming we have
171  * generated n IVs with a cryptographically secure RNG, the approximate
172  * probability p(n) of a collision is given as:
173  *
174  * p(n) ~= e^(-n*(n-1)/(2*(2^96)))
175  *
176  * [http://www.math.cornell.edu/~mec/2008-2009/TianyiZheng/Birthday.html]
177  *
178  * Assuming that we want to ensure that p(n) never goes over 1 / 1 trillion
179  * we must not write more than 398,065,730 blocks with the same encryption key.
180  * Therefore, we rotate our keys after 400,000,000 blocks have been written by
181  * generating a new random 64 bit salt for our HKDF encryption key generation
182  * function.
183  */
184 #define	ZFS_KEY_MAX_SALT_USES_DEFAULT	400000000
185 #define	ZFS_CURRENT_MAX_SALT_USES	\
186 	(MIN(zfs_key_max_salt_uses, ZFS_KEY_MAX_SALT_USES_DEFAULT))
187 uint64_t zfs_key_max_salt_uses = ZFS_KEY_MAX_SALT_USES_DEFAULT;
188 
189 typedef struct blkptr_auth_buf {
190 	uint64_t bab_prop;			/* blk_prop - portable mask */
191 	uint8_t bab_mac[ZIO_DATA_MAC_LEN];	/* MAC from blk_cksum */
192 	uint64_t bab_pad;			/* reserved for future use */
193 } blkptr_auth_buf_t;
194 
195 const zio_crypt_info_t zio_crypt_table[ZIO_CRYPT_FUNCTIONS] = {
196 	{"",			ZC_TYPE_NONE,	0,	"inherit"},
197 	{"",			ZC_TYPE_NONE,	0,	"on"},
198 	{"",			ZC_TYPE_NONE,	0,	"off"},
199 	{SUN_CKM_AES_CCM,	ZC_TYPE_CCM,	16,	"aes-128-ccm"},
200 	{SUN_CKM_AES_CCM,	ZC_TYPE_CCM,	24,	"aes-192-ccm"},
201 	{SUN_CKM_AES_CCM,	ZC_TYPE_CCM,	32,	"aes-256-ccm"},
202 	{SUN_CKM_AES_GCM,	ZC_TYPE_GCM,	16,	"aes-128-gcm"},
203 	{SUN_CKM_AES_GCM,	ZC_TYPE_GCM,	24,	"aes-192-gcm"},
204 	{SUN_CKM_AES_GCM,	ZC_TYPE_GCM,	32,	"aes-256-gcm"}
205 };
206 
207 void
zio_crypt_key_destroy(zio_crypt_key_t * key)208 zio_crypt_key_destroy(zio_crypt_key_t *key)
209 {
210 	zio_crypt_key_close_os(key);
211 
212 	rw_destroy(&key->zk_salt_lock);
213 
214 	/* zero out sensitive data */
215 	memset(key, 0, sizeof (zio_crypt_key_t));
216 }
217 
218 int
zio_crypt_key_init(uint64_t crypt,zio_crypt_key_t * key)219 zio_crypt_key_init(uint64_t crypt, zio_crypt_key_t *key)
220 {
221 	int ret;
222 
223 	ASSERT3P(key, !=, NULL);
224 	ASSERT3U(crypt, <, ZIO_CRYPT_FUNCTIONS);
225 
226 	const zio_crypt_info_t *ci = &zio_crypt_table[crypt];
227 	if (ci->ci_crypt_type != ZC_TYPE_GCM &&
228 	    ci->ci_crypt_type != ZC_TYPE_CCM)
229 		return (ENOTSUP);
230 
231 	memset(key, 0, sizeof (zio_crypt_key_t));
232 
233 	/* fill keydata buffers and salt with random data */
234 	ret = random_get_bytes((uint8_t *)&key->zk_guid, sizeof (uint64_t));
235 	if (ret != 0)
236 		return (ret);
237 
238 	ret = random_get_bytes(key->zk_master_keydata, ci->ci_keylen);
239 	if (ret != 0)
240 		return (ret);
241 
242 	ret = random_get_bytes(key->zk_hmac_keydata, SHA512_HMAC_KEYLEN);
243 	if (ret != 0)
244 		return (ret);
245 
246 	ret = random_get_bytes(key->zk_salt, ZIO_DATA_SALT_LEN);
247 	if (ret != 0)
248 		return (ret);
249 
250 	/* derive the current key from the master key */
251 	ret = hkdf_sha512(key->zk_master_keydata, ci->ci_keylen, NULL, 0,
252 	    key->zk_salt, ZIO_DATA_SALT_LEN, key->zk_current_keydata,
253 	    ci->ci_keylen);
254 	if (ret != 0)
255 		return (ret);
256 
257 	/* initialize keys for the ICP */
258 	key->zk_current_key.ck_data = key->zk_current_keydata;
259 	key->zk_current_key.ck_length = CRYPTO_BYTES2BITS(ci->ci_keylen);
260 
261 	key->zk_hmac_key.ck_data = &key->zk_hmac_key;
262 	key->zk_hmac_key.ck_length = CRYPTO_BYTES2BITS(SHA512_HMAC_KEYLEN);
263 
264 	ret = zio_crypt_key_open_os(key, ci);
265 	if (ret != 0)
266 		return (ret);
267 
268 	rw_init(&key->zk_salt_lock, NULL, RW_DEFAULT, NULL);
269 	key->zk_crypt = crypt;
270 	key->zk_version = ZIO_CRYPT_KEY_CURRENT_VERSION;
271 	key->zk_salt_count = 0;
272 
273 	return (0);
274 }
275 
276 static int
zio_crypt_key_change_salt(zio_crypt_key_t * key)277 zio_crypt_key_change_salt(zio_crypt_key_t *key)
278 {
279 	int ret = 0;
280 	uint8_t salt[ZIO_DATA_SALT_LEN];
281 	const zio_crypt_info_t *ci = &zio_crypt_table[key->zk_crypt];
282 
283 	/* generate a new salt */
284 	ret = random_get_bytes(salt, ZIO_DATA_SALT_LEN);
285 	if (ret != 0)
286 		goto error;
287 
288 	rw_enter(&key->zk_salt_lock, RW_WRITER);
289 
290 	/* someone beat us to the salt rotation, just unlock and return */
291 	if (key->zk_salt_count < ZFS_CURRENT_MAX_SALT_USES)
292 		goto out_unlock;
293 
294 	/* derive the current key from the master key and the new salt */
295 	ret = hkdf_sha512(key->zk_master_keydata, ci->ci_keylen, NULL, 0,
296 	    salt, ZIO_DATA_SALT_LEN, key->zk_current_keydata, ci->ci_keylen);
297 	if (ret != 0)
298 		goto out_unlock;
299 
300 	/* assign the salt and reset the usage count */
301 	memcpy(key->zk_salt, salt, ZIO_DATA_SALT_LEN);
302 	key->zk_salt_count = 0;
303 
304 	ret = zio_crypt_key_reopen_os(key, ci);
305 	if (ret != 0)
306 		goto out_unlock;
307 
308 	rw_exit(&key->zk_salt_lock);
309 
310 	return (0);
311 
312 out_unlock:
313 	rw_exit(&key->zk_salt_lock);
314 error:
315 	return (ret);
316 }
317 
318 /* See comment above zfs_key_max_salt_uses definition for details */
319 int
zio_crypt_key_get_salt(zio_crypt_key_t * key,uint8_t * salt)320 zio_crypt_key_get_salt(zio_crypt_key_t *key, uint8_t *salt)
321 {
322 	int ret;
323 	boolean_t salt_change;
324 
325 	rw_enter(&key->zk_salt_lock, RW_READER);
326 
327 	memcpy(salt, key->zk_salt, ZIO_DATA_SALT_LEN);
328 	salt_change = (atomic_inc_64_nv(&key->zk_salt_count) >=
329 	    ZFS_CURRENT_MAX_SALT_USES);
330 
331 	rw_exit(&key->zk_salt_lock);
332 
333 	if (salt_change) {
334 		ret = zio_crypt_key_change_salt(key);
335 		if (ret != 0)
336 			goto error;
337 	}
338 
339 	return (0);
340 
341 error:
342 	return (ret);
343 }
344 
345 int
zio_crypt_key_wrap(crypto_key_t * cwkey,zio_crypt_key_t * key,uint8_t * iv,uint8_t * mac,uint8_t * keydata_out,uint8_t * hmac_keydata_out)346 zio_crypt_key_wrap(crypto_key_t *cwkey, zio_crypt_key_t *key, uint8_t *iv,
347     uint8_t *mac, uint8_t *keydata_out, uint8_t *hmac_keydata_out)
348 {
349 	int ret;
350 	uint64_t aad[3];
351 	uint_t aad_len;
352 	const zio_crypt_info_t *ci = &zio_crypt_table[key->zk_crypt];
353 
354 	/* generate iv for wrapping the master and hmac key */
355 	ret = random_get_pseudo_bytes(iv, WRAPPING_IV_LEN);
356 	if (ret != 0)
357 		return (ret);
358 
359 	/*
360 	 * Although we don't support writing to the old format, we do
361 	 * support rewrapping the key so that the user can move and
362 	 * quarantine datasets on the old format.
363 	 */
364 	if (key->zk_version == 0) {
365 		aad_len = sizeof (uint64_t);
366 		aad[0] = LE_64(key->zk_guid);
367 	} else {
368 		ASSERT3U(key->zk_version, ==, ZIO_CRYPT_KEY_CURRENT_VERSION);
369 		aad_len = sizeof (uint64_t) * 3;
370 		aad[0] = LE_64(key->zk_guid);
371 		aad[1] = LE_64(key->zk_crypt);
372 		aad[2] = LE_64(key->zk_version);
373 	}
374 
375 	zfs_uio_t puio, cuio;
376 	int idx;
377 	ret = zio_crypt_uios_init_os(&puio, &cuio, 2, &idx);
378 	if (ret != 0)
379 		return (ret);
380 
381 	zfs_uio_iovbase(&puio, idx) = key->zk_master_keydata;
382 	zfs_uio_iovlen(&puio, idx) = ci->ci_keylen;
383 	zfs_uio_iovbase(&puio, idx+1) = key->zk_hmac_keydata;
384 	zfs_uio_iovlen(&puio, idx+1) = SHA512_HMAC_KEYLEN;
385 
386 	zfs_uio_iovbase(&cuio, idx) = keydata_out;
387 	zfs_uio_iovlen(&cuio, idx) = ci->ci_keylen;
388 	zfs_uio_iovbase(&cuio, idx+1) = hmac_keydata_out;
389 	zfs_uio_iovlen(&cuio, idx+1) = SHA512_HMAC_KEYLEN;
390 
391 	/* encrypt the keys and store the resulting ciphertext and mac */
392 	ret = zio_encrypt_os(ci, cwkey, NULL,
393 	    &puio, &cuio, ci->ci_keylen + SHA512_HMAC_KEYLEN,
394 	    iv, (uint8_t *)aad, aad_len, mac);
395 
396 	zio_crypt_uios_fini_os(&puio, &cuio);
397 
398 	return (ret);
399 }
400 
401 int
zio_crypt_key_unwrap(crypto_key_t * cwkey,uint64_t crypt,uint64_t version,uint64_t guid,uint8_t * keydata,uint8_t * hmac_keydata,uint8_t * iv,uint8_t * mac,zio_crypt_key_t * key)402 zio_crypt_key_unwrap(crypto_key_t *cwkey, uint64_t crypt, uint64_t version,
403     uint64_t guid, uint8_t *keydata, uint8_t *hmac_keydata, uint8_t *iv,
404     uint8_t *mac, zio_crypt_key_t *key)
405 {
406 	int ret;
407 	uint64_t aad[3];
408 	uint_t aad_len;
409 	const zio_crypt_info_t *ci = &zio_crypt_table[crypt];
410 
411 	ASSERT3U(crypt, <, ZIO_CRYPT_FUNCTIONS);
412 
413 	if (version == 0) {
414 		aad_len = sizeof (uint64_t);
415 		aad[0] = LE_64(guid);
416 	} else {
417 		ASSERT3U(version, ==, ZIO_CRYPT_KEY_CURRENT_VERSION);
418 		aad_len = sizeof (uint64_t) * 3;
419 		aad[0] = LE_64(guid);
420 		aad[1] = LE_64(crypt);
421 		aad[2] = LE_64(version);
422 	}
423 
424 	zfs_uio_t cuio, puio;
425 	int idx;
426 	ret = zio_crypt_uios_init_os(&cuio, &puio, 2, &idx);
427 	if (ret != 0)
428 		goto error;
429 
430 	zfs_uio_iovbase(&cuio, idx) = keydata;
431 	zfs_uio_iovlen(&cuio, idx) = ci->ci_keylen;
432 	zfs_uio_iovbase(&cuio, idx+1) = hmac_keydata;
433 	zfs_uio_iovlen(&cuio, idx+1) = SHA512_HMAC_KEYLEN;
434 
435 	zfs_uio_iovbase(&puio, idx) = key->zk_master_keydata;
436 	zfs_uio_iovlen(&puio, idx) = ci->ci_keylen;
437 	zfs_uio_iovbase(&puio, idx+1) = key->zk_hmac_keydata;
438 	zfs_uio_iovlen(&puio, idx+1) = SHA512_HMAC_KEYLEN;
439 
440 	ret = zio_decrypt_os(ci, cwkey, NULL,
441 	    &cuio, &puio, ci->ci_keylen + SHA512_HMAC_KEYLEN,
442 	    iv, (uint8_t *)aad, aad_len, mac);
443 
444 	zio_crypt_uios_fini_os(&cuio, &puio);
445 
446 	if (ret != 0)
447 		goto error;
448 
449 	/* generate a fresh salt */
450 	ret = random_get_bytes(key->zk_salt, ZIO_DATA_SALT_LEN);
451 	if (ret != 0)
452 		goto error;
453 
454 	/* derive the current key from the master key */
455 	ret = hkdf_sha512(key->zk_master_keydata, ci->ci_keylen, NULL, 0,
456 	    key->zk_salt, ZIO_DATA_SALT_LEN, key->zk_current_keydata,
457 	    ci->ci_keylen);
458 	if (ret != 0)
459 		goto error;
460 
461 	/* initialize keys for ICP */
462 	key->zk_current_key.ck_data = key->zk_current_keydata;
463 	key->zk_current_key.ck_length = CRYPTO_BYTES2BITS(ci->ci_keylen);
464 
465 	key->zk_hmac_key.ck_data = key->zk_hmac_keydata;
466 	key->zk_hmac_key.ck_length = CRYPTO_BYTES2BITS(SHA512_HMAC_KEYLEN);
467 
468 	ret = zio_crypt_key_open_os(key, ci);
469 	if (ret != 0)
470 		goto error;
471 
472 	rw_init(&key->zk_salt_lock, NULL, RW_DEFAULT, NULL);
473 	key->zk_crypt = crypt;
474 	key->zk_version = version;
475 	key->zk_guid = guid;
476 	key->zk_salt_count = 0;
477 
478 	return (0);
479 
480 error:
481 	memset(key, 0, sizeof (zio_crypt_key_t));
482 	return (ret);
483 }
484 
485 int
zio_crypt_generate_iv(uint8_t * ivbuf)486 zio_crypt_generate_iv(uint8_t *ivbuf)
487 {
488 	int ret;
489 
490 	/* randomly generate the IV */
491 	ret = random_get_pseudo_bytes(ivbuf, ZIO_DATA_IV_LEN);
492 	if (ret != 0)
493 		goto error;
494 
495 	return (0);
496 
497 error:
498 	memset(ivbuf, 0, ZIO_DATA_IV_LEN);
499 	return (ret);
500 }
501 
502 int
zio_crypt_do_hmac(zio_crypt_key_t * key,uint8_t * data,uint_t datalen,uint8_t * digestbuf,uint_t digestlen)503 zio_crypt_do_hmac(zio_crypt_key_t *key, uint8_t *data, uint_t datalen,
504     uint8_t *digestbuf, uint_t digestlen)
505 {
506 	uint8_t raw_digestbuf[SHA512_HMAC_LEN];
507 
508 	ASSERT3U(digestlen, <=, SHA512_HMAC_LEN);
509 
510 	int err = zio_crypt_hmac_os(key, data, datalen, raw_digestbuf);
511 	if (err == 0)
512 		memcpy(digestbuf, raw_digestbuf, digestlen);
513 	else
514 		memset(digestbuf, 0, digestlen);
515 
516 	return (err);
517 }
518 
519 int
zio_crypt_generate_iv_salt_dedup(zio_crypt_key_t * key,uint8_t * data,uint_t datalen,uint8_t * ivbuf,uint8_t * salt)520 zio_crypt_generate_iv_salt_dedup(zio_crypt_key_t *key, uint8_t *data,
521     uint_t datalen, uint8_t *ivbuf, uint8_t *salt)
522 {
523 	int ret;
524 	uint8_t digestbuf[SHA512_HMAC_LEN];
525 
526 	ret = zio_crypt_hmac_os(key, data, datalen, digestbuf);
527 	if (ret != 0)
528 		return (ret);
529 
530 	memcpy(salt, digestbuf, ZIO_DATA_SALT_LEN);
531 	memcpy(ivbuf, digestbuf + ZIO_DATA_SALT_LEN, ZIO_DATA_IV_LEN);
532 
533 	return (0);
534 }
535 
536 /*
537  * The following functions are used to encode and decode encryption parameters
538  * into blkptr_t and zil_header_t. The ICP wants to use these parameters as
539  * byte strings, which normally means that these strings would not need to deal
540  * with byteswapping at all. However, both blkptr_t and zil_header_t may be
541  * byteswapped by lower layers and so we must "undo" that byteswap here upon
542  * decoding and encoding in a non-native byteorder. These functions require
543  * that the byteorder bit is correct before being called.
544  */
545 void
zio_crypt_encode_params_bp(blkptr_t * bp,uint8_t * salt,uint8_t * iv)546 zio_crypt_encode_params_bp(blkptr_t *bp, uint8_t *salt, uint8_t *iv)
547 {
548 	uint64_t val64;
549 	uint32_t val32;
550 
551 	ASSERT(BP_IS_ENCRYPTED(bp));
552 
553 	if (!BP_SHOULD_BYTESWAP(bp)) {
554 		memcpy(&bp->blk_dva[2].dva_word[0], salt, sizeof (uint64_t));
555 		memcpy(&bp->blk_dva[2].dva_word[1], iv, sizeof (uint64_t));
556 		memcpy(&val32, iv + sizeof (uint64_t), sizeof (uint32_t));
557 		BP_SET_IV2(bp, val32);
558 	} else {
559 		memcpy(&val64, salt, sizeof (uint64_t));
560 		bp->blk_dva[2].dva_word[0] = BSWAP_64(val64);
561 
562 		memcpy(&val64, iv, sizeof (uint64_t));
563 		bp->blk_dva[2].dva_word[1] = BSWAP_64(val64);
564 
565 		memcpy(&val32, iv + sizeof (uint64_t), sizeof (uint32_t));
566 		BP_SET_IV2(bp, BSWAP_32(val32));
567 	}
568 }
569 
570 void
zio_crypt_decode_params_bp(const blkptr_t * bp,uint8_t * salt,uint8_t * iv)571 zio_crypt_decode_params_bp(const blkptr_t *bp, uint8_t *salt, uint8_t *iv)
572 {
573 	uint64_t val64;
574 	uint32_t val32;
575 
576 	ASSERT(BP_IS_PROTECTED(bp));
577 
578 	/* for convenience, so callers don't need to check */
579 	if (BP_IS_AUTHENTICATED(bp)) {
580 		memset(salt, 0, ZIO_DATA_SALT_LEN);
581 		memset(iv, 0, ZIO_DATA_IV_LEN);
582 		return;
583 	}
584 
585 	if (!BP_SHOULD_BYTESWAP(bp)) {
586 		memcpy(salt, &bp->blk_dva[2].dva_word[0], sizeof (uint64_t));
587 		memcpy(iv, &bp->blk_dva[2].dva_word[1], sizeof (uint64_t));
588 
589 		val32 = (uint32_t)BP_GET_IV2(bp);
590 		memcpy(iv + sizeof (uint64_t), &val32, sizeof (uint32_t));
591 	} else {
592 		val64 = BSWAP_64(bp->blk_dva[2].dva_word[0]);
593 		memcpy(salt, &val64, sizeof (uint64_t));
594 
595 		val64 = BSWAP_64(bp->blk_dva[2].dva_word[1]);
596 		memcpy(iv, &val64, sizeof (uint64_t));
597 
598 		val32 = BSWAP_32((uint32_t)BP_GET_IV2(bp));
599 		memcpy(iv + sizeof (uint64_t), &val32, sizeof (uint32_t));
600 	}
601 }
602 
603 void
zio_crypt_encode_mac_bp(blkptr_t * bp,uint8_t * mac)604 zio_crypt_encode_mac_bp(blkptr_t *bp, uint8_t *mac)
605 {
606 	uint64_t val64;
607 
608 	ASSERT(BP_USES_CRYPT(bp));
609 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_OBJSET);
610 
611 	if (!BP_SHOULD_BYTESWAP(bp)) {
612 		memcpy(&bp->blk_cksum.zc_word[2], mac, sizeof (uint64_t));
613 		memcpy(&bp->blk_cksum.zc_word[3], mac + sizeof (uint64_t),
614 		    sizeof (uint64_t));
615 	} else {
616 		memcpy(&val64, mac, sizeof (uint64_t));
617 		bp->blk_cksum.zc_word[2] = BSWAP_64(val64);
618 
619 		memcpy(&val64, mac + sizeof (uint64_t), sizeof (uint64_t));
620 		bp->blk_cksum.zc_word[3] = BSWAP_64(val64);
621 	}
622 }
623 
624 void
zio_crypt_decode_mac_bp(const blkptr_t * bp,uint8_t * mac)625 zio_crypt_decode_mac_bp(const blkptr_t *bp, uint8_t *mac)
626 {
627 	uint64_t val64;
628 
629 	ASSERT(BP_USES_CRYPT(bp) || BP_IS_HOLE(bp));
630 
631 	/* for convenience, so callers don't need to check */
632 	if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
633 		memset(mac, 0, ZIO_DATA_MAC_LEN);
634 		return;
635 	}
636 
637 	if (!BP_SHOULD_BYTESWAP(bp)) {
638 		memcpy(mac, &bp->blk_cksum.zc_word[2], sizeof (uint64_t));
639 		memcpy(mac + sizeof (uint64_t), &bp->blk_cksum.zc_word[3],
640 		    sizeof (uint64_t));
641 	} else {
642 		val64 = BSWAP_64(bp->blk_cksum.zc_word[2]);
643 		memcpy(mac, &val64, sizeof (uint64_t));
644 
645 		val64 = BSWAP_64(bp->blk_cksum.zc_word[3]);
646 		memcpy(mac + sizeof (uint64_t), &val64, sizeof (uint64_t));
647 	}
648 }
649 
650 void
zio_crypt_encode_mac_zil(void * data,uint8_t * mac)651 zio_crypt_encode_mac_zil(void *data, uint8_t *mac)
652 {
653 	zil_chain_t *zilc = data;
654 
655 	memcpy(&zilc->zc_eck.zec_cksum.zc_word[2], mac, sizeof (uint64_t));
656 	memcpy(&zilc->zc_eck.zec_cksum.zc_word[3], mac + sizeof (uint64_t),
657 	    sizeof (uint64_t));
658 }
659 
660 void
zio_crypt_decode_mac_zil(const void * data,uint8_t * mac)661 zio_crypt_decode_mac_zil(const void *data, uint8_t *mac)
662 {
663 	/*
664 	 * The ZIL MAC is embedded in the block it protects, which will
665 	 * not have been byteswapped by the time this function has been called.
666 	 * As a result, we don't need to worry about byteswapping the MAC.
667 	 */
668 	const zil_chain_t *zilc = data;
669 
670 	memcpy(mac, &zilc->zc_eck.zec_cksum.zc_word[2], sizeof (uint64_t));
671 	memcpy(mac + sizeof (uint64_t), &zilc->zc_eck.zec_cksum.zc_word[3],
672 	    sizeof (uint64_t));
673 }
674 
675 /*
676  * This routine takes a block of dnodes (src_abd) and copies only the bonus
677  * buffers to the same offsets in the dst buffer. datalen should be the size
678  * of both the src_abd and the dst buffer (not just the length of the bonus
679  * buffers).
680  */
681 void
zio_crypt_copy_dnode_bonus(abd_t * src_abd,uint8_t * dst,uint_t datalen)682 zio_crypt_copy_dnode_bonus(abd_t *src_abd, uint8_t *dst, uint_t datalen)
683 {
684 	uint_t i, max_dnp = datalen >> DNODE_SHIFT;
685 	uint8_t *src;
686 	dnode_phys_t *dnp, *sdnp, *ddnp;
687 
688 	src = abd_borrow_buf_copy(src_abd, datalen);
689 
690 	sdnp = (dnode_phys_t *)src;
691 	ddnp = (dnode_phys_t *)dst;
692 
693 	for (i = 0; i < max_dnp; i += sdnp[i].dn_extra_slots + 1) {
694 		dnp = &sdnp[i];
695 		if (dnp->dn_type != DMU_OT_NONE &&
696 		    DMU_OT_IS_ENCRYPTED(dnp->dn_bonustype) &&
697 		    dnp->dn_bonuslen != 0) {
698 			memcpy(DN_BONUS(&ddnp[i]), DN_BONUS(dnp),
699 			    DN_MAX_BONUS_LEN(dnp));
700 		}
701 	}
702 
703 	abd_return_buf(src_abd, src, datalen);
704 }
705 
706 /*
707  * This function decides what fields from blk_prop are included in
708  * the on-disk various MAC algorithms.
709  */
710 static void
zio_crypt_bp_zero_nonportable_blkprop(blkptr_t * bp,uint64_t version)711 zio_crypt_bp_zero_nonportable_blkprop(blkptr_t *bp, uint64_t version)
712 {
713 	/*
714 	 * Version 0 did not properly zero out all non-portable fields
715 	 * as it should have done. We maintain this code so that we can
716 	 * do read-only imports of pools on this version.
717 	 */
718 	if (version == 0) {
719 		BP_SET_DEDUP(bp, 0);
720 		BP_SET_CHECKSUM(bp, 0);
721 		BP_SET_PSIZE(bp, SPA_MINBLOCKSIZE);
722 		return;
723 	}
724 
725 	ASSERT3U(version, ==, ZIO_CRYPT_KEY_CURRENT_VERSION);
726 
727 	/*
728 	 * The hole_birth feature might set these fields even if this bp
729 	 * is a hole. We zero them out here to guarantee that raw sends
730 	 * will function with or without the feature.
731 	 */
732 	if (BP_IS_HOLE(bp)) {
733 		bp->blk_prop = 0ULL;
734 		return;
735 	}
736 
737 	/*
738 	 * At L0 we want to verify these fields to ensure that data blocks
739 	 * can not be reinterpreted. For instance, we do not want an attacker
740 	 * to trick us into returning raw lz4 compressed data to the user
741 	 * by modifying the compression bits. At higher levels, we cannot
742 	 * enforce this policy since raw sends do not convey any information
743 	 * about indirect blocks, so these values might be different on the
744 	 * receive side. Fortunately, this does not open any new attack
745 	 * vectors, since any alterations that can be made to a higher level
746 	 * bp must still verify the correct order of the layer below it.
747 	 */
748 	if (BP_GET_LEVEL(bp) != 0) {
749 		BP_SET_BYTEORDER(bp, 0);
750 		BP_SET_COMPRESS(bp, 0);
751 
752 		/*
753 		 * psize cannot be set to zero or it will trigger
754 		 * asserts, but the value doesn't really matter as
755 		 * long as it is constant.
756 		 */
757 		BP_SET_PSIZE(bp, SPA_MINBLOCKSIZE);
758 	}
759 
760 	BP_SET_DEDUP(bp, 0);
761 	BP_SET_CHECKSUM(bp, 0);
762 }
763 
764 static void
zio_crypt_bp_auth_init(uint64_t version,boolean_t should_bswap,blkptr_t * bp,blkptr_auth_buf_t * bab,uint_t * bab_len)765 zio_crypt_bp_auth_init(uint64_t version, boolean_t should_bswap, blkptr_t *bp,
766     blkptr_auth_buf_t *bab, uint_t *bab_len)
767 {
768 	blkptr_t tmpbp = *bp;
769 
770 	if (should_bswap)
771 		byteswap_uint64_array(&tmpbp, sizeof (blkptr_t));
772 
773 	ASSERT(BP_USES_CRYPT(&tmpbp) || BP_IS_HOLE(&tmpbp));
774 	ASSERT0(BP_IS_EMBEDDED(&tmpbp));
775 
776 	zio_crypt_decode_mac_bp(&tmpbp, bab->bab_mac);
777 
778 	/*
779 	 * We always MAC blk_prop in LE to ensure portability. This
780 	 * must be done after decoding the mac, since the endianness
781 	 * will get zero'd out here.
782 	 */
783 	zio_crypt_bp_zero_nonportable_blkprop(&tmpbp, version);
784 	bab->bab_prop = LE_64(tmpbp.blk_prop);
785 	bab->bab_pad = 0ULL;
786 
787 	/* version 0 did not include the padding */
788 	*bab_len = sizeof (blkptr_auth_buf_t);
789 	if (version == 0)
790 		*bab_len -= sizeof (uint64_t);
791 }
792 
793 static int
zio_crypt_bp_do_hmac_updates(zio_crypt_hmac_t * hmac,uint64_t version,boolean_t should_bswap,blkptr_t * bp)794 zio_crypt_bp_do_hmac_updates(zio_crypt_hmac_t *hmac, uint64_t version,
795     boolean_t should_bswap, blkptr_t *bp)
796 {
797 	uint_t bab_len;
798 	blkptr_auth_buf_t bab;
799 
800 	zio_crypt_bp_auth_init(version, should_bswap, bp, &bab, &bab_len);
801 	return (zio_crypt_hmac_update_os(hmac, (uint8_t *)&bab, bab_len));
802 }
803 
804 static void
zio_crypt_bp_do_indrect_checksum_updates(SHA2_CTX * ctx,uint64_t version,boolean_t should_bswap,blkptr_t * bp)805 zio_crypt_bp_do_indrect_checksum_updates(SHA2_CTX *ctx, uint64_t version,
806     boolean_t should_bswap, blkptr_t *bp)
807 {
808 	uint_t bab_len;
809 	blkptr_auth_buf_t bab;
810 
811 	zio_crypt_bp_auth_init(version, should_bswap, bp, &bab, &bab_len);
812 	SHA2Update(ctx, &bab, bab_len);
813 }
814 
815 static void
zio_crypt_bp_do_aad_updates(uint8_t ** aadp,uint_t * aad_len,uint64_t version,boolean_t should_bswap,blkptr_t * bp)816 zio_crypt_bp_do_aad_updates(uint8_t **aadp, uint_t *aad_len, uint64_t version,
817     boolean_t should_bswap, blkptr_t *bp)
818 {
819 	uint_t bab_len;
820 	blkptr_auth_buf_t bab;
821 
822 	zio_crypt_bp_auth_init(version, should_bswap, bp, &bab, &bab_len);
823 	memcpy(*aadp, &bab, bab_len);
824 	*aadp += bab_len;
825 	*aad_len += bab_len;
826 }
827 
828 static int
zio_crypt_do_dnode_hmac_updates(zio_crypt_hmac_t * hmac,uint64_t version,boolean_t should_bswap,dnode_phys_t * dnp)829 zio_crypt_do_dnode_hmac_updates(zio_crypt_hmac_t *hmac, uint64_t version,
830     boolean_t should_bswap, dnode_phys_t *dnp)
831 {
832 	int ret, i;
833 	dnode_phys_t *adnp, tmp_dncore;
834 	size_t dn_core_size = offsetof(dnode_phys_t, dn_blkptr);
835 	boolean_t le_bswap = (should_bswap == ZFS_HOST_BYTEORDER);
836 
837 	/*
838 	 * Authenticate the core dnode (masking out non-portable bits).
839 	 * We only copy the first 64 bytes we operate on to avoid the overhead
840 	 * of copying 512-64 unneeded bytes. The compiler seems to be fine
841 	 * with that.
842 	 */
843 	memcpy(&tmp_dncore, dnp, dn_core_size);
844 	adnp = &tmp_dncore;
845 
846 	if (le_bswap) {
847 		adnp->dn_datablkszsec = BSWAP_16(adnp->dn_datablkszsec);
848 		adnp->dn_bonuslen = BSWAP_16(adnp->dn_bonuslen);
849 		adnp->dn_maxblkid = BSWAP_64(adnp->dn_maxblkid);
850 		adnp->dn_used = BSWAP_64(adnp->dn_used);
851 	}
852 	adnp->dn_flags &= DNODE_CRYPT_PORTABLE_FLAGS_MASK;
853 	adnp->dn_used = 0;
854 
855 	ret = zio_crypt_hmac_update_os(hmac, (uint8_t *)adnp, dn_core_size);
856 	if (ret != 0)
857 		goto error;
858 
859 	for (i = 0; i < dnp->dn_nblkptr; i++) {
860 		ret = zio_crypt_bp_do_hmac_updates(hmac, version,
861 		    should_bswap, &dnp->dn_blkptr[i]);
862 		if (ret != 0)
863 			goto error;
864 	}
865 
866 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
867 		ret = zio_crypt_bp_do_hmac_updates(hmac, version,
868 		    should_bswap, DN_SPILL_BLKPTR(dnp));
869 		if (ret != 0)
870 			goto error;
871 	}
872 
873 	return (0);
874 
875 error:
876 	return (ret);
877 }
878 
879 /*
880  * objset_phys_t blocks introduce a number of exceptions to the normal
881  * authentication process. objset_phys_t's contain 2 separate HMACS for
882  * protecting the integrity of their data. The portable_mac protects the
883  * metadnode. This MAC can be sent with a raw send and protects against
884  * reordering of data within the metadnode. The local_mac protects the user
885  * accounting objects which are not sent from one system to another.
886  *
887  * In addition, objset blocks are the only blocks that can be modified and
888  * written to disk without the key loaded under certain circumstances. During
889  * zil_claim() we need to be able to update the zil_header_t to complete
890  * claiming log blocks and during raw receives we need to write out the
891  * portable_mac from the send file. Both of these actions are possible
892  * because these fields are not protected by either MAC so neither one will
893  * need to modify the MACs without the key. However, when the modified blocks
894  * are written out they will be byteswapped into the host machine's native
895  * endianness which will modify fields protected by the MAC. As a result, MAC
896  * calculation for objset blocks works slightly differently from other block
897  * types. Where other block types MAC the data in whatever endianness is
898  * written to disk, objset blocks always MAC little endian version of their
899  * values. In the code, should_bswap is the value from BP_SHOULD_BYTESWAP()
900  * and le_bswap indicates whether a byteswap is needed to get this block
901  * into little endian format.
902  */
903 int
zio_crypt_do_objset_hmacs(zio_crypt_key_t * key,void * data,uint_t datalen,boolean_t should_bswap,uint8_t * portable_mac,uint8_t * local_mac)904 zio_crypt_do_objset_hmacs(zio_crypt_key_t *key, void *data, uint_t datalen,
905     boolean_t should_bswap, uint8_t *portable_mac, uint8_t *local_mac)
906 {
907 	int err;
908 	zio_crypt_hmac_t hmac;
909 	objset_phys_t *osp = data;
910 	uint64_t intval;
911 	boolean_t le_bswap = (should_bswap == ZFS_HOST_BYTEORDER);
912 	uint8_t raw_portable_mac[SHA512_HMAC_LEN];
913 	uint8_t raw_local_mac[SHA512_HMAC_LEN];
914 
915 	/* calculate the portable MAC from the portable fields and metadnode */
916 	err = zio_crypt_hmac_init_os(&hmac, key);
917 	if (err)
918 		goto error;
919 
920 	/* add in the os_type */
921 	intval = (le_bswap) ? osp->os_type : BSWAP_64(osp->os_type);
922 	err = zio_crypt_hmac_update_os(&hmac, (const uint8_t *)&intval,
923 	    sizeof (intval));
924 	if (err)
925 		goto error;
926 
927 	/* add in the portable os_flags */
928 	intval = osp->os_flags;
929 	if (should_bswap)
930 		intval = BSWAP_64(intval);
931 	intval &= OBJSET_CRYPT_PORTABLE_FLAGS_MASK;
932 	if (!ZFS_HOST_BYTEORDER)
933 		intval = BSWAP_64(intval);
934 
935 	err = zio_crypt_hmac_update_os(&hmac, (const uint8_t *)&intval,
936 	    sizeof (intval));
937 	if (err)
938 		goto error;
939 
940 	/* add in fields from the metadnode */
941 	err = zio_crypt_do_dnode_hmac_updates(&hmac, key->zk_version,
942 	    should_bswap, &osp->os_meta_dnode);
943 	if (err)
944 		goto error;
945 
946 	/* store the final digest in a temporary buffer and copy what we need */
947 	err = zio_crypt_hmac_final_os(&hmac, raw_portable_mac);
948 	if (err)
949 		goto error;
950 
951 	memcpy(portable_mac, raw_portable_mac, ZIO_OBJSET_MAC_LEN);
952 
953 	/*
954 	 * This is necessary here as we check next whether
955 	 * OBJSET_FLAG_USERACCOUNTING_COMPLETE is set in order to
956 	 * decide if the local_mac should be zeroed out. That flag will always
957 	 * be set by dmu_objset_id_quota_upgrade_cb() and
958 	 * dmu_objset_userspace_upgrade_cb() if useraccounting has been
959 	 * completed.
960 	 */
961 	intval = osp->os_flags;
962 	if (should_bswap)
963 		intval = BSWAP_64(intval);
964 	boolean_t uacct_incomplete =
965 	    !(intval & OBJSET_FLAG_USERACCOUNTING_COMPLETE);
966 
967 	/*
968 	 * The local MAC protects the user, group and project accounting.
969 	 * If these objects are not present, the local MAC is zeroed out.
970 	 */
971 	if (uacct_incomplete ||
972 	    (datalen >= OBJSET_PHYS_SIZE_V3 &&
973 	    osp->os_userused_dnode.dn_type == DMU_OT_NONE &&
974 	    osp->os_groupused_dnode.dn_type == DMU_OT_NONE &&
975 	    osp->os_projectused_dnode.dn_type == DMU_OT_NONE) ||
976 	    (datalen >= OBJSET_PHYS_SIZE_V2 &&
977 	    osp->os_userused_dnode.dn_type == DMU_OT_NONE &&
978 	    osp->os_groupused_dnode.dn_type == DMU_OT_NONE) ||
979 	    (datalen <= OBJSET_PHYS_SIZE_V1)) {
980 		memset(local_mac, 0, ZIO_OBJSET_MAC_LEN);
981 		return (0);
982 	}
983 
984 	/* calculate the local MAC from the userused and groupused dnodes */
985 	err = zio_crypt_hmac_init_os(&hmac, key);
986 	if (err)
987 		goto error;
988 
989 	/* add in the non-portable os_flags */
990 	intval = osp->os_flags;
991 	if (should_bswap)
992 		intval = BSWAP_64(intval);
993 	intval &= ~OBJSET_CRYPT_PORTABLE_FLAGS_MASK;
994 	if (!ZFS_HOST_BYTEORDER)
995 		intval = BSWAP_64(intval);
996 
997 	err = zio_crypt_hmac_update_os(&hmac, (const uint8_t *)&intval,
998 	    sizeof (intval));
999 	if (err)
1000 		goto error;
1001 
1002 	/* add in fields from the user accounting dnodes */
1003 	if (osp->os_userused_dnode.dn_type != DMU_OT_NONE) {
1004 		err = zio_crypt_do_dnode_hmac_updates(&hmac, key->zk_version,
1005 		    should_bswap, &osp->os_userused_dnode);
1006 		if (err)
1007 			goto error;
1008 	}
1009 
1010 	if (osp->os_groupused_dnode.dn_type != DMU_OT_NONE) {
1011 		err = zio_crypt_do_dnode_hmac_updates(&hmac, key->zk_version,
1012 		    should_bswap, &osp->os_groupused_dnode);
1013 		if (err)
1014 			goto error;
1015 	}
1016 
1017 	if (osp->os_projectused_dnode.dn_type != DMU_OT_NONE &&
1018 	    datalen >= OBJSET_PHYS_SIZE_V3) {
1019 		err = zio_crypt_do_dnode_hmac_updates(&hmac, key->zk_version,
1020 		    should_bswap, &osp->os_projectused_dnode);
1021 		if (err)
1022 			goto error;
1023 	}
1024 
1025 	/* store the final digest in a temporary buffer and copy what we need */
1026 	err = zio_crypt_hmac_final_os(&hmac, raw_local_mac);
1027 	if (err)
1028 		goto error;
1029 
1030 	memcpy(local_mac, raw_local_mac, ZIO_OBJSET_MAC_LEN);
1031 
1032 	return (0);
1033 
1034 error:
1035 	memset(portable_mac, 0, ZIO_OBJSET_MAC_LEN);
1036 	memset(local_mac, 0, ZIO_OBJSET_MAC_LEN);
1037 	return (err);
1038 }
1039 
1040 /*
1041  * This function parses an uncompressed indirect block and returns a checksum
1042  * of all the portable fields from all of the contained bps. The portable
1043  * fields are the MAC and all of the fields from blk_prop except for the dedup,
1044  * checksum, and psize bits. For an explanation of the purpose of this, see
1045  * the comment block on object set authentication.
1046  */
1047 static int
zio_crypt_do_indirect_mac_checksum_impl(boolean_t generate,void * buf,uint_t datalen,uint64_t version,boolean_t byteswap,uint8_t * cksum)1048 zio_crypt_do_indirect_mac_checksum_impl(boolean_t generate, void *buf,
1049     uint_t datalen, uint64_t version, boolean_t byteswap, uint8_t *cksum)
1050 {
1051 	blkptr_t *bp;
1052 	int i, epb = datalen >> SPA_BLKPTRSHIFT;
1053 	SHA2_CTX ctx;
1054 	uint8_t digestbuf[SHA512_HMAC_LEN];
1055 
1056 	/* checksum all of the MACs from the layer below */
1057 	SHA2Init(SHA512, &ctx);
1058 	for (i = 0, bp = buf; i < epb; i++, bp++) {
1059 		zio_crypt_bp_do_indrect_checksum_updates(&ctx, version,
1060 		    byteswap, bp);
1061 	}
1062 	SHA2Final(digestbuf, &ctx);
1063 
1064 	if (generate) {
1065 		memcpy(cksum, digestbuf, ZIO_DATA_MAC_LEN);
1066 		return (0);
1067 	}
1068 
1069 	if (memcmp(digestbuf, cksum, ZIO_DATA_MAC_LEN) != 0)
1070 		return (SET_ERROR(ECKSUM));
1071 
1072 	return (0);
1073 }
1074 
1075 int
zio_crypt_do_indirect_mac_checksum(boolean_t generate,void * buf,uint_t datalen,boolean_t byteswap,uint8_t * cksum)1076 zio_crypt_do_indirect_mac_checksum(boolean_t generate, void *buf,
1077     uint_t datalen, boolean_t byteswap, uint8_t *cksum)
1078 {
1079 	int ret;
1080 
1081 	/*
1082 	 * Unfortunately, callers of this function will not always have
1083 	 * easy access to the on-disk format version. This info is
1084 	 * normally found in the DSL Crypto Key, but the checksum-of-MACs
1085 	 * is expected to be verifiable even when the key isn't loaded.
1086 	 * Here, instead of doing a ZAP lookup for the version for each
1087 	 * zio, we simply try both existing formats.
1088 	 */
1089 	ret = zio_crypt_do_indirect_mac_checksum_impl(generate, buf,
1090 	    datalen, ZIO_CRYPT_KEY_CURRENT_VERSION, byteswap, cksum);
1091 	if (ret == ECKSUM) {
1092 		ASSERT(!generate);
1093 		ret = zio_crypt_do_indirect_mac_checksum_impl(generate,
1094 		    buf, datalen, 0, byteswap, cksum);
1095 	}
1096 
1097 	return (ret);
1098 }
1099 
1100 int
zio_crypt_do_indirect_mac_checksum_abd(boolean_t generate,abd_t * abd,uint_t datalen,boolean_t byteswap,uint8_t * cksum)1101 zio_crypt_do_indirect_mac_checksum_abd(boolean_t generate, abd_t *abd,
1102     uint_t datalen, boolean_t byteswap, uint8_t *cksum)
1103 {
1104 	int ret;
1105 	void *buf;
1106 
1107 	buf = abd_borrow_buf_copy(abd, datalen);
1108 	ret = zio_crypt_do_indirect_mac_checksum(generate, buf, datalen,
1109 	    byteswap, cksum);
1110 	abd_return_buf(abd, buf, datalen);
1111 
1112 	return (ret);
1113 }
1114 
1115 /*
1116  * Special case handling routine for encrypting / decrypting ZIL blocks.
1117  * We do not check for the older ZIL chain because the encryption feature
1118  * was not available before the newer ZIL chain was introduced. The goal
1119  * here is to encrypt everything except the blkptr_t of a lr_write_t and
1120  * the zil_chain_t header. Everything that is not encrypted is authenticated.
1121  */
1122 static int
zio_crypt_init_uios_zil(boolean_t encrypt,uint8_t * plainbuf,uint8_t * cipherbuf,uint_t datalen,boolean_t byteswap,zfs_uio_t * puio,zfs_uio_t * cuio,uint_t * enc_len,uint8_t ** authbuf,uint_t * auth_len,boolean_t * no_crypt)1123 zio_crypt_init_uios_zil(boolean_t encrypt, uint8_t *plainbuf,
1124     uint8_t *cipherbuf, uint_t datalen, boolean_t byteswap, zfs_uio_t *puio,
1125     zfs_uio_t *cuio, uint_t *enc_len, uint8_t **authbuf, uint_t *auth_len,
1126     boolean_t *no_crypt)
1127 {
1128 	uint64_t txtype, lr_len, nused;
1129 	uint_t crypt_len;
1130 	uint_t aad_len = 0, nr_iovecs = 0, total_len = 0;
1131 	uint8_t *src, *dst, *slrp, *dlrp, *blkend, *aadp;
1132 	int idx;
1133 	iovec_t *src_iovecs, *dst_iovecs;
1134 	zil_chain_t *zilc;
1135 	lr_t *lr;
1136 
1137 	if (encrypt) {
1138 		src = plainbuf;
1139 		dst = cipherbuf;
1140 	} else {
1141 		src = cipherbuf;
1142 		dst = plainbuf;
1143 	}
1144 	memset(dst, 0, datalen);
1145 
1146 	/* find the start and end record of the log block */
1147 	zilc = (zil_chain_t *)src;
1148 	slrp = src + sizeof (zil_chain_t);
1149 	nused = ((byteswap) ? BSWAP_64(zilc->zc_nused) : zilc->zc_nused);
1150 	ASSERT3U(nused, >=, sizeof (zil_chain_t));
1151 	ASSERT3U(nused, <=, datalen);
1152 	blkend = src + nused;
1153 
1154 	/* calculate the number of encrypted iovecs we will need */
1155 	for (; slrp < blkend; slrp += lr_len) {
1156 		lr = (lr_t *)slrp;
1157 
1158 		if (!byteswap) {
1159 			txtype = lr->lrc_txtype;
1160 			lr_len = lr->lrc_reclen;
1161 		} else {
1162 			txtype = BSWAP_64(lr->lrc_txtype);
1163 			lr_len = BSWAP_64(lr->lrc_reclen);
1164 		}
1165 		ASSERT3U(lr_len, >=, sizeof (lr_t));
1166 		ASSERT3U(lr_len, <=, blkend - slrp);
1167 
1168 		nr_iovecs++;
1169 		if (txtype == TX_WRITE && lr_len != sizeof (lr_write_t))
1170 			nr_iovecs++;
1171 	}
1172 
1173 	int err = zio_crypt_uios_init_os(puio, cuio, nr_iovecs, &idx);
1174 	if (err != 0)
1175 		return (err);
1176 
1177 	if (encrypt) {
1178 		src_iovecs = zfs_uio_iov(puio);
1179 		dst_iovecs = zfs_uio_iov(cuio);
1180 	} else {
1181 		src_iovecs = zfs_uio_iov(cuio);
1182 		dst_iovecs = zfs_uio_iov(puio);
1183 	}
1184 
1185 	/*
1186 	 * Copy the plain zil header over and authenticate everything except
1187 	 * the checksum that will store our MAC. If we are writing the data
1188 	 * the embedded checksum will not have been calculated yet, so we don't
1189 	 * authenticate that.
1190 	 */
1191 	uint8_t *aadbuf = zio_buf_alloc(datalen);
1192 	aadp = aadbuf;
1193 	memcpy(dst, src, sizeof (zil_chain_t));
1194 	memcpy(aadp, src, sizeof (zil_chain_t) - sizeof (zio_eck_t));
1195 	aadp += sizeof (zil_chain_t) - sizeof (zio_eck_t);
1196 	aad_len += sizeof (zil_chain_t) - sizeof (zio_eck_t);
1197 
1198 	/* loop over records again, filling in iovecs */
1199 	nr_iovecs = 0;
1200 	slrp = src + sizeof (zil_chain_t);
1201 	dlrp = dst + sizeof (zil_chain_t);
1202 
1203 	for (; slrp < blkend; slrp += lr_len, dlrp += lr_len) {
1204 		lr = (lr_t *)slrp;
1205 
1206 		if (!byteswap) {
1207 			txtype = lr->lrc_txtype;
1208 			lr_len = lr->lrc_reclen;
1209 		} else {
1210 			txtype = BSWAP_64(lr->lrc_txtype);
1211 			lr_len = BSWAP_64(lr->lrc_reclen);
1212 		}
1213 
1214 		/* copy the common lr_t */
1215 		memcpy(dlrp, slrp, sizeof (lr_t));
1216 		memcpy(aadp, slrp, sizeof (lr_t));
1217 		aadp += sizeof (lr_t);
1218 		aad_len += sizeof (lr_t);
1219 
1220 		ASSERT3P(src_iovecs, !=, NULL);
1221 		ASSERT3P(dst_iovecs, !=, NULL);
1222 
1223 		/*
1224 		 * If this is a TX_WRITE record we want to encrypt everything
1225 		 * except the bp if exists. If the bp does exist we want to
1226 		 * authenticate it.
1227 		 */
1228 		if (txtype == TX_WRITE) {
1229 			const size_t o = offsetof(lr_write_t, lr_blkptr);
1230 			crypt_len = o - sizeof (lr_t);
1231 			src_iovecs[idx].iov_base = slrp + sizeof (lr_t);
1232 			src_iovecs[idx].iov_len = crypt_len;
1233 			dst_iovecs[idx].iov_base = dlrp + sizeof (lr_t);
1234 			dst_iovecs[idx].iov_len = crypt_len;
1235 			idx++;
1236 
1237 			/* copy the bp now since it will not be encrypted */
1238 			memcpy(dlrp + o, slrp + o, sizeof (blkptr_t));
1239 			memcpy(aadp, slrp + o, sizeof (blkptr_t));
1240 			aadp += sizeof (blkptr_t);
1241 			aad_len += sizeof (blkptr_t);
1242 			nr_iovecs++;
1243 			total_len += crypt_len;
1244 
1245 			if (lr_len != sizeof (lr_write_t)) {
1246 				crypt_len = lr_len - sizeof (lr_write_t);
1247 				src_iovecs[idx].iov_base =
1248 				    slrp + sizeof (lr_write_t);
1249 				src_iovecs[idx].iov_len = crypt_len;
1250 				dst_iovecs[idx].iov_base =
1251 				    dlrp + sizeof (lr_write_t);
1252 				dst_iovecs[idx].iov_len = crypt_len;
1253 				idx++;
1254 				nr_iovecs++;
1255 				total_len += crypt_len;
1256 			}
1257 		} else if (txtype == TX_CLONE_RANGE) {
1258 			const size_t o = offsetof(lr_clone_range_t, lr_nbps);
1259 			crypt_len = o - sizeof (lr_t);
1260 			src_iovecs[idx].iov_base = slrp + sizeof (lr_t);
1261 			src_iovecs[idx].iov_len = crypt_len;
1262 			dst_iovecs[idx].iov_base = dlrp + sizeof (lr_t);
1263 			dst_iovecs[idx].iov_len = crypt_len;
1264 			idx++;
1265 
1266 			/* copy the bps now since they will not be encrypted */
1267 			memcpy(dlrp + o, slrp + o, lr_len - o);
1268 			memcpy(aadp, slrp + o, lr_len - o);
1269 			aadp += lr_len - o;
1270 			aad_len += lr_len - o;
1271 			nr_iovecs++;
1272 			total_len += crypt_len;
1273 		} else {
1274 			crypt_len = lr_len - sizeof (lr_t);
1275 			src_iovecs[idx].iov_base = slrp + sizeof (lr_t);
1276 			src_iovecs[idx].iov_len = crypt_len;
1277 			dst_iovecs[idx].iov_base = dlrp + sizeof (lr_t);
1278 			dst_iovecs[idx].iov_len = crypt_len;
1279 			idx++;
1280 			nr_iovecs++;
1281 			total_len += crypt_len;
1282 		}
1283 	}
1284 
1285 	*no_crypt = (nr_iovecs == 0);
1286 	*enc_len = total_len;
1287 	*authbuf = aadbuf;
1288 	*auth_len = aad_len;
1289 
1290 	return (0);
1291 }
1292 
1293 /*
1294  * Special case handling routine for encrypting / decrypting dnode blocks.
1295  */
1296 static int
zio_crypt_init_uios_dnode(boolean_t encrypt,uint64_t version,uint8_t * plainbuf,uint8_t * cipherbuf,uint_t datalen,boolean_t byteswap,zfs_uio_t * puio,zfs_uio_t * cuio,uint_t * enc_len,uint8_t ** authbuf,uint_t * auth_len,boolean_t * no_crypt)1297 zio_crypt_init_uios_dnode(boolean_t encrypt, uint64_t version,
1298     uint8_t *plainbuf, uint8_t *cipherbuf, uint_t datalen, boolean_t byteswap,
1299     zfs_uio_t *puio, zfs_uio_t *cuio, uint_t *enc_len, uint8_t **authbuf,
1300     uint_t *auth_len, boolean_t *no_crypt)
1301 {
1302 	uint_t crypt_len;
1303 	uint_t aad_len = 0, nr_iovecs = 0, total_len = 0;
1304 	uint_t i, j, max_dnp = datalen >> DNODE_SHIFT;
1305 	uint8_t *src, *dst, *aadp;
1306 	int idx;
1307 	iovec_t *src_iovecs, *dst_iovecs;
1308 	dnode_phys_t *dnp, *adnp, *sdnp, *ddnp;
1309 
1310 	if (encrypt) {
1311 		src = plainbuf;
1312 		dst = cipherbuf;
1313 	} else {
1314 		src = cipherbuf;
1315 		dst = plainbuf;
1316 	}
1317 
1318 	sdnp = (dnode_phys_t *)src;
1319 	ddnp = (dnode_phys_t *)dst;
1320 
1321 	/*
1322 	 * Count the number of iovecs we will need to do the encryption by
1323 	 * counting the number of bonus buffers that need to be encrypted.
1324 	 */
1325 	for (i = 0; i < max_dnp; i += sdnp[i].dn_extra_slots + 1) {
1326 		/*
1327 		 * This block may still be byteswapped. However, all of the
1328 		 * values we use are either uint8_t's (for which byteswapping
1329 		 * is a noop) or a * != 0 check, which will work regardless
1330 		 * of whether or not we byteswap.
1331 		 */
1332 		if (sdnp[i].dn_type != DMU_OT_NONE &&
1333 		    DMU_OT_IS_ENCRYPTED(sdnp[i].dn_bonustype) &&
1334 		    sdnp[i].dn_bonuslen != 0) {
1335 			nr_iovecs++;
1336 		}
1337 	}
1338 
1339 	int err = zio_crypt_uios_init_os(puio, cuio, nr_iovecs, &idx);
1340 	if (err != 0)
1341 		return (err);
1342 
1343 	if (encrypt) {
1344 		src_iovecs = zfs_uio_iov(puio);
1345 		dst_iovecs = zfs_uio_iov(cuio);
1346 	} else {
1347 		src_iovecs = zfs_uio_iov(cuio);
1348 		dst_iovecs = zfs_uio_iov(puio);
1349 	}
1350 
1351 	nr_iovecs = 0;
1352 
1353 	uint8_t *aadbuf = zio_buf_alloc(datalen);
1354 	aadp = aadbuf;
1355 
1356 	/*
1357 	 * Iterate through the dnodes again, this time filling in the uios
1358 	 * we allocated earlier. We also concatenate any data we want to
1359 	 * authenticate onto aadbuf.
1360 	 */
1361 	for (i = 0; i < max_dnp; i += sdnp[i].dn_extra_slots + 1) {
1362 		dnp = &sdnp[i];
1363 
1364 		/* copy over the core fields and blkptrs (kept as plaintext) */
1365 		memcpy(&ddnp[i], dnp,
1366 		    (uint8_t *)DN_BONUS(dnp) - (uint8_t *)dnp);
1367 
1368 		if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1369 			memcpy(DN_SPILL_BLKPTR(&ddnp[i]), DN_SPILL_BLKPTR(dnp),
1370 			    sizeof (blkptr_t));
1371 		}
1372 
1373 		/*
1374 		 * Handle authenticated data. We authenticate everything in
1375 		 * the dnode that can be brought over when we do a raw send.
1376 		 * This includes all of the core fields as well as the MACs
1377 		 * stored in the bp checksums and all of the portable bits
1378 		 * from blk_prop. We include the dnode padding here in case it
1379 		 * ever gets used in the future. Some dn_flags and dn_used are
1380 		 * not portable so we mask those out values out of the
1381 		 * authenticated data.
1382 		 */
1383 		crypt_len = offsetof(dnode_phys_t, dn_blkptr);
1384 		memcpy(aadp, dnp, crypt_len);
1385 		adnp = (dnode_phys_t *)aadp;
1386 		adnp->dn_flags &= DNODE_CRYPT_PORTABLE_FLAGS_MASK;
1387 		adnp->dn_used = 0;
1388 		aadp += crypt_len;
1389 		aad_len += crypt_len;
1390 
1391 		for (j = 0; j < dnp->dn_nblkptr; j++) {
1392 			zio_crypt_bp_do_aad_updates(&aadp, &aad_len,
1393 			    version, byteswap, &dnp->dn_blkptr[j]);
1394 		}
1395 
1396 		if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
1397 			zio_crypt_bp_do_aad_updates(&aadp, &aad_len,
1398 			    version, byteswap, DN_SPILL_BLKPTR(dnp));
1399 		}
1400 
1401 		/*
1402 		 * If this bonus buffer needs to be encrypted, we prepare an
1403 		 * iovec_t. The encryption / decryption functions will fill
1404 		 * this in for us with the encrypted or decrypted data.
1405 		 * Otherwise we add the bonus buffer to the authenticated
1406 		 * data buffer and copy it over to the destination. The
1407 		 * encrypted iovec extends to DN_MAX_BONUS_LEN(dnp) so that
1408 		 * we can guarantee alignment with the AES block size
1409 		 * (128 bits).
1410 		 */
1411 		crypt_len = DN_MAX_BONUS_LEN(dnp);
1412 		if (dnp->dn_type != DMU_OT_NONE &&
1413 		    DMU_OT_IS_ENCRYPTED(dnp->dn_bonustype) &&
1414 		    dnp->dn_bonuslen != 0) {
1415 			ASSERT3P(src_iovecs, !=, NULL);
1416 			ASSERT3P(dst_iovecs, !=, NULL);
1417 			src_iovecs[idx].iov_base = DN_BONUS(dnp);
1418 			src_iovecs[idx].iov_len = crypt_len;
1419 			dst_iovecs[idx].iov_base = DN_BONUS(&ddnp[i]);
1420 			dst_iovecs[idx].iov_len = crypt_len;
1421 			idx++;
1422 
1423 			nr_iovecs++;
1424 			total_len += crypt_len;
1425 		} else {
1426 			memcpy(DN_BONUS(&ddnp[i]), DN_BONUS(dnp), crypt_len);
1427 			memcpy(aadp, DN_BONUS(dnp), crypt_len);
1428 			aadp += crypt_len;
1429 			aad_len += crypt_len;
1430 		}
1431 	}
1432 
1433 	*no_crypt = (nr_iovecs == 0);
1434 	*enc_len = total_len;
1435 	*authbuf = aadbuf;
1436 	*auth_len = aad_len;
1437 
1438 	return (0);
1439 }
1440 
1441 static int
zio_crypt_init_uios_normal(boolean_t encrypt,uint8_t * plainbuf,uint8_t * cipherbuf,uint_t datalen,zfs_uio_t * puio,zfs_uio_t * cuio,uint_t * enc_len)1442 zio_crypt_init_uios_normal(boolean_t encrypt, uint8_t *plainbuf,
1443     uint8_t *cipherbuf, uint_t datalen, zfs_uio_t *puio, zfs_uio_t *cuio,
1444     uint_t *enc_len)
1445 {
1446 	(void) encrypt;
1447 
1448 	int idx;
1449 	int err = zio_crypt_uios_init_os(puio, cuio, 1, &idx);
1450 	if (err != 0)
1451 		return (err);
1452 
1453 	zfs_uio_iovbase(puio, idx) = plainbuf;
1454 	zfs_uio_iovlen(puio, idx) = datalen;
1455 	zfs_uio_iovbase(cuio, idx) = cipherbuf;
1456 	zfs_uio_iovlen(cuio, idx) = datalen;
1457 
1458 	*enc_len = datalen;
1459 
1460 	return (0);
1461 }
1462 
1463 /*
1464  * This function builds up the plaintext (puio) and ciphertext (cuio) uios so
1465  * that they can be used for encryption and decryption by zio_do_crypt_uio().
1466  * Most blocks will use zio_crypt_init_uios_normal(), with ZIL and dnode blocks
1467  * requiring special handling to parse out pieces that are to be encrypted. The
1468  * authbuf is used by these special cases to store additional authenticated
1469  * data (AAD) for the encryption modes.
1470  */
1471 static int
zio_crypt_init_uios(boolean_t encrypt,uint64_t version,dmu_object_type_t ot,uint8_t * plainbuf,uint8_t * cipherbuf,uint_t datalen,boolean_t byteswap,zfs_uio_t * puio,zfs_uio_t * cuio,uint_t * enc_len,uint8_t ** authbuf,uint_t * auth_len,boolean_t * no_crypt)1472 zio_crypt_init_uios(boolean_t encrypt, uint64_t version, dmu_object_type_t ot,
1473     uint8_t *plainbuf, uint8_t *cipherbuf, uint_t datalen, boolean_t byteswap,
1474     zfs_uio_t *puio, zfs_uio_t *cuio, uint_t *enc_len,
1475     uint8_t **authbuf, uint_t *auth_len, boolean_t *no_crypt)
1476 {
1477 	int err;
1478 
1479 	ASSERT(DMU_OT_IS_ENCRYPTED(ot) || ot == DMU_OT_NONE);
1480 
1481 	/* route to handler */
1482 	switch (ot) {
1483 	case DMU_OT_INTENT_LOG:
1484 		err = zio_crypt_init_uios_zil(encrypt, plainbuf, cipherbuf,
1485 		    datalen, byteswap, puio, cuio, enc_len, authbuf, auth_len,
1486 		    no_crypt);
1487 		break;
1488 	case DMU_OT_DNODE:
1489 		err = zio_crypt_init_uios_dnode(encrypt, version, plainbuf,
1490 		    cipherbuf, datalen, byteswap, puio, cuio, enc_len, authbuf,
1491 		    auth_len, no_crypt);
1492 		break;
1493 	default:
1494 		err = zio_crypt_init_uios_normal(encrypt, plainbuf, cipherbuf,
1495 		    datalen, puio, cuio, enc_len);
1496 		*authbuf = NULL;
1497 		*auth_len = 0;
1498 		*no_crypt = B_FALSE;
1499 		break;
1500 	}
1501 
1502 	if (err != 0)
1503 		return (err);
1504 
1505 	return (0);
1506 }
1507 
1508 /*
1509  * Primary encryption / decryption entrypoint for zio data.
1510  */
1511 int
zio_do_crypt_data(boolean_t encrypt,zio_crypt_key_t * key,dmu_object_type_t ot,boolean_t byteswap,uint8_t * salt,uint8_t * iv,uint8_t * mac,uint_t datalen,uint8_t * plainbuf,uint8_t * cipherbuf,boolean_t * no_crypt)1512 zio_do_crypt_data(boolean_t encrypt, zio_crypt_key_t *key,
1513     dmu_object_type_t ot, boolean_t byteswap, uint8_t *salt, uint8_t *iv,
1514     uint8_t *mac, uint_t datalen, uint8_t *plainbuf, uint8_t *cipherbuf,
1515     boolean_t *no_crypt)
1516 {
1517 	int ret;
1518 	boolean_t locked = B_FALSE;
1519 	const zio_crypt_info_t *ci = &zio_crypt_table[key->zk_crypt];
1520 	uint_t enc_len, auth_len;
1521 	zfs_uio_t puio, cuio;
1522 	uint8_t enc_keydata[MASTER_KEY_MAX_LEN];
1523 	crypto_key_t tmp_ckey, *ckey = NULL;
1524 	zio_crypt_session_t *sess;
1525 	uint8_t *authbuf = NULL;
1526 
1527 	memset(&puio, 0, sizeof (puio));
1528 	memset(&cuio, 0, sizeof (cuio));
1529 
1530 	/*
1531 	 * If the needed key is the current one, just use it. Otherwise we
1532 	 * need to generate a temporary one from the given salt + master key.
1533 	 * If we are encrypting, we must return a copy of the current salt
1534 	 * so that it can be stored in the blkptr_t.
1535 	 */
1536 	rw_enter(&key->zk_salt_lock, RW_READER);
1537 	locked = B_TRUE;
1538 
1539 	if (memcmp(salt, key->zk_salt, ZIO_DATA_SALT_LEN) == 0) {
1540 		ckey = &key->zk_current_key;
1541 		sess = &key->zk_current_sess;
1542 	} else {
1543 		rw_exit(&key->zk_salt_lock);
1544 		locked = B_FALSE;
1545 
1546 		ret = hkdf_sha512(key->zk_master_keydata, ci->ci_keylen, NULL,
1547 		    0, salt, ZIO_DATA_SALT_LEN, enc_keydata, ci->ci_keylen);
1548 		if (ret != 0)
1549 			goto error;
1550 
1551 		tmp_ckey.ck_data = enc_keydata;
1552 		tmp_ckey.ck_length = CRYPTO_BYTES2BITS(ci->ci_keylen);
1553 
1554 		ckey = &tmp_ckey;
1555 		sess = NULL;
1556 	}
1557 
1558 	/*
1559 	 * Attempt to use QAT acceleration if we can. We currently don't
1560 	 * do this for metadnode and ZIL blocks, since they have a much
1561 	 * more involved buffer layout and the qat_crypt() function only
1562 	 * works in-place.
1563 	 */
1564 	if (qat_crypt_use_accel(datalen) &&
1565 	    ot != DMU_OT_INTENT_LOG && ot != DMU_OT_DNODE) {
1566 		uint8_t *srcbuf, *dstbuf;
1567 
1568 		if (encrypt) {
1569 			srcbuf = plainbuf;
1570 			dstbuf = cipherbuf;
1571 		} else {
1572 			srcbuf = cipherbuf;
1573 			dstbuf = plainbuf;
1574 		}
1575 
1576 		ret = qat_crypt((encrypt) ? QAT_ENCRYPT : QAT_DECRYPT, srcbuf,
1577 		    dstbuf, NULL, 0, iv, mac, ckey, key->zk_crypt, datalen);
1578 		if (ret == CPA_STATUS_SUCCESS) {
1579 			if (locked) {
1580 				rw_exit(&key->zk_salt_lock);
1581 				locked = B_FALSE;
1582 			}
1583 
1584 			return (0);
1585 		}
1586 		/* If the hardware implementation fails fall back to software */
1587 	}
1588 
1589 	/* create uios for encryption */
1590 	ret = zio_crypt_init_uios(encrypt, key->zk_version, ot, plainbuf,
1591 	    cipherbuf, datalen, byteswap, &puio, &cuio, &enc_len,
1592 	    &authbuf, &auth_len, no_crypt);
1593 	if (ret != 0)
1594 		goto error;
1595 
1596 	/* perform the encryption / decryption in software */
1597 	if (encrypt)
1598 		ret = zio_encrypt_os(ci, ckey, sess, &puio, &cuio, enc_len,
1599 		    iv, authbuf, auth_len, mac);
1600 	else
1601 		ret = zio_decrypt_os(ci, ckey, sess, &cuio, &puio, enc_len,
1602 		    iv, authbuf, auth_len, mac);
1603 	if (ret != 0)
1604 		goto error;
1605 
1606 	if (locked) {
1607 		rw_exit(&key->zk_salt_lock);
1608 	}
1609 
1610 	if (authbuf != NULL)
1611 		zio_buf_free(authbuf, datalen);
1612 	if (ckey == &tmp_ckey)
1613 		memset(enc_keydata, 0, ci->ci_keylen);
1614 
1615 	zio_crypt_uios_fini_os(&puio, &cuio);
1616 
1617 	return (0);
1618 
1619 error:
1620 	if (locked)
1621 		rw_exit(&key->zk_salt_lock);
1622 	if (authbuf != NULL)
1623 		zio_buf_free(authbuf, datalen);
1624 	if (ckey == &tmp_ckey)
1625 		memset(enc_keydata, 0, ci->ci_keylen);
1626 	zio_crypt_uios_fini_os(&puio, &cuio);
1627 	return (SET_ERROR(ret));
1628 }
1629 
1630 /*
1631  * Simple wrapper around zio_do_crypt_data() to work with abd's instead of
1632  * linear buffers.
1633  */
1634 int
zio_do_crypt_abd(boolean_t encrypt,zio_crypt_key_t * key,dmu_object_type_t ot,boolean_t byteswap,uint8_t * salt,uint8_t * iv,uint8_t * mac,uint_t datalen,abd_t * pabd,abd_t * cabd,boolean_t * no_crypt)1635 zio_do_crypt_abd(boolean_t encrypt, zio_crypt_key_t *key, dmu_object_type_t ot,
1636     boolean_t byteswap, uint8_t *salt, uint8_t *iv, uint8_t *mac,
1637     uint_t datalen, abd_t *pabd, abd_t *cabd, boolean_t *no_crypt)
1638 {
1639 	int ret;
1640 	void *ptmp, *ctmp;
1641 
1642 	if (encrypt) {
1643 		ptmp = abd_borrow_buf_copy(pabd, datalen);
1644 		ctmp = abd_borrow_buf(cabd, datalen);
1645 	} else {
1646 		ptmp = abd_borrow_buf(pabd, datalen);
1647 		ctmp = abd_borrow_buf_copy(cabd, datalen);
1648 	}
1649 
1650 	ret = zio_do_crypt_data(encrypt, key, ot, byteswap, salt, iv, mac,
1651 	    datalen, ptmp, ctmp, no_crypt);
1652 	if (ret != 0)
1653 		goto error;
1654 
1655 	if (encrypt) {
1656 		abd_return_buf(pabd, ptmp, datalen);
1657 		abd_return_buf_copy(cabd, ctmp, datalen);
1658 	} else {
1659 		abd_return_buf_copy(pabd, ptmp, datalen);
1660 		abd_return_buf(cabd, ctmp, datalen);
1661 	}
1662 
1663 	return (0);
1664 
1665 error:
1666 	if (encrypt) {
1667 		abd_return_buf(pabd, ptmp, datalen);
1668 		abd_return_buf_copy(cabd, ctmp, datalen);
1669 	} else {
1670 		abd_return_buf_copy(pabd, ptmp, datalen);
1671 		abd_return_buf(cabd, ctmp, datalen);
1672 	}
1673 
1674 	return (SET_ERROR(ret));
1675 }
1676 
1677 ZFS_MODULE_PARAM(zfs, zfs_key_,  max_salt_uses, U64, ZMOD_RW,
1678 	"Max number of times a salt value can be used for generating "
1679 	"encryption keys before it is rotated");
1680