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