xref: /illumos-gate/usr/src/uts/common/fs/zfs/dsl_crypt.c (revision cdd3e9a818787b4def17c9f707f435885ce0ed31)
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/dsl_crypt.h>
21 #include <sys/dsl_pool.h>
22 #include <sys/zap.h>
23 #include <sys/zil.h>
24 #include <sys/dsl_dir.h>
25 #include <sys/dsl_prop.h>
26 #include <sys/spa_impl.h>
27 #include <sys/dmu_objset.h>
28 #include <sys/zvol.h>
29 
30 /*
31  * This file's primary purpose is for managing master encryption keys in
32  * memory and on disk. For more info on how these keys are used, see the
33  * block comment in zio_crypt.c.
34  *
35  * All master keys are stored encrypted on disk in the form of the DSL
36  * Crypto Key ZAP object. The binary key data in this object is always
37  * randomly generated and is encrypted with the user's wrapping key. This
38  * layer of indirection allows the user to change their key without
39  * needing to re-encrypt the entire dataset. The ZAP also holds on to the
40  * (non-encrypted) encryption algorithm identifier, IV, and MAC needed to
41  * safely decrypt the master key. For more info on the user's key see the
42  * block comment in libzfs_crypto.c
43  *
44  * In-memory encryption keys are managed through the spa_keystore. The
45  * keystore consists of 3 AVL trees, which are as follows:
46  *
47  * The Wrapping Key Tree:
48  * The wrapping key (wkey) tree stores the user's keys that are fed into the
49  * kernel through 'zfs load-key' and related commands. Datasets inherit their
50  * parent's wkey by default, so these structures are refcounted. The wrapping
51  * keys remain in memory until they are explicitly unloaded (with
52  * "zfs unload-key"). Unloading is only possible when no datasets are using
53  * them (refcount=0).
54  *
55  * The DSL Crypto Key Tree:
56  * The DSL Crypto Keys (DCK) are the in-memory representation of decrypted
57  * master keys. They are used by the functions in zio_crypt.c to perform
58  * encryption, decryption, and authentication. Snapshots and clones of a given
59  * dataset will share a DSL Crypto Key, so they are also refcounted. Once the
60  * refcount on a key hits zero, it is immediately zeroed out and freed.
61  *
62  * The Crypto Key Mapping Tree:
63  * The zio layer needs to lookup master keys by their dataset object id. Since
64  * the DSL Crypto Keys can belong to multiple datasets, we maintain a tree of
65  * dsl_key_mapping_t's which essentially just map the dataset object id to its
66  * appropriate DSL Crypto Key. The management for creating and destroying these
67  * mappings hooks into the code for owning and disowning datasets. Usually,
68  * there will only be one active dataset owner, but there are times
69  * (particularly during dataset creation and destruction) when this may not be
70  * true or the dataset may not be initialized enough to own. As a result, this
71  * object is also refcounted.
72  */
73 
74 /*
75  * This tunable allows datasets to be raw received even if the stream does
76  * not include IVset guids or if the guids don't match. This is used as part
77  * of the resolution for ZPOOL_ERRATA_ZOL_8308_ENCRYPTION.
78  */
79 int zfs_disable_ivset_guid_check = 0;
80 
81 static void
82 dsl_wrapping_key_hold(dsl_wrapping_key_t *wkey, void *tag)
83 {
84 	(void) zfs_refcount_add(&wkey->wk_refcnt, tag);
85 }
86 
87 static void
88 dsl_wrapping_key_rele(dsl_wrapping_key_t *wkey, void *tag)
89 {
90 	(void) zfs_refcount_remove(&wkey->wk_refcnt, tag);
91 }
92 
93 static void
94 dsl_wrapping_key_free(dsl_wrapping_key_t *wkey)
95 {
96 	ASSERT0(zfs_refcount_count(&wkey->wk_refcnt));
97 
98 	if (wkey->wk_key.ck_data) {
99 		bzero(wkey->wk_key.ck_data,
100 		    CRYPTO_BITS2BYTES(wkey->wk_key.ck_length));
101 		kmem_free(wkey->wk_key.ck_data,
102 		    CRYPTO_BITS2BYTES(wkey->wk_key.ck_length));
103 	}
104 
105 	zfs_refcount_destroy(&wkey->wk_refcnt);
106 	kmem_free(wkey, sizeof (dsl_wrapping_key_t));
107 }
108 
109 static int
110 dsl_wrapping_key_create(uint8_t *wkeydata, zfs_keyformat_t keyformat,
111     uint64_t salt, uint64_t iters, dsl_wrapping_key_t **wkey_out)
112 {
113 	int ret;
114 	dsl_wrapping_key_t *wkey;
115 
116 	/* allocate the wrapping key */
117 	wkey = kmem_alloc(sizeof (dsl_wrapping_key_t), KM_SLEEP);
118 	if (!wkey)
119 		return (SET_ERROR(ENOMEM));
120 
121 	/* allocate and initialize the underlying crypto key */
122 	wkey->wk_key.ck_data = kmem_alloc(WRAPPING_KEY_LEN, KM_SLEEP);
123 	if (!wkey->wk_key.ck_data) {
124 		ret = SET_ERROR(ENOMEM);
125 		goto error;
126 	}
127 
128 	wkey->wk_key.ck_format = CRYPTO_KEY_RAW;
129 	wkey->wk_key.ck_length = CRYPTO_BYTES2BITS(WRAPPING_KEY_LEN);
130 	bcopy(wkeydata, wkey->wk_key.ck_data, WRAPPING_KEY_LEN);
131 
132 	/* initialize the rest of the struct */
133 	zfs_refcount_create(&wkey->wk_refcnt);
134 	wkey->wk_keyformat = keyformat;
135 	wkey->wk_salt = salt;
136 	wkey->wk_iters = iters;
137 
138 	*wkey_out = wkey;
139 	return (0);
140 
141 error:
142 	dsl_wrapping_key_free(wkey);
143 
144 	*wkey_out = NULL;
145 	return (ret);
146 }
147 
148 int
149 dsl_crypto_params_create_nvlist(dcp_cmd_t cmd, nvlist_t *props,
150     nvlist_t *crypto_args, dsl_crypto_params_t **dcp_out)
151 {
152 	int ret;
153 	uint64_t crypt = ZIO_CRYPT_INHERIT;
154 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
155 	uint64_t salt = 0, iters = 0;
156 	dsl_crypto_params_t *dcp = NULL;
157 	dsl_wrapping_key_t *wkey = NULL;
158 	uint8_t *wkeydata = NULL;
159 	uint_t wkeydata_len = 0;
160 	char *keylocation = NULL;
161 
162 	dcp = kmem_zalloc(sizeof (dsl_crypto_params_t), KM_SLEEP);
163 	if (!dcp) {
164 		ret = SET_ERROR(ENOMEM);
165 		goto error;
166 	}
167 
168 	/* get relevant properties from the nvlist */
169 	dcp->cp_cmd = cmd;
170 
171 	/* get relevant arguments from the nvlists */
172 	if (props != NULL) {
173 		(void) nvlist_lookup_uint64(props,
174 		    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &crypt);
175 		(void) nvlist_lookup_uint64(props,
176 		    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
177 		(void) nvlist_lookup_string(props,
178 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
179 		(void) nvlist_lookup_uint64(props,
180 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), &salt);
181 		(void) nvlist_lookup_uint64(props,
182 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
183 		dcp->cp_crypt = crypt;
184 	}
185 
186 	if (crypto_args != NULL) {
187 		(void) nvlist_lookup_uint8_array(crypto_args, "wkeydata",
188 		    &wkeydata, &wkeydata_len);
189 	}
190 
191 	/* check for valid command */
192 	if (dcp->cp_cmd >= DCP_CMD_MAX) {
193 		ret = SET_ERROR(EINVAL);
194 		goto error;
195 	} else {
196 		dcp->cp_cmd = cmd;
197 	}
198 
199 	/* check for valid crypt */
200 	if (dcp->cp_crypt >= ZIO_CRYPT_FUNCTIONS) {
201 		ret = SET_ERROR(EINVAL);
202 		goto error;
203 	} else {
204 		dcp->cp_crypt = crypt;
205 	}
206 
207 	/* check for valid keyformat */
208 	if (keyformat >= ZFS_KEYFORMAT_FORMATS) {
209 		ret = SET_ERROR(EINVAL);
210 		goto error;
211 	}
212 
213 	/* check for a valid keylocation (of any kind) and copy it in */
214 	if (keylocation != NULL) {
215 		if (!zfs_prop_valid_keylocation(keylocation, B_FALSE)) {
216 			ret = SET_ERROR(EINVAL);
217 			goto error;
218 		}
219 
220 		dcp->cp_keylocation = spa_strdup(keylocation);
221 	}
222 
223 	/* check wrapping key length, if given */
224 	if (wkeydata != NULL && wkeydata_len != WRAPPING_KEY_LEN) {
225 		ret = SET_ERROR(EINVAL);
226 		goto error;
227 	}
228 
229 	/* if the user asked for the default crypt, determine that now */
230 	if (dcp->cp_crypt == ZIO_CRYPT_ON)
231 		dcp->cp_crypt = ZIO_CRYPT_ON_VALUE;
232 
233 	/* create the wrapping key from the raw data */
234 	if (wkeydata != NULL) {
235 		/* create the wrapping key with the verified parameters */
236 		ret = dsl_wrapping_key_create(wkeydata, keyformat, salt,
237 		    iters, &wkey);
238 		if (ret != 0)
239 			goto error;
240 
241 		dcp->cp_wkey = wkey;
242 	}
243 
244 	/*
245 	 * Remove the encryption properties from the nvlist since they are not
246 	 * maintained through the DSL.
247 	 */
248 	(void) nvlist_remove_all(props, zfs_prop_to_name(ZFS_PROP_ENCRYPTION));
249 	(void) nvlist_remove_all(props, zfs_prop_to_name(ZFS_PROP_KEYFORMAT));
250 	(void) nvlist_remove_all(props, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT));
251 	(void) nvlist_remove_all(props,
252 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS));
253 
254 	*dcp_out = dcp;
255 
256 	return (0);
257 
258 error:
259 	if (wkey != NULL)
260 		dsl_wrapping_key_free(wkey);
261 	if (dcp != NULL)
262 		kmem_free(dcp, sizeof (dsl_crypto_params_t));
263 
264 	*dcp_out = NULL;
265 	return (ret);
266 }
267 
268 void
269 dsl_crypto_params_free(dsl_crypto_params_t *dcp, boolean_t unload)
270 {
271 	if (dcp == NULL)
272 		return;
273 
274 	if (dcp->cp_keylocation != NULL)
275 		spa_strfree(dcp->cp_keylocation);
276 	if (unload && dcp->cp_wkey != NULL)
277 		dsl_wrapping_key_free(dcp->cp_wkey);
278 
279 	kmem_free(dcp, sizeof (dsl_crypto_params_t));
280 }
281 
282 static int
283 spa_crypto_key_compare(const void *a, const void *b)
284 {
285 	const dsl_crypto_key_t *dcka = a;
286 	const dsl_crypto_key_t *dckb = b;
287 
288 	if (dcka->dck_obj < dckb->dck_obj)
289 		return (-1);
290 	if (dcka->dck_obj > dckb->dck_obj)
291 		return (1);
292 	return (0);
293 }
294 
295 static int
296 spa_key_mapping_compare(const void *a, const void *b)
297 {
298 	const dsl_key_mapping_t *kma = a;
299 	const dsl_key_mapping_t *kmb = b;
300 
301 	if (kma->km_dsobj < kmb->km_dsobj)
302 		return (-1);
303 	if (kma->km_dsobj > kmb->km_dsobj)
304 		return (1);
305 	return (0);
306 }
307 
308 static int
309 spa_wkey_compare(const void *a, const void *b)
310 {
311 	const dsl_wrapping_key_t *wka = a;
312 	const dsl_wrapping_key_t *wkb = b;
313 
314 	if (wka->wk_ddobj < wkb->wk_ddobj)
315 		return (-1);
316 	if (wka->wk_ddobj > wkb->wk_ddobj)
317 		return (1);
318 	return (0);
319 }
320 
321 void
322 spa_keystore_init(spa_keystore_t *sk)
323 {
324 	rw_init(&sk->sk_dk_lock, NULL, RW_DEFAULT, NULL);
325 	rw_init(&sk->sk_km_lock, NULL, RW_DEFAULT, NULL);
326 	rw_init(&sk->sk_wkeys_lock, NULL, RW_DEFAULT, NULL);
327 	avl_create(&sk->sk_dsl_keys, spa_crypto_key_compare,
328 	    sizeof (dsl_crypto_key_t),
329 	    offsetof(dsl_crypto_key_t, dck_avl_link));
330 	avl_create(&sk->sk_key_mappings, spa_key_mapping_compare,
331 	    sizeof (dsl_key_mapping_t),
332 	    offsetof(dsl_key_mapping_t, km_avl_link));
333 	avl_create(&sk->sk_wkeys, spa_wkey_compare, sizeof (dsl_wrapping_key_t),
334 	    offsetof(dsl_wrapping_key_t, wk_avl_link));
335 }
336 
337 void
338 spa_keystore_fini(spa_keystore_t *sk)
339 {
340 	dsl_wrapping_key_t *wkey;
341 	void *cookie = NULL;
342 
343 	ASSERT(avl_is_empty(&sk->sk_dsl_keys));
344 	ASSERT(avl_is_empty(&sk->sk_key_mappings));
345 
346 	while ((wkey = avl_destroy_nodes(&sk->sk_wkeys, &cookie)) != NULL)
347 		dsl_wrapping_key_free(wkey);
348 
349 	avl_destroy(&sk->sk_wkeys);
350 	avl_destroy(&sk->sk_key_mappings);
351 	avl_destroy(&sk->sk_dsl_keys);
352 	rw_destroy(&sk->sk_wkeys_lock);
353 	rw_destroy(&sk->sk_km_lock);
354 	rw_destroy(&sk->sk_dk_lock);
355 }
356 
357 static int
358 dsl_dir_get_encryption_root_ddobj(dsl_dir_t *dd, uint64_t *rddobj)
359 {
360 	if (dd->dd_crypto_obj == 0)
361 		return (SET_ERROR(ENOENT));
362 
363 	return (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
364 	    DSL_CRYPTO_KEY_ROOT_DDOBJ, 8, 1, rddobj));
365 }
366 
367 int
368 dsl_dir_get_encryption_version(dsl_dir_t *dd, uint64_t *version)
369 {
370 	*version = 0;
371 
372 	if (dd->dd_crypto_obj == 0)
373 		return (SET_ERROR(ENOENT));
374 
375 	/* version 0 is implied by ENOENT */
376 	(void) zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
377 	    DSL_CRYPTO_KEY_VERSION, 8, 1, version);
378 
379 	return (0);
380 }
381 
382 boolean_t
383 dsl_dir_incompatible_encryption_version(dsl_dir_t *dd)
384 {
385 	int ret;
386 	uint64_t version = 0;
387 
388 	ret = dsl_dir_get_encryption_version(dd, &version);
389 	if (ret != 0)
390 		return (B_FALSE);
391 
392 	return (version != ZIO_CRYPT_KEY_CURRENT_VERSION);
393 }
394 
395 static int
396 spa_keystore_wkey_hold_ddobj_impl(spa_t *spa, uint64_t ddobj,
397     void *tag, dsl_wrapping_key_t **wkey_out)
398 {
399 	int ret;
400 	dsl_wrapping_key_t search_wkey;
401 	dsl_wrapping_key_t *found_wkey;
402 
403 	ASSERT(RW_LOCK_HELD(&spa->spa_keystore.sk_wkeys_lock));
404 
405 	/* init the search wrapping key */
406 	search_wkey.wk_ddobj = ddobj;
407 
408 	/* lookup the wrapping key */
409 	found_wkey = avl_find(&spa->spa_keystore.sk_wkeys, &search_wkey, NULL);
410 	if (!found_wkey) {
411 		ret = SET_ERROR(ENOENT);
412 		goto error;
413 	}
414 
415 	/* increment the refcount */
416 	dsl_wrapping_key_hold(found_wkey, tag);
417 
418 	*wkey_out = found_wkey;
419 	return (0);
420 
421 error:
422 	*wkey_out = NULL;
423 	return (ret);
424 }
425 
426 static int
427 spa_keystore_wkey_hold_dd(spa_t *spa, dsl_dir_t *dd, void *tag,
428     dsl_wrapping_key_t **wkey_out)
429 {
430 	int ret;
431 	dsl_wrapping_key_t *wkey;
432 	uint64_t rddobj;
433 	boolean_t locked = B_FALSE;
434 
435 	if (!RW_WRITE_HELD(&spa->spa_keystore.sk_wkeys_lock)) {
436 		rw_enter(&spa->spa_keystore.sk_wkeys_lock, RW_READER);
437 		locked = B_TRUE;
438 	}
439 
440 	/* get the ddobj that the keylocation property was inherited from */
441 	ret = dsl_dir_get_encryption_root_ddobj(dd, &rddobj);
442 	if (ret != 0)
443 		goto error;
444 
445 	/* lookup the wkey in the avl tree */
446 	ret = spa_keystore_wkey_hold_ddobj_impl(spa, rddobj, tag, &wkey);
447 	if (ret != 0)
448 		goto error;
449 
450 	/* unlock the wkey tree if we locked it */
451 	if (locked)
452 		rw_exit(&spa->spa_keystore.sk_wkeys_lock);
453 
454 	*wkey_out = wkey;
455 	return (0);
456 
457 error:
458 	if (locked)
459 		rw_exit(&spa->spa_keystore.sk_wkeys_lock);
460 
461 	*wkey_out = NULL;
462 	return (ret);
463 }
464 
465 int
466 dsl_crypto_can_set_keylocation(const char *dsname, const char *keylocation)
467 {
468 	int ret = 0;
469 	dsl_dir_t *dd = NULL;
470 	dsl_pool_t *dp = NULL;
471 	uint64_t rddobj;
472 
473 	/* hold the dsl dir */
474 	ret = dsl_pool_hold(dsname, FTAG, &dp);
475 	if (ret != 0)
476 		goto out;
477 
478 	ret = dsl_dir_hold(dp, dsname, FTAG, &dd, NULL);
479 	if (ret != 0)
480 		goto out;
481 
482 	/* if dd is not encrypted, the value may only be "none" */
483 	if (dd->dd_crypto_obj == 0) {
484 		if (strcmp(keylocation, "none") != 0) {
485 			ret = SET_ERROR(EACCES);
486 			goto out;
487 		}
488 
489 		ret = 0;
490 		goto out;
491 	}
492 
493 	/* check for a valid keylocation for encrypted datasets */
494 	if (!zfs_prop_valid_keylocation(keylocation, B_TRUE)) {
495 		ret = SET_ERROR(EINVAL);
496 		goto out;
497 	}
498 
499 	/* check that this is an encryption root */
500 	ret = dsl_dir_get_encryption_root_ddobj(dd, &rddobj);
501 	if (ret != 0)
502 		goto out;
503 
504 	if (rddobj != dd->dd_object) {
505 		ret = SET_ERROR(EACCES);
506 		goto out;
507 	}
508 
509 	dsl_dir_rele(dd, FTAG);
510 	dsl_pool_rele(dp, FTAG);
511 
512 	return (0);
513 
514 out:
515 	if (dd != NULL)
516 		dsl_dir_rele(dd, FTAG);
517 	if (dp != NULL)
518 		dsl_pool_rele(dp, FTAG);
519 
520 	return (ret);
521 }
522 
523 static void
524 dsl_crypto_key_free(dsl_crypto_key_t *dck)
525 {
526 	ASSERT(zfs_refcount_count(&dck->dck_holds) == 0);
527 
528 	/* destroy the zio_crypt_key_t */
529 	zio_crypt_key_destroy(&dck->dck_key);
530 
531 	/* free the refcount, wrapping key, and lock */
532 	zfs_refcount_destroy(&dck->dck_holds);
533 	if (dck->dck_wkey)
534 		dsl_wrapping_key_rele(dck->dck_wkey, dck);
535 
536 	/* free the key */
537 	kmem_free(dck, sizeof (dsl_crypto_key_t));
538 }
539 
540 static void
541 dsl_crypto_key_rele(dsl_crypto_key_t *dck, void *tag)
542 {
543 	if (zfs_refcount_remove(&dck->dck_holds, tag) == 0)
544 		dsl_crypto_key_free(dck);
545 }
546 
547 static int
548 dsl_crypto_key_open(objset_t *mos, dsl_wrapping_key_t *wkey,
549     uint64_t dckobj, void *tag, dsl_crypto_key_t **dck_out)
550 {
551 	int ret;
552 	uint64_t crypt = 0, guid = 0, version = 0;
553 	uint8_t raw_keydata[MASTER_KEY_MAX_LEN];
554 	uint8_t raw_hmac_keydata[SHA512_HMAC_KEYLEN];
555 	uint8_t iv[WRAPPING_IV_LEN];
556 	uint8_t mac[WRAPPING_MAC_LEN];
557 	dsl_crypto_key_t *dck;
558 
559 	/* allocate and initialize the key */
560 	dck = kmem_zalloc(sizeof (dsl_crypto_key_t), KM_SLEEP);
561 	if (!dck)
562 		return (SET_ERROR(ENOMEM));
563 
564 	/* fetch all of the values we need from the ZAP */
565 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_CRYPTO_SUITE, 8, 1,
566 	    &crypt);
567 	if (ret != 0)
568 		goto error;
569 
570 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_GUID, 8, 1, &guid);
571 	if (ret != 0)
572 		goto error;
573 
574 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_MASTER_KEY, 1,
575 	    MASTER_KEY_MAX_LEN, raw_keydata);
576 	if (ret != 0)
577 		goto error;
578 
579 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_HMAC_KEY, 1,
580 	    SHA512_HMAC_KEYLEN, raw_hmac_keydata);
581 	if (ret != 0)
582 		goto error;
583 
584 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_IV, 1, WRAPPING_IV_LEN,
585 	    iv);
586 	if (ret != 0)
587 		goto error;
588 
589 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_MAC, 1, WRAPPING_MAC_LEN,
590 	    mac);
591 	if (ret != 0)
592 		goto error;
593 
594 	/* the initial on-disk format for encryption did not have a version */
595 	(void) zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_VERSION, 8, 1, &version);
596 
597 	/*
598 	 * Unwrap the keys. If there is an error return EACCES to indicate
599 	 * an authentication failure.
600 	 */
601 	ret = zio_crypt_key_unwrap(&wkey->wk_key, crypt, version, guid,
602 	    raw_keydata, raw_hmac_keydata, iv, mac, &dck->dck_key);
603 	if (ret != 0) {
604 		ret = SET_ERROR(EACCES);
605 		goto error;
606 	}
607 
608 	/* finish initializing the dsl_crypto_key_t */
609 	zfs_refcount_create(&dck->dck_holds);
610 	dsl_wrapping_key_hold(wkey, dck);
611 	dck->dck_wkey = wkey;
612 	dck->dck_obj = dckobj;
613 	(void) zfs_refcount_add(&dck->dck_holds, tag);
614 
615 	*dck_out = dck;
616 	return (0);
617 
618 error:
619 	if (dck != NULL) {
620 		bzero(dck, sizeof (dsl_crypto_key_t));
621 		kmem_free(dck, sizeof (dsl_crypto_key_t));
622 	}
623 
624 	*dck_out = NULL;
625 	return (ret);
626 }
627 
628 static int
629 spa_keystore_dsl_key_hold_impl(spa_t *spa, uint64_t dckobj, void *tag,
630     dsl_crypto_key_t **dck_out)
631 {
632 	int ret;
633 	dsl_crypto_key_t search_dck;
634 	dsl_crypto_key_t *found_dck;
635 
636 	ASSERT(RW_LOCK_HELD(&spa->spa_keystore.sk_dk_lock));
637 
638 	/* init the search key */
639 	search_dck.dck_obj = dckobj;
640 
641 	/* find the matching key in the keystore */
642 	found_dck = avl_find(&spa->spa_keystore.sk_dsl_keys, &search_dck, NULL);
643 	if (!found_dck) {
644 		ret = SET_ERROR(ENOENT);
645 		goto error;
646 	}
647 
648 	/* increment the refcount */
649 	(void) zfs_refcount_add(&found_dck->dck_holds, tag);
650 
651 	*dck_out = found_dck;
652 	return (0);
653 
654 error:
655 	*dck_out = NULL;
656 	return (ret);
657 }
658 
659 static int
660 spa_keystore_dsl_key_hold_dd(spa_t *spa, dsl_dir_t *dd, void *tag,
661     dsl_crypto_key_t **dck_out)
662 {
663 	int ret;
664 	avl_index_t where;
665 	dsl_crypto_key_t *dck_io = NULL, *dck_ks = NULL;
666 	dsl_wrapping_key_t *wkey = NULL;
667 	uint64_t dckobj = dd->dd_crypto_obj;
668 
669 	/* Lookup the key in the tree of currently loaded keys */
670 	rw_enter(&spa->spa_keystore.sk_dk_lock, RW_READER);
671 	ret = spa_keystore_dsl_key_hold_impl(spa, dckobj, tag, &dck_ks);
672 	rw_exit(&spa->spa_keystore.sk_dk_lock);
673 	if (ret == 0) {
674 		*dck_out = dck_ks;
675 		return (0);
676 	}
677 
678 	/* Lookup the wrapping key from the keystore */
679 	ret = spa_keystore_wkey_hold_dd(spa, dd, FTAG, &wkey);
680 	if (ret != 0) {
681 		*dck_out = NULL;
682 		return (SET_ERROR(EACCES));
683 	}
684 
685 	/* Read the key from disk */
686 	ret = dsl_crypto_key_open(spa->spa_meta_objset, wkey, dckobj,
687 	    tag, &dck_io);
688 	if (ret != 0) {
689 		dsl_wrapping_key_rele(wkey, FTAG);
690 		*dck_out = NULL;
691 		return (ret);
692 	}
693 
694 	/*
695 	 * Add the key to the keystore.  It may already exist if it was
696 	 * added while performing the read from disk.  In this case discard
697 	 * it and return the key from the keystore.
698 	 */
699 	rw_enter(&spa->spa_keystore.sk_dk_lock, RW_WRITER);
700 	ret = spa_keystore_dsl_key_hold_impl(spa, dckobj, tag, &dck_ks);
701 	if (ret != 0) {
702 		(void) avl_find(&spa->spa_keystore.sk_dsl_keys, dck_io, &where);
703 		avl_insert(&spa->spa_keystore.sk_dsl_keys, dck_io, where);
704 		*dck_out = dck_io;
705 	} else {
706 		dsl_crypto_key_free(dck_io);
707 		*dck_out = dck_ks;
708 	}
709 
710 	/* Release the wrapping key (the dsl key now has a reference to it) */
711 	dsl_wrapping_key_rele(wkey, FTAG);
712 	rw_exit(&spa->spa_keystore.sk_dk_lock);
713 
714 	return (0);
715 }
716 
717 void
718 spa_keystore_dsl_key_rele(spa_t *spa, dsl_crypto_key_t *dck, void *tag)
719 {
720 	rw_enter(&spa->spa_keystore.sk_dk_lock, RW_WRITER);
721 
722 	if (zfs_refcount_remove(&dck->dck_holds, tag) == 0) {
723 		avl_remove(&spa->spa_keystore.sk_dsl_keys, dck);
724 		dsl_crypto_key_free(dck);
725 	}
726 
727 	rw_exit(&spa->spa_keystore.sk_dk_lock);
728 }
729 
730 int
731 spa_keystore_load_wkey_impl(spa_t *spa, dsl_wrapping_key_t *wkey)
732 {
733 	int ret;
734 	avl_index_t where;
735 	dsl_wrapping_key_t *found_wkey;
736 
737 	rw_enter(&spa->spa_keystore.sk_wkeys_lock, RW_WRITER);
738 
739 	/* insert the wrapping key into the keystore */
740 	found_wkey = avl_find(&spa->spa_keystore.sk_wkeys, wkey, &where);
741 	if (found_wkey != NULL) {
742 		ret = SET_ERROR(EEXIST);
743 		goto error_unlock;
744 	}
745 	avl_insert(&spa->spa_keystore.sk_wkeys, wkey, where);
746 
747 	rw_exit(&spa->spa_keystore.sk_wkeys_lock);
748 
749 	return (0);
750 
751 error_unlock:
752 	rw_exit(&spa->spa_keystore.sk_wkeys_lock);
753 	return (ret);
754 }
755 
756 int
757 spa_keystore_load_wkey(const char *dsname, dsl_crypto_params_t *dcp,
758     boolean_t noop)
759 {
760 	int ret;
761 	dsl_dir_t *dd = NULL;
762 	dsl_crypto_key_t *dck = NULL;
763 	dsl_wrapping_key_t *wkey = dcp->cp_wkey;
764 	dsl_pool_t *dp = NULL;
765 	uint64_t keyformat, salt, iters;
766 
767 	/*
768 	 * We don't validate the wrapping key's keyformat, salt, or iters
769 	 * since they will never be needed after the DCK has been wrapped.
770 	 */
771 	if (dcp->cp_wkey == NULL ||
772 	    dcp->cp_cmd != DCP_CMD_NONE ||
773 	    dcp->cp_crypt != ZIO_CRYPT_INHERIT ||
774 	    dcp->cp_keylocation != NULL)
775 		return (SET_ERROR(EINVAL));
776 
777 	ret = dsl_pool_hold(dsname, FTAG, &dp);
778 	if (ret != 0)
779 		goto error;
780 
781 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION)) {
782 		ret = (SET_ERROR(ENOTSUP));
783 		goto error;
784 	}
785 
786 	/* hold the dsl dir */
787 	ret = dsl_dir_hold(dp, dsname, FTAG, &dd, NULL);
788 	if (ret != 0)
789 		goto error;
790 
791 	/* initialize the wkey's ddobj */
792 	wkey->wk_ddobj = dd->dd_object;
793 
794 	/* verify that the wkey is correct by opening its dsl key */
795 	ret = dsl_crypto_key_open(dp->dp_meta_objset, wkey,
796 	    dd->dd_crypto_obj, FTAG, &dck);
797 	if (ret != 0)
798 		goto error;
799 
800 	/* initialize the wkey encryption parameters from the DSL Crypto Key */
801 	ret = zap_lookup(dp->dp_meta_objset, dd->dd_crypto_obj,
802 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), 8, 1, &keyformat);
803 	if (ret != 0)
804 		goto error;
805 
806 	ret = zap_lookup(dp->dp_meta_objset, dd->dd_crypto_obj,
807 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 8, 1, &salt);
808 	if (ret != 0)
809 		goto error;
810 
811 	ret = zap_lookup(dp->dp_meta_objset, dd->dd_crypto_obj,
812 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 8, 1, &iters);
813 	if (ret != 0)
814 		goto error;
815 
816 	ASSERT3U(keyformat, <, ZFS_KEYFORMAT_FORMATS);
817 	ASSERT3U(keyformat, !=, ZFS_KEYFORMAT_NONE);
818 	IMPLY(keyformat == ZFS_KEYFORMAT_PASSPHRASE, iters != 0);
819 	IMPLY(keyformat == ZFS_KEYFORMAT_PASSPHRASE, salt != 0);
820 	IMPLY(keyformat != ZFS_KEYFORMAT_PASSPHRASE, iters == 0);
821 	IMPLY(keyformat != ZFS_KEYFORMAT_PASSPHRASE, salt == 0);
822 
823 	wkey->wk_keyformat = keyformat;
824 	wkey->wk_salt = salt;
825 	wkey->wk_iters = iters;
826 
827 	/*
828 	 * At this point we have verified the wkey and confirmed that it can
829 	 * be used to decrypt a DSL Crypto Key. We can simply cleanup and
830 	 * return if this is all the user wanted to do.
831 	 */
832 	if (noop)
833 		goto error;
834 
835 	/* insert the wrapping key into the keystore */
836 	ret = spa_keystore_load_wkey_impl(dp->dp_spa, wkey);
837 	if (ret != 0)
838 		goto error;
839 
840 	dsl_crypto_key_rele(dck, FTAG);
841 	dsl_dir_rele(dd, FTAG);
842 	dsl_pool_rele(dp, FTAG);
843 
844 	return (0);
845 
846 error:
847 	if (dck != NULL)
848 		dsl_crypto_key_rele(dck, FTAG);
849 	if (dd != NULL)
850 		dsl_dir_rele(dd, FTAG);
851 	if (dp != NULL)
852 		dsl_pool_rele(dp, FTAG);
853 
854 	return (ret);
855 }
856 
857 int
858 spa_keystore_unload_wkey_impl(spa_t *spa, uint64_t ddobj)
859 {
860 	int ret;
861 	dsl_wrapping_key_t search_wkey;
862 	dsl_wrapping_key_t *found_wkey;
863 
864 	/* init the search wrapping key */
865 	search_wkey.wk_ddobj = ddobj;
866 
867 	rw_enter(&spa->spa_keystore.sk_wkeys_lock, RW_WRITER);
868 
869 	/* remove the wrapping key from the keystore */
870 	found_wkey = avl_find(&spa->spa_keystore.sk_wkeys,
871 	    &search_wkey, NULL);
872 	if (!found_wkey) {
873 		ret = SET_ERROR(EACCES);
874 		goto error_unlock;
875 	} else if (zfs_refcount_count(&found_wkey->wk_refcnt) != 0) {
876 		ret = SET_ERROR(EBUSY);
877 		goto error_unlock;
878 	}
879 	avl_remove(&spa->spa_keystore.sk_wkeys, found_wkey);
880 
881 	rw_exit(&spa->spa_keystore.sk_wkeys_lock);
882 
883 	/* free the wrapping key */
884 	dsl_wrapping_key_free(found_wkey);
885 
886 	return (0);
887 
888 error_unlock:
889 	rw_exit(&spa->spa_keystore.sk_wkeys_lock);
890 	return (ret);
891 }
892 
893 int
894 spa_keystore_unload_wkey(const char *dsname)
895 {
896 	int ret = 0;
897 	dsl_dir_t *dd = NULL;
898 	dsl_pool_t *dp = NULL;
899 	spa_t *spa = NULL;
900 
901 	ret = spa_open(dsname, &spa, FTAG);
902 	if (ret != 0)
903 		return (ret);
904 
905 	/*
906 	 * Wait for any outstanding txg IO to complete, releasing any
907 	 * remaining references on the wkey.
908 	 */
909 	if (spa_mode(spa) != FREAD)
910 		txg_wait_synced(spa->spa_dsl_pool, 0);
911 
912 	spa_close(spa, FTAG);
913 
914 	/* hold the dsl dir */
915 	ret = dsl_pool_hold(dsname, FTAG, &dp);
916 	if (ret != 0)
917 		goto error;
918 
919 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION)) {
920 		ret = (SET_ERROR(ENOTSUP));
921 		goto error;
922 	}
923 
924 	ret = dsl_dir_hold(dp, dsname, FTAG, &dd, NULL);
925 	if (ret != 0)
926 		goto error;
927 
928 	/* unload the wkey */
929 	ret = spa_keystore_unload_wkey_impl(dp->dp_spa, dd->dd_object);
930 	if (ret != 0)
931 		goto error;
932 
933 	dsl_dir_rele(dd, FTAG);
934 	dsl_pool_rele(dp, FTAG);
935 
936 	return (0);
937 
938 error:
939 	if (dd != NULL)
940 		dsl_dir_rele(dd, FTAG);
941 	if (dp != NULL)
942 		dsl_pool_rele(dp, FTAG);
943 
944 	return (ret);
945 }
946 
947 void
948 key_mapping_add_ref(dsl_key_mapping_t *km, void *tag)
949 {
950 	ASSERT3U(zfs_refcount_count(&km->km_refcnt), >=, 1);
951 	(void) zfs_refcount_add(&km->km_refcnt, tag);
952 }
953 
954 /*
955  * The locking here is a little tricky to ensure we don't cause unnecessary
956  * performance problems. We want to release a key mapping whenever someone
957  * decrements the refcount to 0, but freeing the mapping requires removing
958  * it from the spa_keystore, which requires holding sk_km_lock as a writer.
959  * Most of the time we don't want to hold this lock as a writer, since the
960  * same lock is held as a reader for each IO that needs to encrypt / decrypt
961  * data for any dataset and in practice we will only actually free the
962  * mapping after unmounting a dataset.
963  */
964 void
965 key_mapping_rele(spa_t *spa, dsl_key_mapping_t *km, void *tag)
966 {
967 	ASSERT3U(zfs_refcount_count(&km->km_refcnt), >=, 1);
968 
969 	if (zfs_refcount_remove(&km->km_refcnt, tag) != 0)
970 		return;
971 
972 	/*
973 	 * We think we are going to need to free the mapping. Add a
974 	 * reference to prevent most other releasers from thinking
975 	 * this might be their responsibility. This is inherently
976 	 * racy, so we will confirm that we are legitimately the
977 	 * last holder once we have the sk_km_lock as a writer.
978 	 */
979 	(void) zfs_refcount_add(&km->km_refcnt, FTAG);
980 
981 	rw_enter(&spa->spa_keystore.sk_km_lock, RW_WRITER);
982 	if (zfs_refcount_remove(&km->km_refcnt, FTAG) != 0) {
983 		rw_exit(&spa->spa_keystore.sk_km_lock);
984 		return;
985 	}
986 
987 	avl_remove(&spa->spa_keystore.sk_key_mappings, km);
988 	rw_exit(&spa->spa_keystore.sk_km_lock);
989 
990 	spa_keystore_dsl_key_rele(spa, km->km_key, km);
991 	zfs_refcount_destroy(&km->km_refcnt);
992 	kmem_free(km, sizeof (dsl_key_mapping_t));
993 }
994 
995 int
996 spa_keystore_create_mapping(spa_t *spa, dsl_dataset_t *ds, void *tag,
997     dsl_key_mapping_t **km_out)
998 {
999 	int ret;
1000 	avl_index_t where;
1001 	dsl_key_mapping_t *km, *found_km;
1002 	boolean_t should_free = B_FALSE;
1003 
1004 	/* Allocate and initialize the mapping */
1005 	km = kmem_zalloc(sizeof (dsl_key_mapping_t), KM_SLEEP);
1006 	zfs_refcount_create(&km->km_refcnt);
1007 
1008 	ret = spa_keystore_dsl_key_hold_dd(spa, ds->ds_dir, km, &km->km_key);
1009 	if (ret != 0) {
1010 		zfs_refcount_destroy(&km->km_refcnt);
1011 		kmem_free(km, sizeof (dsl_key_mapping_t));
1012 
1013 		if (km_out != NULL)
1014 			*km_out = NULL;
1015 		return (ret);
1016 	}
1017 
1018 	km->km_dsobj = ds->ds_object;
1019 
1020 	rw_enter(&spa->spa_keystore.sk_km_lock, RW_WRITER);
1021 
1022 	/*
1023 	 * If a mapping already exists, simply increment its refcount and
1024 	 * cleanup the one we made. We want to allocate / free outside of
1025 	 * the lock because this lock is also used by the zio layer to lookup
1026 	 * key mappings. Otherwise, use the one we created. Normally, there will
1027 	 * only be one active reference at a time (the objset owner), but there
1028 	 * are times when there could be multiple async users.
1029 	 */
1030 	found_km = avl_find(&spa->spa_keystore.sk_key_mappings, km, &where);
1031 	if (found_km != NULL) {
1032 		should_free = B_TRUE;
1033 		(void) zfs_refcount_add(&found_km->km_refcnt, tag);
1034 		if (km_out != NULL)
1035 			*km_out = found_km;
1036 	} else {
1037 		(void) zfs_refcount_add(&km->km_refcnt, tag);
1038 		avl_insert(&spa->spa_keystore.sk_key_mappings, km, where);
1039 		if (km_out != NULL)
1040 			*km_out = km;
1041 	}
1042 
1043 	rw_exit(&spa->spa_keystore.sk_km_lock);
1044 
1045 	if (should_free) {
1046 		spa_keystore_dsl_key_rele(spa, km->km_key, km);
1047 		zfs_refcount_destroy(&km->km_refcnt);
1048 		kmem_free(km, sizeof (dsl_key_mapping_t));
1049 	}
1050 
1051 	return (0);
1052 }
1053 
1054 int
1055 spa_keystore_remove_mapping(spa_t *spa, uint64_t dsobj, void *tag)
1056 {
1057 	int ret;
1058 	dsl_key_mapping_t search_km;
1059 	dsl_key_mapping_t *found_km;
1060 
1061 	/* init the search key mapping */
1062 	search_km.km_dsobj = dsobj;
1063 
1064 	rw_enter(&spa->spa_keystore.sk_km_lock, RW_READER);
1065 
1066 	/* find the matching mapping */
1067 	found_km = avl_find(&spa->spa_keystore.sk_key_mappings,
1068 	    &search_km, NULL);
1069 	if (found_km == NULL) {
1070 		ret = SET_ERROR(ENOENT);
1071 		goto error_unlock;
1072 	}
1073 
1074 	rw_exit(&spa->spa_keystore.sk_km_lock);
1075 
1076 	key_mapping_rele(spa, found_km, tag);
1077 
1078 	return (0);
1079 
1080 error_unlock:
1081 	rw_exit(&spa->spa_keystore.sk_km_lock);
1082 	return (ret);
1083 }
1084 
1085 /*
1086  * This function is primarily used by the zio and arc layer to lookup
1087  * DSL Crypto Keys for encryption. Callers must release the key with
1088  * spa_keystore_dsl_key_rele(). The function may also be called with
1089  * dck_out == NULL and tag == NULL to simply check that a key exists
1090  * without getting a reference to it.
1091  */
1092 int
1093 spa_keystore_lookup_key(spa_t *spa, uint64_t dsobj, void *tag,
1094     dsl_crypto_key_t **dck_out)
1095 {
1096 	int ret;
1097 	dsl_key_mapping_t search_km;
1098 	dsl_key_mapping_t *found_km;
1099 
1100 	ASSERT((tag != NULL && dck_out != NULL) ||
1101 	    (tag == NULL && dck_out == NULL));
1102 
1103 	/* init the search key mapping */
1104 	search_km.km_dsobj = dsobj;
1105 
1106 	rw_enter(&spa->spa_keystore.sk_km_lock, RW_READER);
1107 
1108 	/* remove the mapping from the tree */
1109 	found_km = avl_find(&spa->spa_keystore.sk_key_mappings, &search_km,
1110 	    NULL);
1111 	if (found_km == NULL) {
1112 		ret = SET_ERROR(ENOENT);
1113 		goto error_unlock;
1114 	}
1115 
1116 	if (found_km && tag)
1117 		(void) zfs_refcount_add(&found_km->km_key->dck_holds, tag);
1118 
1119 	rw_exit(&spa->spa_keystore.sk_km_lock);
1120 
1121 	if (dck_out != NULL)
1122 		*dck_out = found_km->km_key;
1123 	return (0);
1124 
1125 error_unlock:
1126 	rw_exit(&spa->spa_keystore.sk_km_lock);
1127 
1128 	if (dck_out != NULL)
1129 		*dck_out = NULL;
1130 	return (ret);
1131 }
1132 
1133 static int
1134 dmu_objset_check_wkey_loaded(dsl_dir_t *dd)
1135 {
1136 	int ret;
1137 	dsl_wrapping_key_t *wkey = NULL;
1138 
1139 	ret = spa_keystore_wkey_hold_dd(dd->dd_pool->dp_spa, dd, FTAG,
1140 	    &wkey);
1141 	if (ret != 0)
1142 		return (SET_ERROR(EACCES));
1143 
1144 	dsl_wrapping_key_rele(wkey, FTAG);
1145 
1146 	return (0);
1147 }
1148 
1149 static zfs_keystatus_t
1150 dsl_dataset_get_keystatus(dsl_dir_t *dd)
1151 {
1152 	/* check if this dd has a has a dsl key */
1153 	if (dd->dd_crypto_obj == 0)
1154 		return (ZFS_KEYSTATUS_NONE);
1155 
1156 	return (dmu_objset_check_wkey_loaded(dd) == 0 ?
1157 	    ZFS_KEYSTATUS_AVAILABLE : ZFS_KEYSTATUS_UNAVAILABLE);
1158 }
1159 
1160 static int
1161 dsl_dir_get_crypt(dsl_dir_t *dd, uint64_t *crypt)
1162 {
1163 	if (dd->dd_crypto_obj == 0) {
1164 		*crypt = ZIO_CRYPT_OFF;
1165 		return (0);
1166 	}
1167 
1168 	return (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
1169 	    DSL_CRYPTO_KEY_CRYPTO_SUITE, 8, 1, crypt));
1170 }
1171 
1172 static void
1173 dsl_crypto_key_sync_impl(objset_t *mos, uint64_t dckobj, uint64_t crypt,
1174     uint64_t root_ddobj, uint64_t guid, uint8_t *iv, uint8_t *mac,
1175     uint8_t *keydata, uint8_t *hmac_keydata, uint64_t keyformat,
1176     uint64_t salt, uint64_t iters, dmu_tx_t *tx)
1177 {
1178 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_CRYPTO_SUITE, 8, 1,
1179 	    &crypt, tx));
1180 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_ROOT_DDOBJ, 8, 1,
1181 	    &root_ddobj, tx));
1182 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_GUID, 8, 1,
1183 	    &guid, tx));
1184 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_IV, 1, WRAPPING_IV_LEN,
1185 	    iv, tx));
1186 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_MAC, 1, WRAPPING_MAC_LEN,
1187 	    mac, tx));
1188 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_MASTER_KEY, 1,
1189 	    MASTER_KEY_MAX_LEN, keydata, tx));
1190 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_HMAC_KEY, 1,
1191 	    SHA512_HMAC_KEYLEN, hmac_keydata, tx));
1192 	VERIFY0(zap_update(mos, dckobj, zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
1193 	    8, 1, &keyformat, tx));
1194 	VERIFY0(zap_update(mos, dckobj, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT),
1195 	    8, 1, &salt, tx));
1196 	VERIFY0(zap_update(mos, dckobj, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS),
1197 	    8, 1, &iters, tx));
1198 }
1199 
1200 static void
1201 dsl_crypto_key_sync(dsl_crypto_key_t *dck, dmu_tx_t *tx)
1202 {
1203 	zio_crypt_key_t *key = &dck->dck_key;
1204 	dsl_wrapping_key_t *wkey = dck->dck_wkey;
1205 	uint8_t keydata[MASTER_KEY_MAX_LEN];
1206 	uint8_t hmac_keydata[SHA512_HMAC_KEYLEN];
1207 	uint8_t iv[WRAPPING_IV_LEN];
1208 	uint8_t mac[WRAPPING_MAC_LEN];
1209 
1210 	ASSERT(dmu_tx_is_syncing(tx));
1211 	ASSERT3U(key->zk_crypt, <, ZIO_CRYPT_FUNCTIONS);
1212 
1213 	/* encrypt and store the keys along with the IV and MAC */
1214 	VERIFY0(zio_crypt_key_wrap(&dck->dck_wkey->wk_key, key, iv, mac,
1215 	    keydata, hmac_keydata));
1216 
1217 	/* update the ZAP with the obtained values */
1218 	dsl_crypto_key_sync_impl(tx->tx_pool->dp_meta_objset, dck->dck_obj,
1219 	    key->zk_crypt, wkey->wk_ddobj, key->zk_guid, iv, mac, keydata,
1220 	    hmac_keydata, wkey->wk_keyformat, wkey->wk_salt, wkey->wk_iters,
1221 	    tx);
1222 }
1223 
1224 int
1225 spa_keystore_change_key_check(void *arg, dmu_tx_t *tx)
1226 {
1227 	int ret;
1228 	dsl_dir_t *dd = NULL;
1229 	dsl_pool_t *dp = dmu_tx_pool(tx);
1230 	spa_keystore_change_key_args_t *skcka = arg;
1231 	dsl_crypto_params_t *dcp = skcka->skcka_cp;
1232 	uint64_t rddobj;
1233 
1234 	/* check for the encryption feature */
1235 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION)) {
1236 		ret = SET_ERROR(ENOTSUP);
1237 		goto error;
1238 	}
1239 
1240 	/* check for valid key change command */
1241 	if (dcp->cp_cmd != DCP_CMD_NEW_KEY &&
1242 	    dcp->cp_cmd != DCP_CMD_INHERIT &&
1243 	    dcp->cp_cmd != DCP_CMD_FORCE_NEW_KEY &&
1244 	    dcp->cp_cmd != DCP_CMD_FORCE_INHERIT) {
1245 		ret = SET_ERROR(EINVAL);
1246 		goto error;
1247 	}
1248 
1249 	/* hold the dd */
1250 	ret = dsl_dir_hold(dp, skcka->skcka_dsname, FTAG, &dd, NULL);
1251 	if (ret != 0)
1252 		goto error;
1253 
1254 	/* verify that the dataset is encrypted */
1255 	if (dd->dd_crypto_obj == 0) {
1256 		ret = SET_ERROR(EINVAL);
1257 		goto error;
1258 	}
1259 
1260 	/* clones must always use their origin's key */
1261 	if (dsl_dir_is_clone(dd)) {
1262 		ret = SET_ERROR(EINVAL);
1263 		goto error;
1264 	}
1265 
1266 	/* lookup the ddobj we are inheriting the keylocation from */
1267 	ret = dsl_dir_get_encryption_root_ddobj(dd, &rddobj);
1268 	if (ret != 0)
1269 		goto error;
1270 
1271 	/* Handle inheritance */
1272 	if (dcp->cp_cmd == DCP_CMD_INHERIT ||
1273 	    dcp->cp_cmd == DCP_CMD_FORCE_INHERIT) {
1274 		/* no other encryption params should be given */
1275 		if (dcp->cp_crypt != ZIO_CRYPT_INHERIT ||
1276 		    dcp->cp_keylocation != NULL ||
1277 		    dcp->cp_wkey != NULL) {
1278 			ret = SET_ERROR(EINVAL);
1279 			goto error;
1280 		}
1281 
1282 		/* check that this is an encryption root */
1283 		if (dd->dd_object != rddobj) {
1284 			ret = SET_ERROR(EINVAL);
1285 			goto error;
1286 		}
1287 
1288 		/* check that the parent is encrypted */
1289 		if (dd->dd_parent->dd_crypto_obj == 0) {
1290 			ret = SET_ERROR(EINVAL);
1291 			goto error;
1292 		}
1293 
1294 		/* if we are rewrapping check that both keys are loaded */
1295 		if (dcp->cp_cmd == DCP_CMD_INHERIT) {
1296 			ret = dmu_objset_check_wkey_loaded(dd);
1297 			if (ret != 0)
1298 				goto error;
1299 
1300 			ret = dmu_objset_check_wkey_loaded(dd->dd_parent);
1301 			if (ret != 0)
1302 				goto error;
1303 		}
1304 
1305 		dsl_dir_rele(dd, FTAG);
1306 		return (0);
1307 	}
1308 
1309 	/* handle forcing an encryption root without rewrapping */
1310 	if (dcp->cp_cmd == DCP_CMD_FORCE_NEW_KEY) {
1311 		/* no other encryption params should be given */
1312 		if (dcp->cp_crypt != ZIO_CRYPT_INHERIT ||
1313 		    dcp->cp_keylocation != NULL ||
1314 		    dcp->cp_wkey != NULL) {
1315 			ret = SET_ERROR(EINVAL);
1316 			goto error;
1317 		}
1318 
1319 		/* check that this is not an encryption root */
1320 		if (dd->dd_object == rddobj) {
1321 			ret = SET_ERROR(EINVAL);
1322 			goto error;
1323 		}
1324 
1325 		dsl_dir_rele(dd, FTAG);
1326 		return (0);
1327 	}
1328 
1329 	/* crypt cannot be changed after creation */
1330 	if (dcp->cp_crypt != ZIO_CRYPT_INHERIT) {
1331 		ret = SET_ERROR(EINVAL);
1332 		goto error;
1333 	}
1334 
1335 	/* we are not inheritting our parent's wkey so we need one ourselves */
1336 	if (dcp->cp_wkey == NULL) {
1337 		ret = SET_ERROR(EINVAL);
1338 		goto error;
1339 	}
1340 
1341 	/* check for a valid keyformat for the new wrapping key */
1342 	if (dcp->cp_wkey->wk_keyformat >= ZFS_KEYFORMAT_FORMATS ||
1343 	    dcp->cp_wkey->wk_keyformat == ZFS_KEYFORMAT_NONE) {
1344 		ret = SET_ERROR(EINVAL);
1345 		goto error;
1346 	}
1347 
1348 	/*
1349 	 * If this dataset is not currently an encryption root we need a new
1350 	 * keylocation for this dataset's new wrapping key. Otherwise we can
1351 	 * just keep the one we already had.
1352 	 */
1353 	if (dd->dd_object != rddobj && dcp->cp_keylocation == NULL) {
1354 		ret = SET_ERROR(EINVAL);
1355 		goto error;
1356 	}
1357 
1358 	/* check that the keylocation is valid if it is not NULL */
1359 	if (dcp->cp_keylocation != NULL &&
1360 	    !zfs_prop_valid_keylocation(dcp->cp_keylocation, B_TRUE)) {
1361 		ret = SET_ERROR(EINVAL);
1362 		goto error;
1363 	}
1364 
1365 	/* passphrases require pbkdf2 salt and iters */
1366 	if (dcp->cp_wkey->wk_keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
1367 		if (dcp->cp_wkey->wk_salt == 0 ||
1368 		    dcp->cp_wkey->wk_iters < MIN_PBKDF2_ITERATIONS) {
1369 			ret = SET_ERROR(EINVAL);
1370 			goto error;
1371 		}
1372 	} else {
1373 		if (dcp->cp_wkey->wk_salt != 0 || dcp->cp_wkey->wk_iters != 0) {
1374 			ret = SET_ERROR(EINVAL);
1375 			goto error;
1376 		}
1377 	}
1378 
1379 	/* make sure the dd's wkey is loaded */
1380 	ret = dmu_objset_check_wkey_loaded(dd);
1381 	if (ret != 0)
1382 		goto error;
1383 
1384 	dsl_dir_rele(dd, FTAG);
1385 
1386 	return (0);
1387 
1388 error:
1389 	if (dd != NULL)
1390 		dsl_dir_rele(dd, FTAG);
1391 
1392 	return (ret);
1393 }
1394 
1395 /*
1396  * This function deals with the intricacies of updating wrapping
1397  * key references and encryption roots recursively in the event
1398  * of a call to 'zfs change-key' or 'zfs promote'. The 'skip'
1399  * parameter should always be set to B_FALSE when called
1400  * externally.
1401  */
1402 static void
1403 spa_keystore_change_key_sync_impl(uint64_t rddobj, uint64_t ddobj,
1404     uint64_t new_rddobj, dsl_wrapping_key_t *wkey, boolean_t skip,
1405     dmu_tx_t *tx)
1406 {
1407 	int ret;
1408 	zap_cursor_t *zc;
1409 	zap_attribute_t *za;
1410 	dsl_pool_t *dp = dmu_tx_pool(tx);
1411 	dsl_dir_t *dd = NULL;
1412 	dsl_crypto_key_t *dck = NULL;
1413 	uint64_t curr_rddobj;
1414 
1415 	ASSERT(RW_WRITE_HELD(&dp->dp_spa->spa_keystore.sk_wkeys_lock));
1416 
1417 	/* hold the dd */
1418 	VERIFY0(dsl_dir_hold_obj(dp, ddobj, NULL, FTAG, &dd));
1419 
1420 	/* ignore special dsl dirs */
1421 	if (dd->dd_myname[0] == '$' || dd->dd_myname[0] == '%') {
1422 		dsl_dir_rele(dd, FTAG);
1423 		return;
1424 	}
1425 
1426 	ret = dsl_dir_get_encryption_root_ddobj(dd, &curr_rddobj);
1427 	VERIFY(ret == 0 || ret == ENOENT);
1428 
1429 	/*
1430 	 * Stop recursing if this dsl dir didn't inherit from the root
1431 	 * or if this dd is a clone.
1432 	 */
1433 	if (ret == ENOENT ||
1434 	    (!skip && (curr_rddobj != rddobj || dsl_dir_is_clone(dd)))) {
1435 		dsl_dir_rele(dd, FTAG);
1436 		return;
1437 	}
1438 
1439 	/*
1440 	 * If we don't have a wrapping key just update the dck to reflect the
1441 	 * new encryption root. Otherwise rewrap the entire dck and re-sync it
1442 	 * to disk. If skip is set, we don't do any of this work.
1443 	 */
1444 	if (!skip) {
1445 		if (wkey == NULL) {
1446 			VERIFY0(zap_update(dp->dp_meta_objset,
1447 			    dd->dd_crypto_obj,
1448 			    DSL_CRYPTO_KEY_ROOT_DDOBJ, 8, 1,
1449 			    &new_rddobj, tx));
1450 		} else {
1451 			VERIFY0(spa_keystore_dsl_key_hold_dd(dp->dp_spa, dd,
1452 			    FTAG, &dck));
1453 			dsl_wrapping_key_hold(wkey, dck);
1454 			dsl_wrapping_key_rele(dck->dck_wkey, dck);
1455 			dck->dck_wkey = wkey;
1456 			dsl_crypto_key_sync(dck, tx);
1457 			spa_keystore_dsl_key_rele(dp->dp_spa, dck, FTAG);
1458 		}
1459 	}
1460 
1461 	zc = kmem_alloc(sizeof (zap_cursor_t), KM_SLEEP);
1462 	za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
1463 
1464 	/* Recurse into all child dsl dirs. */
1465 	for (zap_cursor_init(zc, dp->dp_meta_objset,
1466 	    dsl_dir_phys(dd)->dd_child_dir_zapobj);
1467 	    zap_cursor_retrieve(zc, za) == 0;
1468 	    zap_cursor_advance(zc)) {
1469 		spa_keystore_change_key_sync_impl(rddobj,
1470 		    za->za_first_integer, new_rddobj, wkey, B_FALSE, tx);
1471 	}
1472 	zap_cursor_fini(zc);
1473 
1474 	/*
1475 	 * Recurse into all dsl dirs of clones. We utilize the skip parameter
1476 	 * here so that we don't attempt to process the clones directly. This
1477 	 * is because the clone and its origin share the same dck, which has
1478 	 * already been updated.
1479 	 */
1480 	for (zap_cursor_init(zc, dp->dp_meta_objset,
1481 	    dsl_dir_phys(dd)->dd_clones);
1482 	    zap_cursor_retrieve(zc, za) == 0;
1483 	    zap_cursor_advance(zc)) {
1484 		dsl_dataset_t *clone;
1485 
1486 		VERIFY0(dsl_dataset_hold_obj(dp, za->za_first_integer,
1487 		    FTAG, &clone));
1488 		spa_keystore_change_key_sync_impl(rddobj,
1489 		    clone->ds_dir->dd_object, new_rddobj, wkey, B_TRUE, tx);
1490 		dsl_dataset_rele(clone, FTAG);
1491 	}
1492 	zap_cursor_fini(zc);
1493 
1494 	kmem_free(za, sizeof (zap_attribute_t));
1495 	kmem_free(zc, sizeof (zap_cursor_t));
1496 
1497 	dsl_dir_rele(dd, FTAG);
1498 }
1499 
1500 void
1501 spa_keystore_change_key_sync(void *arg, dmu_tx_t *tx)
1502 {
1503 	dsl_dataset_t *ds;
1504 	avl_index_t where;
1505 	dsl_pool_t *dp = dmu_tx_pool(tx);
1506 	spa_t *spa = dp->dp_spa;
1507 	spa_keystore_change_key_args_t *skcka = arg;
1508 	dsl_crypto_params_t *dcp = skcka->skcka_cp;
1509 	dsl_wrapping_key_t *wkey = NULL, *found_wkey;
1510 	dsl_wrapping_key_t wkey_search;
1511 	char *keylocation = dcp->cp_keylocation;
1512 	uint64_t rddobj, new_rddobj;
1513 
1514 	/* create and initialize the wrapping key */
1515 	VERIFY0(dsl_dataset_hold(dp, skcka->skcka_dsname, FTAG, &ds));
1516 	ASSERT(!ds->ds_is_snapshot);
1517 
1518 	if (dcp->cp_cmd == DCP_CMD_NEW_KEY ||
1519 	    dcp->cp_cmd == DCP_CMD_FORCE_NEW_KEY) {
1520 		/*
1521 		 * We are changing to a new wkey. Set additional properties
1522 		 * which can be sent along with this ioctl. Note that this
1523 		 * command can set keylocation even if it can't normally be
1524 		 * set via 'zfs set' due to a non-local keylocation.
1525 		 */
1526 		if (dcp->cp_cmd == DCP_CMD_NEW_KEY) {
1527 			wkey = dcp->cp_wkey;
1528 			wkey->wk_ddobj = ds->ds_dir->dd_object;
1529 		} else {
1530 			keylocation = "prompt";
1531 		}
1532 
1533 		if (keylocation != NULL) {
1534 			dsl_prop_set_sync_impl(ds,
1535 			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1536 			    ZPROP_SRC_LOCAL, 1, strlen(keylocation) + 1,
1537 			    keylocation, tx);
1538 		}
1539 
1540 		VERIFY0(dsl_dir_get_encryption_root_ddobj(ds->ds_dir, &rddobj));
1541 		new_rddobj = ds->ds_dir->dd_object;
1542 	} else {
1543 		/*
1544 		 * We are inheriting the parent's wkey. Unset any local
1545 		 * keylocation and grab a reference to the wkey.
1546 		 */
1547 		if (dcp->cp_cmd == DCP_CMD_INHERIT) {
1548 			VERIFY0(spa_keystore_wkey_hold_dd(spa,
1549 			    ds->ds_dir->dd_parent, FTAG, &wkey));
1550 		}
1551 
1552 		dsl_prop_set_sync_impl(ds,
1553 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), ZPROP_SRC_NONE,
1554 		    0, 0, NULL, tx);
1555 
1556 		rddobj = ds->ds_dir->dd_object;
1557 		VERIFY0(dsl_dir_get_encryption_root_ddobj(ds->ds_dir->dd_parent,
1558 		    &new_rddobj));
1559 	}
1560 
1561 	if (wkey == NULL) {
1562 		ASSERT(dcp->cp_cmd == DCP_CMD_FORCE_INHERIT ||
1563 		    dcp->cp_cmd == DCP_CMD_FORCE_NEW_KEY);
1564 	}
1565 
1566 	rw_enter(&spa->spa_keystore.sk_wkeys_lock, RW_WRITER);
1567 
1568 	/* recurse through all children and rewrap their keys */
1569 	spa_keystore_change_key_sync_impl(rddobj, ds->ds_dir->dd_object,
1570 	    new_rddobj, wkey, B_FALSE, tx);
1571 
1572 	/*
1573 	 * All references to the old wkey should be released now (if it
1574 	 * existed). Replace the wrapping key.
1575 	 */
1576 	wkey_search.wk_ddobj = ds->ds_dir->dd_object;
1577 	found_wkey = avl_find(&spa->spa_keystore.sk_wkeys, &wkey_search, NULL);
1578 	if (found_wkey != NULL) {
1579 		ASSERT0(zfs_refcount_count(&found_wkey->wk_refcnt));
1580 		avl_remove(&spa->spa_keystore.sk_wkeys, found_wkey);
1581 		dsl_wrapping_key_free(found_wkey);
1582 	}
1583 
1584 	if (dcp->cp_cmd == DCP_CMD_NEW_KEY) {
1585 		(void) avl_find(&spa->spa_keystore.sk_wkeys, wkey, &where);
1586 		avl_insert(&spa->spa_keystore.sk_wkeys, wkey, where);
1587 	} else if (wkey != NULL) {
1588 		dsl_wrapping_key_rele(wkey, FTAG);
1589 	}
1590 
1591 	rw_exit(&spa->spa_keystore.sk_wkeys_lock);
1592 
1593 	dsl_dataset_rele(ds, FTAG);
1594 }
1595 
1596 int
1597 spa_keystore_change_key(const char *dsname, dsl_crypto_params_t *dcp)
1598 {
1599 	spa_keystore_change_key_args_t skcka;
1600 
1601 	/* initialize the args struct */
1602 	skcka.skcka_dsname = dsname;
1603 	skcka.skcka_cp = dcp;
1604 
1605 	/*
1606 	 * Perform the actual work in syncing context. The blocks modified
1607 	 * here could be calculated but it would require holding the pool
1608 	 * lock and traversing all of the datasets that will have their keys
1609 	 * changed.
1610 	 */
1611 	return (dsl_sync_task(dsname, spa_keystore_change_key_check,
1612 	    spa_keystore_change_key_sync, &skcka, 15,
1613 	    ZFS_SPACE_CHECK_RESERVED));
1614 }
1615 
1616 int
1617 dsl_dir_rename_crypt_check(dsl_dir_t *dd, dsl_dir_t *newparent)
1618 {
1619 	int ret;
1620 	uint64_t curr_rddobj, parent_rddobj;
1621 
1622 	if (dd->dd_crypto_obj == 0)
1623 		return (0);
1624 
1625 	ret = dsl_dir_get_encryption_root_ddobj(dd, &curr_rddobj);
1626 	if (ret != 0)
1627 		goto error;
1628 
1629 	/*
1630 	 * if this is not an encryption root, we must make sure we are not
1631 	 * moving dd to a new encryption root
1632 	 */
1633 	if (dd->dd_object != curr_rddobj) {
1634 		ret = dsl_dir_get_encryption_root_ddobj(newparent,
1635 		    &parent_rddobj);
1636 		if (ret != 0)
1637 			goto error;
1638 
1639 		if (parent_rddobj != curr_rddobj) {
1640 			ret = SET_ERROR(EACCES);
1641 			goto error;
1642 		}
1643 	}
1644 
1645 	return (0);
1646 
1647 error:
1648 	return (ret);
1649 }
1650 
1651 /*
1652  * Check to make sure that a promote from targetdd to origindd will not require
1653  * any key rewraps.
1654  */
1655 int
1656 dsl_dataset_promote_crypt_check(dsl_dir_t *target, dsl_dir_t *origin)
1657 {
1658 	int ret;
1659 	uint64_t rddobj, op_rddobj, tp_rddobj;
1660 
1661 	/* If the dataset is not encrypted we don't need to check anything */
1662 	if (origin->dd_crypto_obj == 0)
1663 		return (0);
1664 
1665 	/*
1666 	 * If we are not changing the first origin snapshot in a chain
1667 	 * the encryption root won't change either.
1668 	 */
1669 	if (dsl_dir_is_clone(origin))
1670 		return (0);
1671 
1672 	/*
1673 	 * If the origin is the encryption root we will update
1674 	 * the DSL Crypto Key to point to the target instead.
1675 	 */
1676 	ret = dsl_dir_get_encryption_root_ddobj(origin, &rddobj);
1677 	if (ret != 0)
1678 		return (ret);
1679 
1680 	if (rddobj == origin->dd_object)
1681 		return (0);
1682 
1683 	/*
1684 	 * The origin is inheriting its encryption root from its parent.
1685 	 * Check that the parent of the target has the same encryption root.
1686 	 */
1687 	ret = dsl_dir_get_encryption_root_ddobj(origin->dd_parent, &op_rddobj);
1688 	if (ret != 0)
1689 		return (ret);
1690 
1691 	ret = dsl_dir_get_encryption_root_ddobj(target->dd_parent, &tp_rddobj);
1692 	if (ret != 0)
1693 		return (ret);
1694 
1695 	if (op_rddobj != tp_rddobj)
1696 		return (SET_ERROR(EACCES));
1697 
1698 	return (0);
1699 }
1700 
1701 void
1702 dsl_dataset_promote_crypt_sync(dsl_dir_t *target, dsl_dir_t *origin,
1703     dmu_tx_t *tx)
1704 {
1705 	uint64_t rddobj;
1706 	dsl_pool_t *dp = target->dd_pool;
1707 	dsl_dataset_t *targetds;
1708 	dsl_dataset_t *originds;
1709 	char *keylocation;
1710 
1711 	if (origin->dd_crypto_obj == 0)
1712 		return;
1713 	if (dsl_dir_is_clone(origin))
1714 		return;
1715 
1716 	VERIFY0(dsl_dir_get_encryption_root_ddobj(origin, &rddobj));
1717 
1718 	if (rddobj != origin->dd_object)
1719 		return;
1720 
1721 	/*
1722 	 * If the target is being promoted to the encryption root update the
1723 	 * DSL Crypto Key and keylocation to reflect that. We also need to
1724 	 * update the DSL Crypto Keys of all children inheriting their
1725 	 * encryption root to point to the new target. Otherwise, the check
1726 	 * function ensured that the encryption root will not change.
1727 	 */
1728 	keylocation = kmem_alloc(ZAP_MAXVALUELEN, KM_SLEEP);
1729 
1730 	VERIFY0(dsl_dataset_hold_obj(dp,
1731 	    dsl_dir_phys(target)->dd_head_dataset_obj, FTAG, &targetds));
1732 	VERIFY0(dsl_dataset_hold_obj(dp,
1733 	    dsl_dir_phys(origin)->dd_head_dataset_obj, FTAG, &originds));
1734 
1735 	VERIFY0(dsl_prop_get_dd(origin, zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1736 	    1, ZAP_MAXVALUELEN, keylocation, NULL, B_FALSE));
1737 	dsl_prop_set_sync_impl(targetds, zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1738 	    ZPROP_SRC_LOCAL, 1, strlen(keylocation) + 1, keylocation, tx);
1739 	dsl_prop_set_sync_impl(originds, zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1740 	    ZPROP_SRC_NONE, 0, 0, NULL, tx);
1741 
1742 	rw_enter(&dp->dp_spa->spa_keystore.sk_wkeys_lock, RW_WRITER);
1743 	spa_keystore_change_key_sync_impl(rddobj, origin->dd_object,
1744 	    target->dd_object, NULL, B_FALSE, tx);
1745 	rw_exit(&dp->dp_spa->spa_keystore.sk_wkeys_lock);
1746 
1747 	dsl_dataset_rele(targetds, FTAG);
1748 	dsl_dataset_rele(originds, FTAG);
1749 	kmem_free(keylocation, ZAP_MAXVALUELEN);
1750 }
1751 
1752 int
1753 dmu_objset_create_crypt_check(dsl_dir_t *parentdd, dsl_crypto_params_t *dcp,
1754     boolean_t *will_encrypt)
1755 {
1756 	int ret;
1757 	uint64_t pcrypt, crypt;
1758 	dsl_crypto_params_t dummy_dcp = { 0 };
1759 
1760 	if (will_encrypt != NULL)
1761 		*will_encrypt = B_FALSE;
1762 
1763 	if (dcp == NULL)
1764 		dcp = &dummy_dcp;
1765 
1766 	if (dcp->cp_cmd != DCP_CMD_NONE)
1767 		return (SET_ERROR(EINVAL));
1768 
1769 	if (parentdd != NULL) {
1770 		ret = dsl_dir_get_crypt(parentdd, &pcrypt);
1771 		if (ret != 0)
1772 			return (ret);
1773 	} else {
1774 		pcrypt = ZIO_CRYPT_OFF;
1775 	}
1776 
1777 	crypt = (dcp->cp_crypt == ZIO_CRYPT_INHERIT) ? pcrypt : dcp->cp_crypt;
1778 
1779 	ASSERT3U(pcrypt, !=, ZIO_CRYPT_INHERIT);
1780 	ASSERT3U(crypt, !=, ZIO_CRYPT_INHERIT);
1781 
1782 	/* check for valid dcp with no encryption (inherited or local) */
1783 	if (crypt == ZIO_CRYPT_OFF) {
1784 		/* Must not specify encryption params */
1785 		if (dcp->cp_wkey != NULL ||
1786 		    (dcp->cp_keylocation != NULL &&
1787 		    strcmp(dcp->cp_keylocation, "none") != 0))
1788 			return (SET_ERROR(EINVAL));
1789 
1790 		return (0);
1791 	}
1792 
1793 	if (will_encrypt != NULL)
1794 		*will_encrypt = B_TRUE;
1795 
1796 	/*
1797 	 * We will now definitely be encrypting. Check the feature flag. When
1798 	 * creating the pool the caller will check this for us since we won't
1799 	 * technically have the feature activated yet.
1800 	 */
1801 	if (parentdd != NULL &&
1802 	    !spa_feature_is_enabled(parentdd->dd_pool->dp_spa,
1803 	    SPA_FEATURE_ENCRYPTION)) {
1804 		return (SET_ERROR(EOPNOTSUPP));
1805 	}
1806 
1807 	/* check for errata #4 (encryption enabled, bookmark_v2 disabled) */
1808 	if (parentdd != NULL &&
1809 	    !spa_feature_is_enabled(parentdd->dd_pool->dp_spa,
1810 	    SPA_FEATURE_BOOKMARK_V2)) {
1811 		return (SET_ERROR(EOPNOTSUPP));
1812 	}
1813 
1814 	/* handle inheritance */
1815 	if (dcp->cp_wkey == NULL) {
1816 		ASSERT3P(parentdd, !=, NULL);
1817 
1818 		/* key must be fully unspecified */
1819 		if (dcp->cp_keylocation != NULL)
1820 			return (SET_ERROR(EINVAL));
1821 
1822 		/* parent must have a key to inherit */
1823 		if (pcrypt == ZIO_CRYPT_OFF)
1824 			return (SET_ERROR(EINVAL));
1825 
1826 		/* check for parent key */
1827 		ret = dmu_objset_check_wkey_loaded(parentdd);
1828 		if (ret != 0)
1829 			return (ret);
1830 
1831 		return (0);
1832 	}
1833 
1834 	/* At this point we should have a fully specified key. Check location */
1835 	if (dcp->cp_keylocation == NULL ||
1836 	    !zfs_prop_valid_keylocation(dcp->cp_keylocation, B_TRUE))
1837 		return (SET_ERROR(EINVAL));
1838 
1839 	/* Must have fully specified keyformat */
1840 	switch (dcp->cp_wkey->wk_keyformat) {
1841 		case ZFS_KEYFORMAT_HEX:
1842 		case ZFS_KEYFORMAT_RAW:
1843 			/* requires no pbkdf2 iters and salt */
1844 			if (dcp->cp_wkey->wk_salt != 0 ||
1845 			    dcp->cp_wkey->wk_iters != 0)
1846 				return (SET_ERROR(EINVAL));
1847 			break;
1848 		case ZFS_KEYFORMAT_PASSPHRASE:
1849 			/* requires pbkdf2 iters and salt */
1850 			if (dcp->cp_wkey->wk_salt == 0 ||
1851 			    dcp->cp_wkey->wk_iters < MIN_PBKDF2_ITERATIONS)
1852 				return (SET_ERROR(EINVAL));
1853 			break;
1854 		case ZFS_KEYFORMAT_NONE:
1855 		default:
1856 			/* keyformat must be specified and valid */
1857 			return (SET_ERROR(EINVAL));
1858 	}
1859 
1860 	return (0);
1861 }
1862 
1863 void
1864 dsl_dataset_create_crypt_sync(uint64_t dsobj, dsl_dir_t *dd,
1865     dsl_dataset_t *origin, dsl_crypto_params_t *dcp, dmu_tx_t *tx)
1866 {
1867 	dsl_pool_t *dp = dd->dd_pool;
1868 	uint64_t crypt;
1869 	dsl_wrapping_key_t *wkey;
1870 
1871 	/* clones always use their origin's wrapping key */
1872 	if (dsl_dir_is_clone(dd)) {
1873 		ASSERT3P(dcp, ==, NULL);
1874 
1875 		/*
1876 		 * If this is an encrypted clone we just need to clone the
1877 		 * dck into dd. Zapify the dd so we can do that.
1878 		 */
1879 		if (origin->ds_dir->dd_crypto_obj != 0) {
1880 			dmu_buf_will_dirty(dd->dd_dbuf, tx);
1881 			dsl_dir_zapify(dd, tx);
1882 
1883 			dd->dd_crypto_obj =
1884 			    dsl_crypto_key_clone_sync(origin->ds_dir, tx);
1885 			VERIFY0(zap_add(dp->dp_meta_objset, dd->dd_object,
1886 			    DD_FIELD_CRYPTO_KEY_OBJ, sizeof (uint64_t), 1,
1887 			    &dd->dd_crypto_obj, tx));
1888 		}
1889 
1890 		return;
1891 	}
1892 
1893 	/*
1894 	 * A NULL dcp at this point indicates this is the origin dataset
1895 	 * which does not have an objset to encrypt. Raw receives will handle
1896 	 * encryption separately later. In both cases we can simply return.
1897 	 */
1898 	if (dcp == NULL || dcp->cp_cmd == DCP_CMD_RAW_RECV)
1899 		return;
1900 
1901 	crypt = dcp->cp_crypt;
1902 	wkey = dcp->cp_wkey;
1903 
1904 	/* figure out the effective crypt */
1905 	if (crypt == ZIO_CRYPT_INHERIT && dd->dd_parent != NULL)
1906 		VERIFY0(dsl_dir_get_crypt(dd->dd_parent, &crypt));
1907 
1908 	/* if we aren't doing encryption just return */
1909 	if (crypt == ZIO_CRYPT_OFF || crypt == ZIO_CRYPT_INHERIT)
1910 		return;
1911 
1912 	/* zapify the dd so that we can add the crypto key obj to it */
1913 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1914 	dsl_dir_zapify(dd, tx);
1915 
1916 	/* use the new key if given or inherit from the parent */
1917 	if (wkey == NULL) {
1918 		VERIFY0(spa_keystore_wkey_hold_dd(dp->dp_spa,
1919 		    dd->dd_parent, FTAG, &wkey));
1920 	} else {
1921 		wkey->wk_ddobj = dd->dd_object;
1922 	}
1923 
1924 	ASSERT3P(wkey, !=, NULL);
1925 
1926 	/* Create or clone the DSL crypto key and activate the feature */
1927 	dd->dd_crypto_obj = dsl_crypto_key_create_sync(crypt, wkey, tx);
1928 	VERIFY0(zap_add(dp->dp_meta_objset, dd->dd_object,
1929 	    DD_FIELD_CRYPTO_KEY_OBJ, sizeof (uint64_t), 1, &dd->dd_crypto_obj,
1930 	    tx));
1931 	dsl_dataset_activate_feature(dsobj, SPA_FEATURE_ENCRYPTION, tx);
1932 
1933 	/*
1934 	 * If we inherited the wrapping key we release our reference now.
1935 	 * Otherwise, this is a new key and we need to load it into the
1936 	 * keystore.
1937 	 */
1938 	if (dcp->cp_wkey == NULL) {
1939 		dsl_wrapping_key_rele(wkey, FTAG);
1940 	} else {
1941 		VERIFY0(spa_keystore_load_wkey_impl(dp->dp_spa, wkey));
1942 	}
1943 }
1944 
1945 typedef struct dsl_crypto_recv_key_arg {
1946 	uint64_t dcrka_dsobj;
1947 	uint64_t dcrka_fromobj;
1948 	dmu_objset_type_t dcrka_ostype;
1949 	nvlist_t *dcrka_nvl;
1950 	boolean_t dcrka_do_key;
1951 } dsl_crypto_recv_key_arg_t;
1952 
1953 static int
1954 dsl_crypto_recv_raw_objset_check(dsl_dataset_t *ds, dsl_dataset_t *fromds,
1955     dmu_objset_type_t ostype, nvlist_t *nvl, dmu_tx_t *tx)
1956 {
1957 	int ret;
1958 	objset_t *os;
1959 	dnode_t *mdn;
1960 	uint8_t *buf = NULL;
1961 	uint_t len;
1962 	uint64_t intval, nlevels, blksz, ibs;
1963 	uint64_t nblkptr, maxblkid;
1964 
1965 	if (ostype != DMU_OST_ZFS && ostype != DMU_OST_ZVOL)
1966 		return (SET_ERROR(EINVAL));
1967 
1968 	/* raw receives also need info about the structure of the metadnode */
1969 	ret = nvlist_lookup_uint64(nvl, "mdn_compress", &intval);
1970 	if (ret != 0 || intval >= ZIO_COMPRESS_LEGACY_FUNCTIONS)
1971 		return (SET_ERROR(EINVAL));
1972 
1973 	ret = nvlist_lookup_uint64(nvl, "mdn_checksum", &intval);
1974 	if (ret != 0 || intval >= ZIO_CHECKSUM_LEGACY_FUNCTIONS)
1975 		return (SET_ERROR(EINVAL));
1976 
1977 	ret = nvlist_lookup_uint64(nvl, "mdn_nlevels", &nlevels);
1978 	if (ret != 0 || nlevels > DN_MAX_LEVELS)
1979 		return (SET_ERROR(EINVAL));
1980 
1981 	ret = nvlist_lookup_uint64(nvl, "mdn_blksz", &blksz);
1982 	if (ret != 0 || blksz < SPA_MINBLOCKSIZE)
1983 		return (SET_ERROR(EINVAL));
1984 	else if (blksz > spa_maxblocksize(tx->tx_pool->dp_spa))
1985 		return (SET_ERROR(ENOTSUP));
1986 
1987 	ret = nvlist_lookup_uint64(nvl, "mdn_indblkshift", &ibs);
1988 	if (ret != 0 || ibs < DN_MIN_INDBLKSHIFT || ibs > DN_MAX_INDBLKSHIFT)
1989 		return (SET_ERROR(ENOTSUP));
1990 
1991 	ret = nvlist_lookup_uint64(nvl, "mdn_nblkptr", &nblkptr);
1992 	if (ret != 0 || nblkptr != DN_MAX_NBLKPTR)
1993 		return (SET_ERROR(ENOTSUP));
1994 
1995 	ret = nvlist_lookup_uint64(nvl, "mdn_maxblkid", &maxblkid);
1996 	if (ret != 0)
1997 		return (SET_ERROR(EINVAL));
1998 
1999 	ret = nvlist_lookup_uint8_array(nvl, "portable_mac", &buf, &len);
2000 	if (ret != 0 || len != ZIO_OBJSET_MAC_LEN)
2001 		return (SET_ERROR(EINVAL));
2002 
2003 	ret = dmu_objset_from_ds(ds, &os);
2004 	if (ret != 0)
2005 		return (ret);
2006 
2007 	/*
2008 	 * Useraccounting is not portable and must be done with the keys loaded.
2009 	 * Therefore, whenever we do any kind of receive the useraccounting
2010 	 * must not be present.
2011 	 */
2012 	ASSERT0(os->os_flags & OBJSET_FLAG_USERACCOUNTING_COMPLETE);
2013 
2014 	mdn = DMU_META_DNODE(os);
2015 
2016 	/*
2017 	 * If we already created the objset, make sure its unchangeable
2018 	 * properties match the ones received in the nvlist.
2019 	 */
2020 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2021 	if (!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)) &&
2022 	    (mdn->dn_nlevels != nlevels || mdn->dn_datablksz != blksz ||
2023 	    mdn->dn_indblkshift != ibs || mdn->dn_nblkptr != nblkptr)) {
2024 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
2025 		return (SET_ERROR(EINVAL));
2026 	}
2027 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2028 
2029 	/*
2030 	 * Check that the ivset guid of the fromds matches the one from the
2031 	 * send stream. Older versions of the encryption code did not have
2032 	 * an ivset guid on the from dataset and did not send one in the
2033 	 * stream. For these streams we provide the
2034 	 * zfs_disable_ivset_guid_check tunable to allow these datasets to
2035 	 * be received with a generated ivset guid.
2036 	 */
2037 	if (fromds != NULL && !zfs_disable_ivset_guid_check) {
2038 		uint64_t from_ivset_guid = 0;
2039 		intval = 0;
2040 
2041 		(void) nvlist_lookup_uint64(nvl, "from_ivset_guid", &intval);
2042 		(void) zap_lookup(tx->tx_pool->dp_meta_objset,
2043 		    fromds->ds_object, DS_FIELD_IVSET_GUID,
2044 		    sizeof (from_ivset_guid), 1, &from_ivset_guid);
2045 
2046 		if (intval == 0 || from_ivset_guid == 0)
2047 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISSING));
2048 
2049 		if (intval != from_ivset_guid)
2050 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISMATCH));
2051 	}
2052 
2053 	/*
2054 	 * Check that the ivset guid of the fromds matches the one from the
2055 	 * send stream. Older versions of the encryption code did not have
2056 	 * an ivset guid on the from dataset and did not send one in the
2057 	 * stream. For these streams we provide the
2058 	 * zfs_disable_ivset_guid_check tunable to allow these datasets to
2059 	 * be received with a generated ivset guid.
2060 	 */
2061 	if (fromds != NULL && !zfs_disable_ivset_guid_check) {
2062 		uint64_t from_ivset_guid = 0;
2063 		intval = 0;
2064 
2065 		(void) nvlist_lookup_uint64(nvl, "from_ivset_guid", &intval);
2066 		(void) zap_lookup(tx->tx_pool->dp_meta_objset,
2067 		    fromds->ds_object, DS_FIELD_IVSET_GUID,
2068 		    sizeof (from_ivset_guid), 1, &from_ivset_guid);
2069 
2070 		if (intval == 0 || from_ivset_guid == 0)
2071 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISSING));
2072 
2073 		if (intval != from_ivset_guid)
2074 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISMATCH));
2075 	}
2076 
2077 	return (0);
2078 }
2079 
2080 static void
2081 dsl_crypto_recv_raw_objset_sync(dsl_dataset_t *ds, dmu_objset_type_t ostype,
2082     nvlist_t *nvl, dmu_tx_t *tx)
2083 {
2084 	dsl_pool_t *dp = tx->tx_pool;
2085 	objset_t *os;
2086 	dnode_t *mdn;
2087 	zio_t *zio;
2088 	uint8_t *portable_mac;
2089 	uint_t len;
2090 	uint64_t compress, checksum, nlevels, blksz, ibs, maxblkid;
2091 	boolean_t newds = B_FALSE;
2092 
2093 	VERIFY0(dmu_objset_from_ds(ds, &os));
2094 	mdn = DMU_META_DNODE(os);
2095 
2096 	/*
2097 	 * Fetch the values we need from the nvlist. "to_ivset_guid" must
2098 	 * be set on the snapshot, which doesn't exist yet. The receive
2099 	 * code will take care of this for us later.
2100 	 */
2101 	compress = fnvlist_lookup_uint64(nvl, "mdn_compress");
2102 	checksum = fnvlist_lookup_uint64(nvl, "mdn_checksum");
2103 	nlevels = fnvlist_lookup_uint64(nvl, "mdn_nlevels");
2104 	blksz = fnvlist_lookup_uint64(nvl, "mdn_blksz");
2105 	ibs = fnvlist_lookup_uint64(nvl, "mdn_indblkshift");
2106 	maxblkid = fnvlist_lookup_uint64(nvl, "mdn_maxblkid");
2107 	VERIFY0(nvlist_lookup_uint8_array(nvl, "portable_mac", &portable_mac,
2108 	    &len));
2109 
2110 	/* if we haven't created an objset for the ds yet, do that now */
2111 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2112 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(ds))) {
2113 		(void) dmu_objset_create_impl_dnstats(dp->dp_spa, ds,
2114 		    dsl_dataset_get_blkptr(ds), ostype, nlevels, blksz,
2115 		    ibs, tx);
2116 		newds = B_TRUE;
2117 	}
2118 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2119 
2120 	/*
2121 	 * Set the portable MAC. The local MAC will always be zero since the
2122 	 * incoming data will all be portable and user accounting will be
2123 	 * deferred until the next mount. Afterwards, flag the os to be
2124 	 * written out raw next time.
2125 	 */
2126 	arc_release(os->os_phys_buf, &os->os_phys_buf);
2127 	bcopy(portable_mac, os->os_phys->os_portable_mac, ZIO_OBJSET_MAC_LEN);
2128 	bzero(os->os_phys->os_local_mac, ZIO_OBJSET_MAC_LEN);
2129 	os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
2130 
2131 	/* set metadnode compression and checksum */
2132 	mdn->dn_compress = compress;
2133 	mdn->dn_checksum = checksum;
2134 
2135 	rw_enter(&mdn->dn_struct_rwlock, RW_WRITER);
2136 	dnode_new_blkid(mdn, maxblkid, tx, B_FALSE, B_TRUE);
2137 	rw_exit(&mdn->dn_struct_rwlock);
2138 
2139 	/*
2140 	 * We can't normally dirty the dataset in syncing context unless
2141 	 * we are creating a new dataset. In this case, we perform a
2142 	 * pseudo txg sync here instead.
2143 	 */
2144 	if (newds) {
2145 		dsl_dataset_dirty(ds, tx);
2146 	} else {
2147 		zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
2148 		dsl_dataset_sync(ds, zio, tx);
2149 		VERIFY0(zio_wait(zio));
2150 
2151 		/* dsl_dataset_sync_done will drop this reference. */
2152 		dmu_buf_add_ref(ds->ds_dbuf, ds);
2153 		dsl_dataset_sync_done(ds, tx);
2154 	}
2155 }
2156 
2157 int
2158 dsl_crypto_recv_raw_key_check(dsl_dataset_t *ds, nvlist_t *nvl, dmu_tx_t *tx)
2159 {
2160 	int ret;
2161 	objset_t *mos = tx->tx_pool->dp_meta_objset;
2162 	uint8_t *buf = NULL;
2163 	uint_t len;
2164 	uint64_t intval, key_guid, version;
2165 	boolean_t is_passphrase = B_FALSE;
2166 
2167 	ASSERT(dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT);
2168 
2169 	/*
2170 	 * Read and check all the encryption values from the nvlist. We need
2171 	 * all of the fields of a DSL Crypto Key, as well as a fully specified
2172 	 * wrapping key.
2173 	 */
2174 	ret = nvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_CRYPTO_SUITE, &intval);
2175 	if (ret != 0 || intval >= ZIO_CRYPT_FUNCTIONS ||
2176 	    intval <= ZIO_CRYPT_OFF)
2177 		return (SET_ERROR(EINVAL));
2178 
2179 	ret = nvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_GUID, &intval);
2180 	if (ret != 0)
2181 		return (SET_ERROR(EINVAL));
2182 
2183 	/*
2184 	 * If this is an incremental receive make sure the given key guid
2185 	 * matches the one we already have.
2186 	 */
2187 	if (ds->ds_dir->dd_crypto_obj != 0) {
2188 		ret = zap_lookup(mos, ds->ds_dir->dd_crypto_obj,
2189 		    DSL_CRYPTO_KEY_GUID, 8, 1, &key_guid);
2190 		if (ret != 0)
2191 			return (ret);
2192 		if (intval != key_guid)
2193 			return (SET_ERROR(EACCES));
2194 	}
2195 
2196 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MASTER_KEY,
2197 	    &buf, &len);
2198 	if (ret != 0 || len != MASTER_KEY_MAX_LEN)
2199 		return (SET_ERROR(EINVAL));
2200 
2201 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_HMAC_KEY,
2202 	    &buf, &len);
2203 	if (ret != 0 || len != SHA512_HMAC_KEYLEN)
2204 		return (SET_ERROR(EINVAL));
2205 
2206 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_IV, &buf, &len);
2207 	if (ret != 0 || len != WRAPPING_IV_LEN)
2208 		return (SET_ERROR(EINVAL));
2209 
2210 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MAC, &buf, &len);
2211 	if (ret != 0 || len != WRAPPING_MAC_LEN)
2212 		return (SET_ERROR(EINVAL));
2213 
2214 	/*
2215 	 * We don't support receiving old on-disk formats. The version 0
2216 	 * implementation protected several fields in an objset that were
2217 	 * not always portable during a raw receive. As a result, we call
2218 	 * the old version an on-disk errata #3.
2219 	 */
2220 	ret = nvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_VERSION, &version);
2221 	if (ret != 0 || version != ZIO_CRYPT_KEY_CURRENT_VERSION)
2222 		return (SET_ERROR(ENOTSUP));
2223 
2224 	ret = nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
2225 	    &intval);
2226 	if (ret != 0 || intval >= ZFS_KEYFORMAT_FORMATS ||
2227 	    intval == ZFS_KEYFORMAT_NONE)
2228 		return (SET_ERROR(EINVAL));
2229 
2230 	is_passphrase = (intval == ZFS_KEYFORMAT_PASSPHRASE);
2231 
2232 	/*
2233 	 * for raw receives we allow any number of pbkdf2iters since there
2234 	 * won't be a chance for the user to change it.
2235 	 */
2236 	ret = nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS),
2237 	    &intval);
2238 	if (ret != 0 || (is_passphrase == (intval == 0)))
2239 		return (SET_ERROR(EINVAL));
2240 
2241 	ret = nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT),
2242 	    &intval);
2243 	if (ret != 0 || (is_passphrase == (intval == 0)))
2244 		return (SET_ERROR(EINVAL));
2245 
2246 	return (0);
2247 }
2248 
2249 void
2250 dsl_crypto_recv_raw_key_sync(dsl_dataset_t *ds, nvlist_t *nvl, dmu_tx_t *tx)
2251 {
2252 	dsl_pool_t *dp = tx->tx_pool;
2253 	objset_t *mos = dp->dp_meta_objset;
2254 	dsl_dir_t *dd = ds->ds_dir;
2255 	uint_t len;
2256 	uint64_t rddobj, one = 1;
2257 	uint8_t *keydata, *hmac_keydata, *iv, *mac;
2258 	uint64_t crypt, key_guid, keyformat, iters, salt;
2259 	uint64_t version = ZIO_CRYPT_KEY_CURRENT_VERSION;
2260 	char *keylocation = "prompt";
2261 
2262 	/* lookup the values we need to create the DSL Crypto Key */
2263 	crypt = fnvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_CRYPTO_SUITE);
2264 	key_guid = fnvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_GUID);
2265 	keyformat = fnvlist_lookup_uint64(nvl,
2266 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT));
2267 	iters = fnvlist_lookup_uint64(nvl,
2268 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS));
2269 	salt = fnvlist_lookup_uint64(nvl,
2270 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT));
2271 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MASTER_KEY,
2272 	    &keydata, &len));
2273 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_HMAC_KEY,
2274 	    &hmac_keydata, &len));
2275 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_IV, &iv, &len));
2276 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MAC, &mac, &len));
2277 
2278 	/* if this is a new dataset setup the DSL Crypto Key. */
2279 	if (dd->dd_crypto_obj == 0) {
2280 		/* zapify the dsl dir so we can add the key object to it */
2281 		dmu_buf_will_dirty(dd->dd_dbuf, tx);
2282 		dsl_dir_zapify(dd, tx);
2283 
2284 		/* create the DSL Crypto Key on disk and activate the feature */
2285 		dd->dd_crypto_obj = zap_create(mos,
2286 		    DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
2287 		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2288 		    dd->dd_crypto_obj, DSL_CRYPTO_KEY_REFCOUNT,
2289 		    sizeof (uint64_t), 1, &one, tx));
2290 		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2291 		    dd->dd_crypto_obj, DSL_CRYPTO_KEY_VERSION,
2292 		    sizeof (uint64_t), 1, &version, tx));
2293 
2294 		dsl_dataset_activate_feature(ds->ds_object,
2295 		    SPA_FEATURE_ENCRYPTION, tx);
2296 		ds->ds_feature_inuse[SPA_FEATURE_ENCRYPTION] = B_TRUE;
2297 
2298 		/* save the dd_crypto_obj on disk */
2299 		VERIFY0(zap_add(mos, dd->dd_object, DD_FIELD_CRYPTO_KEY_OBJ,
2300 		    sizeof (uint64_t), 1, &dd->dd_crypto_obj, tx));
2301 
2302 		/*
2303 		 * Set the keylocation to prompt by default. If keylocation
2304 		 * has been provided via the properties, this will be overridden
2305 		 * later.
2306 		 */
2307 		dsl_prop_set_sync_impl(ds,
2308 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
2309 		    ZPROP_SRC_LOCAL, 1, strlen(keylocation) + 1,
2310 		    keylocation, tx);
2311 
2312 		rddobj = dd->dd_object;
2313 	} else {
2314 		VERIFY0(dsl_dir_get_encryption_root_ddobj(dd, &rddobj));
2315 	}
2316 
2317 	/* sync the key data to the ZAP object on disk */
2318 	dsl_crypto_key_sync_impl(mos, dd->dd_crypto_obj, crypt,
2319 	    rddobj, key_guid, iv, mac, keydata, hmac_keydata, keyformat, salt,
2320 	    iters, tx);
2321 }
2322 
2323 int
2324 dsl_crypto_recv_key_check(void *arg, dmu_tx_t *tx)
2325 {
2326 	int ret;
2327 	dsl_crypto_recv_key_arg_t *dcrka = arg;
2328 	dsl_dataset_t *ds = NULL, *fromds = NULL;
2329 
2330 	ret = dsl_dataset_hold_obj(tx->tx_pool, dcrka->dcrka_dsobj,
2331 	    FTAG, &ds);
2332 	if (ret != 0)
2333 		goto out;
2334 
2335 	if (dcrka->dcrka_fromobj != 0) {
2336 		ret = dsl_dataset_hold_obj(tx->tx_pool, dcrka->dcrka_fromobj,
2337 		    FTAG, &fromds);
2338 		if (ret != 0)
2339 			goto out;
2340 	}
2341 
2342 	ret = dsl_crypto_recv_raw_objset_check(ds, fromds,
2343 	    dcrka->dcrka_ostype, dcrka->dcrka_nvl, tx);
2344 	if (ret != 0)
2345 		goto out;
2346 
2347 	/*
2348 	 * We run this check even if we won't be doing this part of
2349 	 * the receive now so that we don't make the user wait until
2350 	 * the receive finishes to fail.
2351 	 */
2352 	ret = dsl_crypto_recv_raw_key_check(ds, dcrka->dcrka_nvl, tx);
2353 	if (ret != 0)
2354 		goto out;
2355 
2356 out:
2357 	if (ds != NULL)
2358 		dsl_dataset_rele(ds, FTAG);
2359 	if (fromds != NULL)
2360 		dsl_dataset_rele(fromds, FTAG);
2361 	return (ret);
2362 }
2363 
2364 void
2365 dsl_crypto_recv_key_sync(void *arg, dmu_tx_t *tx)
2366 {
2367 	dsl_crypto_recv_key_arg_t *dcrka = arg;
2368 	dsl_dataset_t *ds;
2369 
2370 	VERIFY0(dsl_dataset_hold_obj(tx->tx_pool, dcrka->dcrka_dsobj,
2371 	    FTAG, &ds));
2372 	dsl_crypto_recv_raw_objset_sync(ds, dcrka->dcrka_ostype,
2373 	    dcrka->dcrka_nvl, tx);
2374 	if (dcrka->dcrka_do_key)
2375 		dsl_crypto_recv_raw_key_sync(ds, dcrka->dcrka_nvl, tx);
2376 	dsl_dataset_rele(ds, FTAG);
2377 }
2378 
2379 /*
2380  * This function is used to sync an nvlist representing a DSL Crypto Key and
2381  * the associated encryption parameters. The key will be written exactly as is
2382  * without wrapping it.
2383  */
2384 int
2385 dsl_crypto_recv_raw(const char *poolname, uint64_t dsobj, uint64_t fromobj,
2386     dmu_objset_type_t ostype, nvlist_t *nvl, boolean_t do_key)
2387 {
2388 	dsl_crypto_recv_key_arg_t dcrka;
2389 
2390 	dcrka.dcrka_dsobj = dsobj;
2391 	dcrka.dcrka_fromobj = fromobj;
2392 	dcrka.dcrka_ostype = ostype;
2393 	dcrka.dcrka_nvl = nvl;
2394 	dcrka.dcrka_do_key = do_key;
2395 
2396 	return (dsl_sync_task(poolname, dsl_crypto_recv_key_check,
2397 	    dsl_crypto_recv_key_sync, &dcrka, 1, ZFS_SPACE_CHECK_NORMAL));
2398 }
2399 
2400 int
2401 dsl_crypto_populate_key_nvlist(dsl_dataset_t *ds, uint64_t from_ivset_guid,
2402     nvlist_t **nvl_out)
2403 {
2404 	int ret;
2405 	objset_t *os;
2406 	dnode_t *mdn;
2407 	uint64_t rddobj;
2408 	nvlist_t *nvl = NULL;
2409 	uint64_t dckobj = ds->ds_dir->dd_crypto_obj;
2410 	dsl_dir_t *rdd = NULL;
2411 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2412 	objset_t *mos = dp->dp_meta_objset;
2413 	uint64_t crypt = 0, key_guid = 0, format = 0;
2414 	uint64_t iters = 0, salt = 0, version = 0;
2415 	uint64_t to_ivset_guid = 0;
2416 	uint8_t raw_keydata[MASTER_KEY_MAX_LEN];
2417 	uint8_t raw_hmac_keydata[SHA512_HMAC_KEYLEN];
2418 	uint8_t iv[WRAPPING_IV_LEN];
2419 	uint8_t mac[WRAPPING_MAC_LEN];
2420 
2421 	ASSERT(dckobj != 0);
2422 
2423 	VERIFY0(dmu_objset_from_ds(ds, &os));
2424 	mdn = DMU_META_DNODE(os);
2425 
2426 	ret = nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP);
2427 	if (ret != 0)
2428 		goto error;
2429 
2430 	/* lookup values from the DSL Crypto Key */
2431 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_CRYPTO_SUITE, 8, 1,
2432 	    &crypt);
2433 	if (ret != 0)
2434 		goto error;
2435 
2436 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_GUID, 8, 1, &key_guid);
2437 	if (ret != 0)
2438 		goto error;
2439 
2440 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_MASTER_KEY, 1,
2441 	    MASTER_KEY_MAX_LEN, raw_keydata);
2442 	if (ret != 0)
2443 		goto error;
2444 
2445 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_HMAC_KEY, 1,
2446 	    SHA512_HMAC_KEYLEN, raw_hmac_keydata);
2447 	if (ret != 0)
2448 		goto error;
2449 
2450 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_IV, 1, WRAPPING_IV_LEN,
2451 	    iv);
2452 	if (ret != 0)
2453 		goto error;
2454 
2455 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_MAC, 1, WRAPPING_MAC_LEN,
2456 	    mac);
2457 	if (ret != 0)
2458 		goto error;
2459 
2460 	/* see zfs_disable_ivset_guid_check tunable for errata info */
2461 	ret = zap_lookup(mos, ds->ds_object, DS_FIELD_IVSET_GUID, 8, 1,
2462 	    &to_ivset_guid);
2463 	if (ret != 0)
2464 		ASSERT3U(dp->dp_spa->spa_errata, !=, 0);
2465 
2466 	/*
2467 	 * We don't support raw sends of legacy on-disk formats. See the
2468 	 * comment in dsl_crypto_recv_key_check() for details.
2469 	 */
2470 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_VERSION, 8, 1, &version);
2471 	if (ret != 0 || version != ZIO_CRYPT_KEY_CURRENT_VERSION) {
2472 		dp->dp_spa->spa_errata = ZPOOL_ERRATA_ZOL_6845_ENCRYPTION;
2473 		ret = SET_ERROR(ENOTSUP);
2474 		goto error;
2475 	}
2476 
2477 	/*
2478 	 * Lookup wrapping key properties. An early version of the code did
2479 	 * not correctly add these values to the wrapping key or the DSL
2480 	 * Crypto Key on disk for non encryption roots, so to be safe we
2481 	 * always take the slightly circuitous route of looking it up from
2482 	 * the encryption root's key.
2483 	 */
2484 	ret = dsl_dir_get_encryption_root_ddobj(ds->ds_dir, &rddobj);
2485 	if (ret != 0)
2486 		goto error;
2487 
2488 	dsl_pool_config_enter(dp, FTAG);
2489 
2490 	ret = dsl_dir_hold_obj(dp, rddobj, NULL, FTAG, &rdd);
2491 	if (ret != 0)
2492 		goto error_unlock;
2493 
2494 	ret = zap_lookup(dp->dp_meta_objset, rdd->dd_crypto_obj,
2495 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), 8, 1, &format);
2496 	if (ret != 0)
2497 		goto error_unlock;
2498 
2499 	if (format == ZFS_KEYFORMAT_PASSPHRASE) {
2500 		ret = zap_lookup(dp->dp_meta_objset, rdd->dd_crypto_obj,
2501 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 8, 1, &iters);
2502 		if (ret != 0)
2503 			goto error_unlock;
2504 
2505 		ret = zap_lookup(dp->dp_meta_objset, rdd->dd_crypto_obj,
2506 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 8, 1, &salt);
2507 		if (ret != 0)
2508 			goto error_unlock;
2509 	}
2510 
2511 	dsl_dir_rele(rdd, FTAG);
2512 	dsl_pool_config_exit(dp, FTAG);
2513 
2514 	fnvlist_add_uint64(nvl, DSL_CRYPTO_KEY_CRYPTO_SUITE, crypt);
2515 	fnvlist_add_uint64(nvl, DSL_CRYPTO_KEY_GUID, key_guid);
2516 	fnvlist_add_uint64(nvl, DSL_CRYPTO_KEY_VERSION, version);
2517 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_MASTER_KEY,
2518 	    raw_keydata, MASTER_KEY_MAX_LEN));
2519 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_HMAC_KEY,
2520 	    raw_hmac_keydata, SHA512_HMAC_KEYLEN));
2521 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_IV, iv,
2522 	    WRAPPING_IV_LEN));
2523 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_MAC, mac,
2524 	    WRAPPING_MAC_LEN));
2525 	VERIFY0(nvlist_add_uint8_array(nvl, "portable_mac",
2526 	    os->os_phys->os_portable_mac, ZIO_OBJSET_MAC_LEN));
2527 	fnvlist_add_uint64(nvl, zfs_prop_to_name(ZFS_PROP_KEYFORMAT), format);
2528 	fnvlist_add_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), iters);
2529 	fnvlist_add_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt);
2530 	fnvlist_add_uint64(nvl, "mdn_checksum", mdn->dn_checksum);
2531 	fnvlist_add_uint64(nvl, "mdn_compress", mdn->dn_compress);
2532 	fnvlist_add_uint64(nvl, "mdn_nlevels", mdn->dn_nlevels);
2533 	fnvlist_add_uint64(nvl, "mdn_blksz", mdn->dn_datablksz);
2534 	fnvlist_add_uint64(nvl, "mdn_indblkshift", mdn->dn_indblkshift);
2535 	fnvlist_add_uint64(nvl, "mdn_nblkptr", mdn->dn_nblkptr);
2536 	fnvlist_add_uint64(nvl, "mdn_maxblkid", mdn->dn_maxblkid);
2537 	fnvlist_add_uint64(nvl, "to_ivset_guid", to_ivset_guid);
2538 	fnvlist_add_uint64(nvl, "from_ivset_guid", from_ivset_guid);
2539 
2540 	*nvl_out = nvl;
2541 	return (0);
2542 
2543 error_unlock:
2544 	dsl_pool_config_exit(dp, FTAG);
2545 error:
2546 	if (rdd != NULL)
2547 		dsl_dir_rele(rdd, FTAG);
2548 	nvlist_free(nvl);
2549 
2550 	*nvl_out = NULL;
2551 	return (ret);
2552 }
2553 
2554 uint64_t
2555 dsl_crypto_key_create_sync(uint64_t crypt, dsl_wrapping_key_t *wkey,
2556     dmu_tx_t *tx)
2557 {
2558 	dsl_crypto_key_t dck;
2559 	uint64_t version = ZIO_CRYPT_KEY_CURRENT_VERSION;
2560 	uint64_t one = 1ULL;
2561 
2562 	ASSERT(dmu_tx_is_syncing(tx));
2563 	ASSERT3U(crypt, <, ZIO_CRYPT_FUNCTIONS);
2564 	ASSERT3U(crypt, >, ZIO_CRYPT_OFF);
2565 
2566 	/* create the DSL Crypto Key ZAP object */
2567 	dck.dck_obj = zap_create(tx->tx_pool->dp_meta_objset,
2568 	    DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
2569 
2570 	/* fill in the key (on the stack) and sync it to disk */
2571 	dck.dck_wkey = wkey;
2572 	VERIFY0(zio_crypt_key_init(crypt, &dck.dck_key));
2573 
2574 	dsl_crypto_key_sync(&dck, tx);
2575 	VERIFY0(zap_update(tx->tx_pool->dp_meta_objset, dck.dck_obj,
2576 	    DSL_CRYPTO_KEY_REFCOUNT, sizeof (uint64_t), 1, &one, tx));
2577 	VERIFY0(zap_update(tx->tx_pool->dp_meta_objset, dck.dck_obj,
2578 	    DSL_CRYPTO_KEY_VERSION, sizeof (uint64_t), 1, &version, tx));
2579 
2580 	zio_crypt_key_destroy(&dck.dck_key);
2581 	bzero(&dck.dck_key, sizeof (zio_crypt_key_t));
2582 
2583 	return (dck.dck_obj);
2584 }
2585 
2586 uint64_t
2587 dsl_crypto_key_clone_sync(dsl_dir_t *origindd, dmu_tx_t *tx)
2588 {
2589 	objset_t *mos = tx->tx_pool->dp_meta_objset;
2590 
2591 	ASSERT(dmu_tx_is_syncing(tx));
2592 
2593 	VERIFY0(zap_increment(mos, origindd->dd_crypto_obj,
2594 	    DSL_CRYPTO_KEY_REFCOUNT, 1, tx));
2595 
2596 	return (origindd->dd_crypto_obj);
2597 }
2598 
2599 void
2600 dsl_crypto_key_destroy_sync(uint64_t dckobj, dmu_tx_t *tx)
2601 {
2602 	objset_t *mos = tx->tx_pool->dp_meta_objset;
2603 	uint64_t refcnt;
2604 
2605 	/* Decrement the refcount, destroy if this is the last reference */
2606 	VERIFY0(zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_REFCOUNT,
2607 	    sizeof (uint64_t), 1, &refcnt));
2608 
2609 	if (refcnt != 1) {
2610 		VERIFY0(zap_increment(mos, dckobj, DSL_CRYPTO_KEY_REFCOUNT,
2611 		    -1, tx));
2612 	} else {
2613 		VERIFY0(zap_destroy(mos, dckobj, tx));
2614 	}
2615 }
2616 
2617 void
2618 dsl_dataset_crypt_stats(dsl_dataset_t *ds, nvlist_t *nv)
2619 {
2620 	uint64_t intval;
2621 	dsl_dir_t *dd = ds->ds_dir;
2622 	dsl_dir_t *enc_root;
2623 	char buf[ZFS_MAX_DATASET_NAME_LEN];
2624 
2625 	if (dd->dd_crypto_obj == 0)
2626 		return;
2627 
2628 	intval = dsl_dataset_get_keystatus(dd);
2629 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_KEYSTATUS, intval);
2630 
2631 	if (dsl_dir_get_crypt(dd, &intval) == 0)
2632 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_ENCRYPTION, intval);
2633 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2634 	    DSL_CRYPTO_KEY_GUID, 8, 1, &intval) == 0) {
2635 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_KEY_GUID, intval);
2636 	}
2637 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2638 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), 8, 1, &intval) == 0) {
2639 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_KEYFORMAT, intval);
2640 	}
2641 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2642 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 8, 1, &intval) == 0) {
2643 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_PBKDF2_SALT, intval);
2644 	}
2645 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2646 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 8, 1, &intval) == 0) {
2647 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_PBKDF2_ITERS, intval);
2648 	}
2649 	if (zap_lookup(dd->dd_pool->dp_meta_objset, ds->ds_object,
2650 	    DS_FIELD_IVSET_GUID, 8, 1, &intval) == 0) {
2651 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_IVSET_GUID, intval);
2652 	}
2653 
2654 	if (dsl_dir_get_encryption_root_ddobj(dd, &intval) == 0) {
2655 		VERIFY0(dsl_dir_hold_obj(dd->dd_pool, intval, NULL, FTAG,
2656 		    &enc_root));
2657 		dsl_dir_name(enc_root, buf);
2658 		dsl_dir_rele(enc_root, FTAG);
2659 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ENCRYPTION_ROOT, buf);
2660 	}
2661 }
2662 
2663 int
2664 spa_crypt_get_salt(spa_t *spa, uint64_t dsobj, uint8_t *salt)
2665 {
2666 	int ret;
2667 	dsl_crypto_key_t *dck = NULL;
2668 
2669 	/* look up the key from the spa's keystore */
2670 	ret = spa_keystore_lookup_key(spa, dsobj, FTAG, &dck);
2671 	if (ret != 0)
2672 		goto error;
2673 
2674 	ret = zio_crypt_key_get_salt(&dck->dck_key, salt);
2675 	if (ret != 0)
2676 		goto error;
2677 
2678 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2679 	return (0);
2680 
2681 error:
2682 	if (dck != NULL)
2683 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
2684 	return (ret);
2685 }
2686 
2687 /*
2688  * Objset blocks are a special case for MAC generation. These blocks have 2
2689  * 256-bit MACs which are embedded within the block itself, rather than a
2690  * single 128 bit MAC. As a result, this function handles encoding and decoding
2691  * the MACs on its own, unlike other functions in this file.
2692  */
2693 int
2694 spa_do_crypt_objset_mac_abd(boolean_t generate, spa_t *spa, uint64_t dsobj,
2695     abd_t *abd, uint_t datalen, boolean_t byteswap)
2696 {
2697 	int ret;
2698 	dsl_crypto_key_t *dck = NULL;
2699 	void *buf = abd_borrow_buf_copy(abd, datalen);
2700 	objset_phys_t *osp = buf;
2701 	uint8_t portable_mac[ZIO_OBJSET_MAC_LEN];
2702 	uint8_t local_mac[ZIO_OBJSET_MAC_LEN];
2703 
2704 	/* look up the key from the spa's keystore */
2705 	ret = spa_keystore_lookup_key(spa, dsobj, FTAG, &dck);
2706 	if (ret != 0)
2707 		goto error;
2708 
2709 	/* calculate both HMACs */
2710 	ret = zio_crypt_do_objset_hmacs(&dck->dck_key, buf, datalen,
2711 	    byteswap, portable_mac, local_mac);
2712 	if (ret != 0)
2713 		goto error;
2714 
2715 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2716 
2717 	/* if we are generating encode the HMACs in the objset_phys_t */
2718 	if (generate) {
2719 		bcopy(portable_mac, osp->os_portable_mac, ZIO_OBJSET_MAC_LEN);
2720 		bcopy(local_mac, osp->os_local_mac, ZIO_OBJSET_MAC_LEN);
2721 		abd_return_buf_copy(abd, buf, datalen);
2722 		return (0);
2723 	}
2724 
2725 	if (bcmp(portable_mac, osp->os_portable_mac, ZIO_OBJSET_MAC_LEN) != 0 ||
2726 	    bcmp(local_mac, osp->os_local_mac, ZIO_OBJSET_MAC_LEN) != 0) {
2727 		abd_return_buf(abd, buf, datalen);
2728 		return (SET_ERROR(ECKSUM));
2729 	}
2730 
2731 	abd_return_buf(abd, buf, datalen);
2732 
2733 	return (0);
2734 
2735 error:
2736 	if (dck != NULL)
2737 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
2738 	abd_return_buf(abd, buf, datalen);
2739 	return (ret);
2740 }
2741 
2742 int
2743 spa_do_crypt_mac_abd(boolean_t generate, spa_t *spa, uint64_t dsobj, abd_t *abd,
2744     uint_t datalen, uint8_t *mac)
2745 {
2746 	int ret;
2747 	dsl_crypto_key_t *dck = NULL;
2748 	uint8_t *buf = abd_borrow_buf_copy(abd, datalen);
2749 	uint8_t digestbuf[ZIO_DATA_MAC_LEN];
2750 
2751 	/* look up the key from the spa's keystore */
2752 	ret = spa_keystore_lookup_key(spa, dsobj, FTAG, &dck);
2753 	if (ret != 0)
2754 		goto error;
2755 
2756 	/* perform the hmac */
2757 	ret = zio_crypt_do_hmac(&dck->dck_key, buf, datalen,
2758 	    digestbuf, ZIO_DATA_MAC_LEN);
2759 	if (ret != 0)
2760 		goto error;
2761 
2762 	abd_return_buf(abd, buf, datalen);
2763 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2764 
2765 	/*
2766 	 * Truncate and fill in mac buffer if we were asked to generate a MAC.
2767 	 * Otherwise verify that the MAC matched what we expected.
2768 	 */
2769 	if (generate) {
2770 		bcopy(digestbuf, mac, ZIO_DATA_MAC_LEN);
2771 		return (0);
2772 	}
2773 
2774 	if (bcmp(digestbuf, mac, ZIO_DATA_MAC_LEN) != 0)
2775 		return (SET_ERROR(ECKSUM));
2776 
2777 	return (0);
2778 
2779 error:
2780 	if (dck != NULL)
2781 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
2782 	abd_return_buf(abd, buf, datalen);
2783 	return (ret);
2784 }
2785 
2786 /*
2787  * This function serves as a multiplexer for encryption and decryption of
2788  * all blocks (except the L2ARC). For encryption, it will populate the IV,
2789  * salt, MAC, and cabd (the ciphertext). On decryption it will simply use
2790  * these fields to populate pabd (the plaintext).
2791  */
2792 /* ARGSUSED */
2793 int
2794 spa_do_crypt_abd(boolean_t encrypt, spa_t *spa, const zbookmark_phys_t *zb,
2795     dmu_object_type_t ot, boolean_t dedup, boolean_t bswap, uint8_t *salt,
2796     uint8_t *iv, uint8_t *mac, uint_t datalen, abd_t *pabd, abd_t *cabd,
2797     boolean_t *no_crypt)
2798 {
2799 	int ret;
2800 	dsl_crypto_key_t *dck = NULL;
2801 	uint8_t *plainbuf = NULL, *cipherbuf = NULL;
2802 
2803 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_ENCRYPTION));
2804 
2805 	/* look up the key from the spa's keystore */
2806 	ret = spa_keystore_lookup_key(spa, zb->zb_objset, FTAG, &dck);
2807 	if (ret != 0) {
2808 		ret = SET_ERROR(EACCES);
2809 		return (ret);
2810 	}
2811 
2812 	if (encrypt) {
2813 		plainbuf = abd_borrow_buf_copy(pabd, datalen);
2814 		cipherbuf = abd_borrow_buf(cabd, datalen);
2815 	} else {
2816 		plainbuf = abd_borrow_buf(pabd, datalen);
2817 		cipherbuf = abd_borrow_buf_copy(cabd, datalen);
2818 	}
2819 
2820 	/*
2821 	 * Both encryption and decryption functions need a salt for key
2822 	 * generation and an IV. When encrypting a non-dedup block, we
2823 	 * generate the salt and IV randomly to be stored by the caller. Dedup
2824 	 * blocks perform a (more expensive) HMAC of the plaintext to obtain
2825 	 * the salt and the IV. ZIL blocks have their salt and IV generated
2826 	 * at allocation time in zio_alloc_zil(). On decryption, we simply use
2827 	 * the provided values.
2828 	 */
2829 	if (encrypt && ot != DMU_OT_INTENT_LOG && !dedup) {
2830 		ret = zio_crypt_key_get_salt(&dck->dck_key, salt);
2831 		if (ret != 0)
2832 			goto error;
2833 
2834 		ret = zio_crypt_generate_iv(iv);
2835 		if (ret != 0)
2836 			goto error;
2837 	} else if (encrypt && dedup) {
2838 		ret = zio_crypt_generate_iv_salt_dedup(&dck->dck_key,
2839 		    plainbuf, datalen, iv, salt);
2840 		if (ret != 0)
2841 			goto error;
2842 	}
2843 
2844 	/* call lower level function to perform encryption / decryption */
2845 	ret = zio_do_crypt_data(encrypt, &dck->dck_key, ot, bswap, salt, iv,
2846 	    mac, datalen, plainbuf, cipherbuf, no_crypt);
2847 
2848 	/*
2849 	 * Handle injected decryption faults. Unfortunately, we cannot inject
2850 	 * faults for dnode blocks because we might trigger the panic in
2851 	 * dbuf_prepare_encrypted_dnode_leaf(), which exists because syncing
2852 	 * context is not prepared to handle malicious decryption failures.
2853 	 */
2854 	if (zio_injection_enabled && !encrypt && ot != DMU_OT_DNODE && ret == 0)
2855 		ret = zio_handle_decrypt_injection(spa, zb, ot, ECKSUM);
2856 	if (ret != 0)
2857 		goto error;
2858 
2859 	if (encrypt) {
2860 		abd_return_buf(pabd, plainbuf, datalen);
2861 		abd_return_buf_copy(cabd, cipherbuf, datalen);
2862 	} else {
2863 		abd_return_buf_copy(pabd, plainbuf, datalen);
2864 		abd_return_buf(cabd, cipherbuf, datalen);
2865 	}
2866 
2867 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2868 
2869 	return (0);
2870 
2871 error:
2872 	if (encrypt) {
2873 		/* zero out any state we might have changed while encrypting */
2874 		bzero(salt, ZIO_DATA_SALT_LEN);
2875 		bzero(iv, ZIO_DATA_IV_LEN);
2876 		bzero(mac, ZIO_DATA_MAC_LEN);
2877 		abd_return_buf(pabd, plainbuf, datalen);
2878 		abd_return_buf_copy(cabd, cipherbuf, datalen);
2879 	} else {
2880 		abd_return_buf_copy(pabd, plainbuf, datalen);
2881 		abd_return_buf(cabd, cipherbuf, datalen);
2882 	}
2883 
2884 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2885 
2886 	return (ret);
2887 }
2888