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