xref: /illumos-gate/usr/src/uts/common/fs/zfs/dsl_crypt.c (revision d8109ce4330e1b8ad6c29f9fccacec969066bb9d)
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 deault 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 	kmem_free(km, sizeof (dsl_key_mapping_t));
992 }
993 
994 int
995 spa_keystore_create_mapping(spa_t *spa, dsl_dataset_t *ds, void *tag,
996     dsl_key_mapping_t **km_out)
997 {
998 	int ret;
999 	avl_index_t where;
1000 	dsl_key_mapping_t *km, *found_km;
1001 	boolean_t should_free = B_FALSE;
1002 
1003 	/* Allocate and initialize the mapping */
1004 	km = kmem_zalloc(sizeof (dsl_key_mapping_t), KM_SLEEP);
1005 	zfs_refcount_create(&km->km_refcnt);
1006 
1007 	ret = spa_keystore_dsl_key_hold_dd(spa, ds->ds_dir, km, &km->km_key);
1008 	if (ret != 0) {
1009 		zfs_refcount_destroy(&km->km_refcnt);
1010 		kmem_free(km, sizeof (dsl_key_mapping_t));
1011 
1012 		if (km_out != NULL)
1013 			*km_out = NULL;
1014 		return (ret);
1015 	}
1016 
1017 	km->km_dsobj = ds->ds_object;
1018 
1019 	rw_enter(&spa->spa_keystore.sk_km_lock, RW_WRITER);
1020 
1021 	/*
1022 	 * If a mapping already exists, simply increment its refcount and
1023 	 * cleanup the one we made. We want to allocate / free outside of
1024 	 * the lock because this lock is also used by the zio layer to lookup
1025 	 * key mappings. Otherwise, use the one we created. Normally, there will
1026 	 * only be one active reference at a time (the objset owner), but there
1027 	 * are times when there could be multiple async users.
1028 	 */
1029 	found_km = avl_find(&spa->spa_keystore.sk_key_mappings, km, &where);
1030 	if (found_km != NULL) {
1031 		should_free = B_TRUE;
1032 		(void) zfs_refcount_add(&found_km->km_refcnt, tag);
1033 		if (km_out != NULL)
1034 			*km_out = found_km;
1035 	} else {
1036 		(void) zfs_refcount_add(&km->km_refcnt, tag);
1037 		avl_insert(&spa->spa_keystore.sk_key_mappings, km, where);
1038 		if (km_out != NULL)
1039 			*km_out = km;
1040 	}
1041 
1042 	rw_exit(&spa->spa_keystore.sk_km_lock);
1043 
1044 	if (should_free) {
1045 		spa_keystore_dsl_key_rele(spa, km->km_key, km);
1046 		zfs_refcount_destroy(&km->km_refcnt);
1047 		kmem_free(km, sizeof (dsl_key_mapping_t));
1048 	}
1049 
1050 	return (0);
1051 }
1052 
1053 int
1054 spa_keystore_remove_mapping(spa_t *spa, uint64_t dsobj, void *tag)
1055 {
1056 	int ret;
1057 	dsl_key_mapping_t search_km;
1058 	dsl_key_mapping_t *found_km;
1059 
1060 	/* init the search key mapping */
1061 	search_km.km_dsobj = dsobj;
1062 
1063 	rw_enter(&spa->spa_keystore.sk_km_lock, RW_READER);
1064 
1065 	/* find the matching mapping */
1066 	found_km = avl_find(&spa->spa_keystore.sk_key_mappings,
1067 	    &search_km, NULL);
1068 	if (found_km == NULL) {
1069 		ret = SET_ERROR(ENOENT);
1070 		goto error_unlock;
1071 	}
1072 
1073 	rw_exit(&spa->spa_keystore.sk_km_lock);
1074 
1075 	key_mapping_rele(spa, found_km, tag);
1076 
1077 	return (0);
1078 
1079 error_unlock:
1080 	rw_exit(&spa->spa_keystore.sk_km_lock);
1081 	return (ret);
1082 }
1083 
1084 /*
1085  * This function is primarily used by the zio and arc layer to lookup
1086  * DSL Crypto Keys for encryption. Callers must release the key with
1087  * spa_keystore_dsl_key_rele(). The function may also be called with
1088  * dck_out == NULL and tag == NULL to simply check that a key exists
1089  * without getting a reference to it.
1090  */
1091 int
1092 spa_keystore_lookup_key(spa_t *spa, uint64_t dsobj, void *tag,
1093     dsl_crypto_key_t **dck_out)
1094 {
1095 	int ret;
1096 	dsl_key_mapping_t search_km;
1097 	dsl_key_mapping_t *found_km;
1098 
1099 	ASSERT((tag != NULL && dck_out != NULL) ||
1100 	    (tag == NULL && dck_out == NULL));
1101 
1102 	/* init the search key mapping */
1103 	search_km.km_dsobj = dsobj;
1104 
1105 	rw_enter(&spa->spa_keystore.sk_km_lock, RW_READER);
1106 
1107 	/* remove the mapping from the tree */
1108 	found_km = avl_find(&spa->spa_keystore.sk_key_mappings, &search_km,
1109 	    NULL);
1110 	if (found_km == NULL) {
1111 		ret = SET_ERROR(ENOENT);
1112 		goto error_unlock;
1113 	}
1114 
1115 	if (found_km && tag)
1116 		(void) zfs_refcount_add(&found_km->km_key->dck_holds, tag);
1117 
1118 	rw_exit(&spa->spa_keystore.sk_km_lock);
1119 
1120 	if (dck_out != NULL)
1121 		*dck_out = found_km->km_key;
1122 	return (0);
1123 
1124 error_unlock:
1125 	rw_exit(&spa->spa_keystore.sk_km_lock);
1126 
1127 	if (dck_out != NULL)
1128 		*dck_out = NULL;
1129 	return (ret);
1130 }
1131 
1132 static int
1133 dmu_objset_check_wkey_loaded(dsl_dir_t *dd)
1134 {
1135 	int ret;
1136 	dsl_wrapping_key_t *wkey = NULL;
1137 
1138 	ret = spa_keystore_wkey_hold_dd(dd->dd_pool->dp_spa, dd, FTAG,
1139 	    &wkey);
1140 	if (ret != 0)
1141 		return (SET_ERROR(EACCES));
1142 
1143 	dsl_wrapping_key_rele(wkey, FTAG);
1144 
1145 	return (0);
1146 }
1147 
1148 static zfs_keystatus_t
1149 dsl_dataset_get_keystatus(dsl_dir_t *dd)
1150 {
1151 	/* check if this dd has a has a dsl key */
1152 	if (dd->dd_crypto_obj == 0)
1153 		return (ZFS_KEYSTATUS_NONE);
1154 
1155 	return (dmu_objset_check_wkey_loaded(dd) == 0 ?
1156 	    ZFS_KEYSTATUS_AVAILABLE : ZFS_KEYSTATUS_UNAVAILABLE);
1157 }
1158 
1159 static int
1160 dsl_dir_get_crypt(dsl_dir_t *dd, uint64_t *crypt)
1161 {
1162 	if (dd->dd_crypto_obj == 0) {
1163 		*crypt = ZIO_CRYPT_OFF;
1164 		return (0);
1165 	}
1166 
1167 	return (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
1168 	    DSL_CRYPTO_KEY_CRYPTO_SUITE, 8, 1, crypt));
1169 }
1170 
1171 static void
1172 dsl_crypto_key_sync_impl(objset_t *mos, uint64_t dckobj, uint64_t crypt,
1173     uint64_t root_ddobj, uint64_t guid, uint8_t *iv, uint8_t *mac,
1174     uint8_t *keydata, uint8_t *hmac_keydata, uint64_t keyformat,
1175     uint64_t salt, uint64_t iters, dmu_tx_t *tx)
1176 {
1177 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_CRYPTO_SUITE, 8, 1,
1178 	    &crypt, tx));
1179 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_ROOT_DDOBJ, 8, 1,
1180 	    &root_ddobj, tx));
1181 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_GUID, 8, 1,
1182 	    &guid, tx));
1183 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_IV, 1, WRAPPING_IV_LEN,
1184 	    iv, tx));
1185 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_MAC, 1, WRAPPING_MAC_LEN,
1186 	    mac, tx));
1187 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_MASTER_KEY, 1,
1188 	    MASTER_KEY_MAX_LEN, keydata, tx));
1189 	VERIFY0(zap_update(mos, dckobj, DSL_CRYPTO_KEY_HMAC_KEY, 1,
1190 	    SHA512_HMAC_KEYLEN, hmac_keydata, tx));
1191 	VERIFY0(zap_update(mos, dckobj, zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
1192 	    8, 1, &keyformat, tx));
1193 	VERIFY0(zap_update(mos, dckobj, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT),
1194 	    8, 1, &salt, tx));
1195 	VERIFY0(zap_update(mos, dckobj, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS),
1196 	    8, 1, &iters, tx));
1197 }
1198 
1199 static void
1200 dsl_crypto_key_sync(dsl_crypto_key_t *dck, dmu_tx_t *tx)
1201 {
1202 	zio_crypt_key_t *key = &dck->dck_key;
1203 	dsl_wrapping_key_t *wkey = dck->dck_wkey;
1204 	uint8_t keydata[MASTER_KEY_MAX_LEN];
1205 	uint8_t hmac_keydata[SHA512_HMAC_KEYLEN];
1206 	uint8_t iv[WRAPPING_IV_LEN];
1207 	uint8_t mac[WRAPPING_MAC_LEN];
1208 
1209 	ASSERT(dmu_tx_is_syncing(tx));
1210 	ASSERT3U(key->zk_crypt, <, ZIO_CRYPT_FUNCTIONS);
1211 
1212 	/* encrypt and store the keys along with the IV and MAC */
1213 	VERIFY0(zio_crypt_key_wrap(&dck->dck_wkey->wk_key, key, iv, mac,
1214 	    keydata, hmac_keydata));
1215 
1216 	/* update the ZAP with the obtained values */
1217 	dsl_crypto_key_sync_impl(tx->tx_pool->dp_meta_objset, dck->dck_obj,
1218 	    key->zk_crypt, wkey->wk_ddobj, key->zk_guid, iv, mac, keydata,
1219 	    hmac_keydata, wkey->wk_keyformat, wkey->wk_salt, wkey->wk_iters,
1220 	    tx);
1221 }
1222 
1223 typedef struct spa_keystore_change_key_args {
1224 	const char *skcka_dsname;
1225 	dsl_crypto_params_t *skcka_cp;
1226 } spa_keystore_change_key_args_t;
1227 
1228 static int
1229 spa_keystore_change_key_check(void *arg, dmu_tx_t *tx)
1230 {
1231 	int ret;
1232 	dsl_dir_t *dd = NULL;
1233 	dsl_pool_t *dp = dmu_tx_pool(tx);
1234 	spa_keystore_change_key_args_t *skcka = arg;
1235 	dsl_crypto_params_t *dcp = skcka->skcka_cp;
1236 	uint64_t rddobj;
1237 
1238 	/* check for the encryption feature */
1239 	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION)) {
1240 		ret = SET_ERROR(ENOTSUP);
1241 		goto error;
1242 	}
1243 
1244 	/* check for valid key change command */
1245 	if (dcp->cp_cmd != DCP_CMD_NEW_KEY &&
1246 	    dcp->cp_cmd != DCP_CMD_INHERIT &&
1247 	    dcp->cp_cmd != DCP_CMD_FORCE_NEW_KEY &&
1248 	    dcp->cp_cmd != DCP_CMD_FORCE_INHERIT) {
1249 		ret = SET_ERROR(EINVAL);
1250 		goto error;
1251 	}
1252 
1253 	/* hold the dd */
1254 	ret = dsl_dir_hold(dp, skcka->skcka_dsname, FTAG, &dd, NULL);
1255 	if (ret != 0)
1256 		goto error;
1257 
1258 	/* verify that the dataset is encrypted */
1259 	if (dd->dd_crypto_obj == 0) {
1260 		ret = SET_ERROR(EINVAL);
1261 		goto error;
1262 	}
1263 
1264 	/* clones must always use their origin's key */
1265 	if (dsl_dir_is_clone(dd)) {
1266 		ret = SET_ERROR(EINVAL);
1267 		goto error;
1268 	}
1269 
1270 	/* lookup the ddobj we are inheriting the keylocation from */
1271 	ret = dsl_dir_get_encryption_root_ddobj(dd, &rddobj);
1272 	if (ret != 0)
1273 		goto error;
1274 
1275 	/* Handle inheritance */
1276 	if (dcp->cp_cmd == DCP_CMD_INHERIT ||
1277 	    dcp->cp_cmd == DCP_CMD_FORCE_INHERIT) {
1278 		/* no other encryption params should be given */
1279 		if (dcp->cp_crypt != ZIO_CRYPT_INHERIT ||
1280 		    dcp->cp_keylocation != NULL ||
1281 		    dcp->cp_wkey != NULL) {
1282 			ret = SET_ERROR(EINVAL);
1283 			goto error;
1284 		}
1285 
1286 		/* check that this is an encryption root */
1287 		if (dd->dd_object != rddobj) {
1288 			ret = SET_ERROR(EINVAL);
1289 			goto error;
1290 		}
1291 
1292 		/* check that the parent is encrypted */
1293 		if (dd->dd_parent->dd_crypto_obj == 0) {
1294 			ret = SET_ERROR(EINVAL);
1295 			goto error;
1296 		}
1297 
1298 		/* if we are rewrapping check that both keys are loaded */
1299 		if (dcp->cp_cmd == DCP_CMD_INHERIT) {
1300 			ret = dmu_objset_check_wkey_loaded(dd);
1301 			if (ret != 0)
1302 				goto error;
1303 
1304 			ret = dmu_objset_check_wkey_loaded(dd->dd_parent);
1305 			if (ret != 0)
1306 				goto error;
1307 		}
1308 
1309 		dsl_dir_rele(dd, FTAG);
1310 		return (0);
1311 	}
1312 
1313 	/* handle forcing an encryption root without rewrapping */
1314 	if (dcp->cp_cmd == DCP_CMD_FORCE_NEW_KEY) {
1315 		/* no other encryption params should be given */
1316 		if (dcp->cp_crypt != ZIO_CRYPT_INHERIT ||
1317 		    dcp->cp_keylocation != NULL ||
1318 		    dcp->cp_wkey != NULL) {
1319 			ret = SET_ERROR(EINVAL);
1320 			goto error;
1321 		}
1322 
1323 		/* check that this is not an encryption root */
1324 		if (dd->dd_object == rddobj) {
1325 			ret = SET_ERROR(EINVAL);
1326 			goto error;
1327 		}
1328 
1329 		dsl_dir_rele(dd, FTAG);
1330 		return (0);
1331 	}
1332 
1333 	/* crypt cannot be changed after creation */
1334 	if (dcp->cp_crypt != ZIO_CRYPT_INHERIT) {
1335 		ret = SET_ERROR(EINVAL);
1336 		goto error;
1337 	}
1338 
1339 	/* we are not inheritting our parent's wkey so we need one ourselves */
1340 	if (dcp->cp_wkey == NULL) {
1341 		ret = SET_ERROR(EINVAL);
1342 		goto error;
1343 	}
1344 
1345 	/* check for a valid keyformat for the new wrapping key */
1346 	if (dcp->cp_wkey->wk_keyformat >= ZFS_KEYFORMAT_FORMATS ||
1347 	    dcp->cp_wkey->wk_keyformat == ZFS_KEYFORMAT_NONE) {
1348 		ret = SET_ERROR(EINVAL);
1349 		goto error;
1350 	}
1351 
1352 	/*
1353 	 * If this dataset is not currently an encryption root we need a new
1354 	 * keylocation for this dataset's new wrapping key. Otherwise we can
1355 	 * just keep the one we already had.
1356 	 */
1357 	if (dd->dd_object != rddobj && dcp->cp_keylocation == NULL) {
1358 		ret = SET_ERROR(EINVAL);
1359 		goto error;
1360 	}
1361 
1362 	/* check that the keylocation is valid if it is not NULL */
1363 	if (dcp->cp_keylocation != NULL &&
1364 	    !zfs_prop_valid_keylocation(dcp->cp_keylocation, B_TRUE)) {
1365 		ret = SET_ERROR(EINVAL);
1366 		goto error;
1367 	}
1368 
1369 	/* passphrases require pbkdf2 salt and iters */
1370 	if (dcp->cp_wkey->wk_keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
1371 		if (dcp->cp_wkey->wk_salt == 0 ||
1372 		    dcp->cp_wkey->wk_iters < MIN_PBKDF2_ITERATIONS) {
1373 			ret = SET_ERROR(EINVAL);
1374 			goto error;
1375 		}
1376 	} else {
1377 		if (dcp->cp_wkey->wk_salt != 0 || dcp->cp_wkey->wk_iters != 0) {
1378 			ret = SET_ERROR(EINVAL);
1379 			goto error;
1380 		}
1381 	}
1382 
1383 	/* make sure the dd's wkey is loaded */
1384 	ret = dmu_objset_check_wkey_loaded(dd);
1385 	if (ret != 0)
1386 		goto error;
1387 
1388 	dsl_dir_rele(dd, FTAG);
1389 
1390 	return (0);
1391 
1392 error:
1393 	if (dd != NULL)
1394 		dsl_dir_rele(dd, FTAG);
1395 
1396 	return (ret);
1397 }
1398 
1399 
1400 static void
1401 spa_keystore_change_key_sync_impl(uint64_t rddobj, uint64_t ddobj,
1402     uint64_t new_rddobj, dsl_wrapping_key_t *wkey, dmu_tx_t *tx)
1403 {
1404 	zap_cursor_t *zc;
1405 	zap_attribute_t *za;
1406 	dsl_pool_t *dp = dmu_tx_pool(tx);
1407 	dsl_dir_t *dd = NULL;
1408 	dsl_crypto_key_t *dck = NULL;
1409 	uint64_t curr_rddobj;
1410 
1411 	ASSERT(RW_WRITE_HELD(&dp->dp_spa->spa_keystore.sk_wkeys_lock));
1412 
1413 	/* hold the dd */
1414 	VERIFY0(dsl_dir_hold_obj(dp, ddobj, NULL, FTAG, &dd));
1415 
1416 	/* ignore hidden dsl dirs */
1417 	if (dd->dd_myname[0] == '$' || dd->dd_myname[0] == '%') {
1418 		dsl_dir_rele(dd, FTAG);
1419 		return;
1420 	}
1421 
1422 	/*
1423 	 * Stop recursing if this dsl dir didn't inherit from the root
1424 	 * or if this dd is a clone.
1425 	 */
1426 	VERIFY0(dsl_dir_get_encryption_root_ddobj(dd, &curr_rddobj));
1427 	if (curr_rddobj != rddobj || dsl_dir_is_clone(dd)) {
1428 		dsl_dir_rele(dd, FTAG);
1429 		return;
1430 	}
1431 
1432 	/*
1433 	 * If we don't have a wrapping key just update the dck to reflect the
1434 	 * new encryption root. Otherwise rewrap the entire dck and re-sync it
1435 	 * to disk.
1436 	 */
1437 	if (wkey == NULL) {
1438 		VERIFY0(zap_update(dp->dp_meta_objset, dd->dd_crypto_obj,
1439 		    DSL_CRYPTO_KEY_ROOT_DDOBJ, 8, 1, &new_rddobj, tx));
1440 	} else {
1441 		VERIFY0(spa_keystore_dsl_key_hold_dd(dp->dp_spa, dd,
1442 		    FTAG, &dck));
1443 		dsl_wrapping_key_hold(wkey, dck);
1444 		dsl_wrapping_key_rele(dck->dck_wkey, dck);
1445 		dck->dck_wkey = wkey;
1446 		dsl_crypto_key_sync(dck, tx);
1447 		spa_keystore_dsl_key_rele(dp->dp_spa, dck, FTAG);
1448 	}
1449 
1450 	zc = kmem_alloc(sizeof (zap_cursor_t), KM_SLEEP);
1451 	za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
1452 
1453 	/* Recurse into all child dsl dirs. */
1454 	for (zap_cursor_init(zc, dp->dp_meta_objset,
1455 	    dsl_dir_phys(dd)->dd_child_dir_zapobj);
1456 	    zap_cursor_retrieve(zc, za) == 0;
1457 	    zap_cursor_advance(zc)) {
1458 		spa_keystore_change_key_sync_impl(rddobj,
1459 		    za->za_first_integer, new_rddobj, wkey, tx);
1460 	}
1461 	zap_cursor_fini(zc);
1462 
1463 	kmem_free(za, sizeof (zap_attribute_t));
1464 	kmem_free(zc, sizeof (zap_cursor_t));
1465 
1466 	dsl_dir_rele(dd, FTAG);
1467 }
1468 
1469 static void
1470 spa_keystore_change_key_sync(void *arg, dmu_tx_t *tx)
1471 {
1472 	dsl_dataset_t *ds;
1473 	avl_index_t where;
1474 	dsl_pool_t *dp = dmu_tx_pool(tx);
1475 	spa_t *spa = dp->dp_spa;
1476 	spa_keystore_change_key_args_t *skcka = arg;
1477 	dsl_crypto_params_t *dcp = skcka->skcka_cp;
1478 	dsl_wrapping_key_t *wkey = NULL, *found_wkey;
1479 	dsl_wrapping_key_t wkey_search;
1480 	char *keylocation = dcp->cp_keylocation;
1481 	uint64_t rddobj, new_rddobj;
1482 
1483 	/* create and initialize the wrapping key */
1484 	VERIFY0(dsl_dataset_hold(dp, skcka->skcka_dsname, FTAG, &ds));
1485 	ASSERT(!ds->ds_is_snapshot);
1486 
1487 	if (dcp->cp_cmd == DCP_CMD_NEW_KEY ||
1488 	    dcp->cp_cmd == DCP_CMD_FORCE_NEW_KEY) {
1489 		/*
1490 		 * We are changing to a new wkey. Set additional properties
1491 		 * which can be sent along with this ioctl. Note that this
1492 		 * command can set keylocation even if it can't normally be
1493 		 * set via 'zfs set' due to a non-local keylocation.
1494 		 */
1495 		if (dcp->cp_cmd == DCP_CMD_NEW_KEY) {
1496 			wkey = dcp->cp_wkey;
1497 			wkey->wk_ddobj = ds->ds_dir->dd_object;
1498 		} else {
1499 			keylocation = "prompt";
1500 		}
1501 
1502 		if (keylocation != NULL) {
1503 			dsl_prop_set_sync_impl(ds,
1504 			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1505 			    ZPROP_SRC_LOCAL, 1, strlen(keylocation) + 1,
1506 			    keylocation, tx);
1507 		}
1508 
1509 		VERIFY0(dsl_dir_get_encryption_root_ddobj(ds->ds_dir, &rddobj));
1510 		new_rddobj = ds->ds_dir->dd_object;
1511 	} else {
1512 		/*
1513 		 * We are inheriting the parent's wkey. Unset any local
1514 		 * keylocation and grab a reference to the wkey.
1515 		 */
1516 		if (dcp->cp_cmd == DCP_CMD_INHERIT) {
1517 			VERIFY0(spa_keystore_wkey_hold_dd(spa,
1518 			    ds->ds_dir->dd_parent, FTAG, &wkey));
1519 		}
1520 
1521 		dsl_prop_set_sync_impl(ds,
1522 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), ZPROP_SRC_NONE,
1523 		    0, 0, NULL, tx);
1524 
1525 		rddobj = ds->ds_dir->dd_object;
1526 		VERIFY0(dsl_dir_get_encryption_root_ddobj(ds->ds_dir->dd_parent,
1527 		    &new_rddobj));
1528 	}
1529 
1530 	if (wkey == NULL) {
1531 		ASSERT(dcp->cp_cmd == DCP_CMD_FORCE_INHERIT ||
1532 		    dcp->cp_cmd == DCP_CMD_FORCE_NEW_KEY);
1533 	}
1534 
1535 	rw_enter(&spa->spa_keystore.sk_wkeys_lock, RW_WRITER);
1536 
1537 	/* recurse through all children and rewrap their keys */
1538 	spa_keystore_change_key_sync_impl(rddobj, ds->ds_dir->dd_object,
1539 	    new_rddobj, wkey, tx);
1540 
1541 	/*
1542 	 * All references to the old wkey should be released now (if it
1543 	 * existed). Replace the wrapping key.
1544 	 */
1545 	wkey_search.wk_ddobj = ds->ds_dir->dd_object;
1546 	found_wkey = avl_find(&spa->spa_keystore.sk_wkeys, &wkey_search, NULL);
1547 	if (found_wkey != NULL) {
1548 		ASSERT0(zfs_refcount_count(&found_wkey->wk_refcnt));
1549 		avl_remove(&spa->spa_keystore.sk_wkeys, found_wkey);
1550 		dsl_wrapping_key_free(found_wkey);
1551 	}
1552 
1553 	if (dcp->cp_cmd == DCP_CMD_NEW_KEY) {
1554 		(void) avl_find(&spa->spa_keystore.sk_wkeys, wkey, &where);
1555 		avl_insert(&spa->spa_keystore.sk_wkeys, wkey, where);
1556 	} else if (wkey != NULL) {
1557 		dsl_wrapping_key_rele(wkey, FTAG);
1558 	}
1559 
1560 	rw_exit(&spa->spa_keystore.sk_wkeys_lock);
1561 
1562 	dsl_dataset_rele(ds, FTAG);
1563 }
1564 
1565 int
1566 spa_keystore_change_key(const char *dsname, dsl_crypto_params_t *dcp)
1567 {
1568 	spa_keystore_change_key_args_t skcka;
1569 
1570 	/* initialize the args struct */
1571 	skcka.skcka_dsname = dsname;
1572 	skcka.skcka_cp = dcp;
1573 
1574 	/*
1575 	 * Perform the actual work in syncing context. The blocks modified
1576 	 * here could be calculated but it would require holding the pool
1577 	 * lock and traversing all of the datasets that will have their keys
1578 	 * changed.
1579 	 */
1580 	return (dsl_sync_task(dsname, spa_keystore_change_key_check,
1581 	    spa_keystore_change_key_sync, &skcka, 15,
1582 	    ZFS_SPACE_CHECK_RESERVED));
1583 }
1584 
1585 int
1586 dsl_dir_rename_crypt_check(dsl_dir_t *dd, dsl_dir_t *newparent)
1587 {
1588 	int ret;
1589 	uint64_t curr_rddobj, parent_rddobj;
1590 
1591 	if (dd->dd_crypto_obj == 0)
1592 		return (0);
1593 
1594 	ret = dsl_dir_get_encryption_root_ddobj(dd, &curr_rddobj);
1595 	if (ret != 0)
1596 		goto error;
1597 
1598 	/*
1599 	 * if this is not an encryption root, we must make sure we are not
1600 	 * moving dd to a new encryption root
1601 	 */
1602 	if (dd->dd_object != curr_rddobj) {
1603 		ret = dsl_dir_get_encryption_root_ddobj(newparent,
1604 		    &parent_rddobj);
1605 		if (ret != 0)
1606 			goto error;
1607 
1608 		if (parent_rddobj != curr_rddobj) {
1609 			ret = SET_ERROR(EACCES);
1610 			goto error;
1611 		}
1612 	}
1613 
1614 	return (0);
1615 
1616 error:
1617 	return (ret);
1618 }
1619 
1620 /*
1621  * Check to make sure that a promote from targetdd to origindd will not require
1622  * any key rewraps.
1623  */
1624 int
1625 dsl_dataset_promote_crypt_check(dsl_dir_t *target, dsl_dir_t *origin)
1626 {
1627 	int ret;
1628 	uint64_t rddobj, op_rddobj, tp_rddobj;
1629 
1630 	/* If the dataset is not encrypted we don't need to check anything */
1631 	if (origin->dd_crypto_obj == 0)
1632 		return (0);
1633 
1634 	/*
1635 	 * If we are not changing the first origin snapshot in a chain
1636 	 * the encryption root won't change either.
1637 	 */
1638 	if (dsl_dir_is_clone(origin))
1639 		return (0);
1640 
1641 	/*
1642 	 * If the origin is the encryption root we will update
1643 	 * the DSL Crypto Key to point to the target instead.
1644 	 */
1645 	ret = dsl_dir_get_encryption_root_ddobj(origin, &rddobj);
1646 	if (ret != 0)
1647 		return (ret);
1648 
1649 	if (rddobj == origin->dd_object)
1650 		return (0);
1651 
1652 	/*
1653 	 * The origin is inheriting its encryption root from its parent.
1654 	 * Check that the parent of the target has the same encryption root.
1655 	 */
1656 	ret = dsl_dir_get_encryption_root_ddobj(origin->dd_parent, &op_rddobj);
1657 	if (ret != 0)
1658 		return (ret);
1659 
1660 	ret = dsl_dir_get_encryption_root_ddobj(target->dd_parent, &tp_rddobj);
1661 	if (ret != 0)
1662 		return (ret);
1663 
1664 	if (op_rddobj != tp_rddobj)
1665 		return (SET_ERROR(EACCES));
1666 
1667 	return (0);
1668 }
1669 
1670 void
1671 dsl_dataset_promote_crypt_sync(dsl_dir_t *target, dsl_dir_t *origin,
1672     dmu_tx_t *tx)
1673 {
1674 	uint64_t rddobj;
1675 	dsl_pool_t *dp = target->dd_pool;
1676 	dsl_dataset_t *targetds;
1677 	dsl_dataset_t *originds;
1678 	char *keylocation;
1679 
1680 	if (origin->dd_crypto_obj == 0)
1681 		return;
1682 	if (dsl_dir_is_clone(origin))
1683 		return;
1684 
1685 	VERIFY0(dsl_dir_get_encryption_root_ddobj(origin, &rddobj));
1686 
1687 	if (rddobj != origin->dd_object)
1688 		return;
1689 
1690 	/*
1691 	 * If the target is being promoted to the encryption root update the
1692 	 * DSL Crypto Key and keylocation to reflect that. We also need to
1693 	 * update the DSL Crypto Keys of all children inheriting their
1694 	 * encryption root to point to the new target. Otherwise, the check
1695 	 * function ensured that the encryption root will not change.
1696 	 */
1697 	keylocation = kmem_alloc(ZAP_MAXVALUELEN, KM_SLEEP);
1698 
1699 	VERIFY0(dsl_dataset_hold_obj(dp,
1700 	    dsl_dir_phys(target)->dd_head_dataset_obj, FTAG, &targetds));
1701 	VERIFY0(dsl_dataset_hold_obj(dp,
1702 	    dsl_dir_phys(origin)->dd_head_dataset_obj, FTAG, &originds));
1703 
1704 	VERIFY0(dsl_prop_get_dd(origin, zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1705 	    1, ZAP_MAXVALUELEN, keylocation, NULL, B_FALSE));
1706 	dsl_prop_set_sync_impl(targetds, zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1707 	    ZPROP_SRC_LOCAL, 1, strlen(keylocation) + 1, keylocation, tx);
1708 	dsl_prop_set_sync_impl(originds, zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1709 	    ZPROP_SRC_NONE, 0, 0, NULL, tx);
1710 
1711 	rw_enter(&dp->dp_spa->spa_keystore.sk_wkeys_lock, RW_WRITER);
1712 	spa_keystore_change_key_sync_impl(rddobj, origin->dd_object,
1713 	    target->dd_object, NULL, tx);
1714 	rw_exit(&dp->dp_spa->spa_keystore.sk_wkeys_lock);
1715 
1716 	dsl_dataset_rele(targetds, FTAG);
1717 	dsl_dataset_rele(originds, FTAG);
1718 	kmem_free(keylocation, ZAP_MAXVALUELEN);
1719 }
1720 
1721 int
1722 dmu_objset_create_crypt_check(dsl_dir_t *parentdd, dsl_crypto_params_t *dcp,
1723     boolean_t *will_encrypt)
1724 {
1725 	int ret;
1726 	uint64_t pcrypt, crypt;
1727 	dsl_crypto_params_t dummy_dcp = { 0 };
1728 
1729 	if (will_encrypt != NULL)
1730 		*will_encrypt = B_FALSE;
1731 
1732 	if (dcp == NULL)
1733 		dcp = &dummy_dcp;
1734 
1735 	if (dcp->cp_cmd != DCP_CMD_NONE)
1736 		return (SET_ERROR(EINVAL));
1737 
1738 	if (parentdd != NULL) {
1739 		ret = dsl_dir_get_crypt(parentdd, &pcrypt);
1740 		if (ret != 0)
1741 			return (ret);
1742 	} else {
1743 		pcrypt = ZIO_CRYPT_OFF;
1744 	}
1745 
1746 	crypt = (dcp->cp_crypt == ZIO_CRYPT_INHERIT) ? pcrypt : dcp->cp_crypt;
1747 
1748 	ASSERT3U(pcrypt, !=, ZIO_CRYPT_INHERIT);
1749 	ASSERT3U(crypt, !=, ZIO_CRYPT_INHERIT);
1750 
1751 	/* check for valid dcp with no encryption (inherited or local) */
1752 	if (crypt == ZIO_CRYPT_OFF) {
1753 		/* Must not specify encryption params */
1754 		if (dcp->cp_wkey != NULL ||
1755 		    (dcp->cp_keylocation != NULL &&
1756 		    strcmp(dcp->cp_keylocation, "none") != 0))
1757 			return (SET_ERROR(EINVAL));
1758 
1759 		return (0);
1760 	}
1761 
1762 	if (will_encrypt != NULL)
1763 		*will_encrypt = B_TRUE;
1764 
1765 	/*
1766 	 * We will now definitely be encrypting. Check the feature flag. When
1767 	 * creating the pool the caller will check this for us since we won't
1768 	 * technically have the feature activated yet.
1769 	 */
1770 	if (parentdd != NULL &&
1771 	    !spa_feature_is_enabled(parentdd->dd_pool->dp_spa,
1772 	    SPA_FEATURE_ENCRYPTION)) {
1773 		return (SET_ERROR(EOPNOTSUPP));
1774 	}
1775 
1776 	/* check for errata #4 (encryption enabled, bookmark_v2 disabled) */
1777 	if (parentdd != NULL &&
1778 	    !spa_feature_is_enabled(parentdd->dd_pool->dp_spa,
1779 	    SPA_FEATURE_BOOKMARK_V2)) {
1780 		return (SET_ERROR(EOPNOTSUPP));
1781 	}
1782 
1783 	/* handle inheritance */
1784 	if (dcp->cp_wkey == NULL) {
1785 		ASSERT3P(parentdd, !=, NULL);
1786 
1787 		/* key must be fully unspecified */
1788 		if (dcp->cp_keylocation != NULL)
1789 			return (SET_ERROR(EINVAL));
1790 
1791 		/* parent must have a key to inherit */
1792 		if (pcrypt == ZIO_CRYPT_OFF)
1793 			return (SET_ERROR(EINVAL));
1794 
1795 		/* check for parent key */
1796 		ret = dmu_objset_check_wkey_loaded(parentdd);
1797 		if (ret != 0)
1798 			return (ret);
1799 
1800 		return (0);
1801 	}
1802 
1803 	/* At this point we should have a fully specified key. Check location */
1804 	if (dcp->cp_keylocation == NULL ||
1805 	    !zfs_prop_valid_keylocation(dcp->cp_keylocation, B_TRUE))
1806 		return (SET_ERROR(EINVAL));
1807 
1808 	/* Must have fully specified keyformat */
1809 	switch (dcp->cp_wkey->wk_keyformat) {
1810 		case ZFS_KEYFORMAT_HEX:
1811 		case ZFS_KEYFORMAT_RAW:
1812 			/* requires no pbkdf2 iters and salt */
1813 			if (dcp->cp_wkey->wk_salt != 0 ||
1814 			    dcp->cp_wkey->wk_iters != 0)
1815 				return (SET_ERROR(EINVAL));
1816 			break;
1817 		case ZFS_KEYFORMAT_PASSPHRASE:
1818 			/* requires pbkdf2 iters and salt */
1819 			if (dcp->cp_wkey->wk_salt == 0 ||
1820 			    dcp->cp_wkey->wk_iters < MIN_PBKDF2_ITERATIONS)
1821 				return (SET_ERROR(EINVAL));
1822 			break;
1823 		case ZFS_KEYFORMAT_NONE:
1824 		default:
1825 			/* keyformat must be specified and valid */
1826 			return (SET_ERROR(EINVAL));
1827 	}
1828 
1829 	return (0);
1830 }
1831 
1832 void
1833 dsl_dataset_create_crypt_sync(uint64_t dsobj, dsl_dir_t *dd,
1834     dsl_dataset_t *origin, dsl_crypto_params_t *dcp, dmu_tx_t *tx)
1835 {
1836 	dsl_pool_t *dp = dd->dd_pool;
1837 	uint64_t crypt;
1838 	dsl_wrapping_key_t *wkey;
1839 
1840 	/* clones always use their origin's wrapping key */
1841 	if (dsl_dir_is_clone(dd)) {
1842 		ASSERT3P(dcp, ==, NULL);
1843 
1844 		/*
1845 		 * If this is an encrypted clone we just need to clone the
1846 		 * dck into dd. Zapify the dd so we can do that.
1847 		 */
1848 		if (origin->ds_dir->dd_crypto_obj != 0) {
1849 			dmu_buf_will_dirty(dd->dd_dbuf, tx);
1850 			dsl_dir_zapify(dd, tx);
1851 
1852 			dd->dd_crypto_obj =
1853 			    dsl_crypto_key_clone_sync(origin->ds_dir, tx);
1854 			VERIFY0(zap_add(dp->dp_meta_objset, dd->dd_object,
1855 			    DD_FIELD_CRYPTO_KEY_OBJ, sizeof (uint64_t), 1,
1856 			    &dd->dd_crypto_obj, tx));
1857 		}
1858 
1859 		return;
1860 	}
1861 
1862 	/*
1863 	 * A NULL dcp at this point indicates this is the origin dataset
1864 	 * which does not have an objset to encrypt. Raw receives will handle
1865 	 * encryption separately later. In both cases we can simply return.
1866 	 */
1867 	if (dcp == NULL || dcp->cp_cmd == DCP_CMD_RAW_RECV)
1868 		return;
1869 
1870 	crypt = dcp->cp_crypt;
1871 	wkey = dcp->cp_wkey;
1872 
1873 	/* figure out the effective crypt */
1874 	if (crypt == ZIO_CRYPT_INHERIT && dd->dd_parent != NULL)
1875 		VERIFY0(dsl_dir_get_crypt(dd->dd_parent, &crypt));
1876 
1877 	/* if we aren't doing encryption just return */
1878 	if (crypt == ZIO_CRYPT_OFF || crypt == ZIO_CRYPT_INHERIT)
1879 		return;
1880 
1881 	/* zapify the dd so that we can add the crypto key obj to it */
1882 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1883 	dsl_dir_zapify(dd, tx);
1884 
1885 	/* use the new key if given or inherit from the parent */
1886 	if (wkey == NULL) {
1887 		VERIFY0(spa_keystore_wkey_hold_dd(dp->dp_spa,
1888 		    dd->dd_parent, FTAG, &wkey));
1889 	} else {
1890 		wkey->wk_ddobj = dd->dd_object;
1891 	}
1892 
1893 	ASSERT3P(wkey, !=, NULL);
1894 
1895 	/* Create or clone the DSL crypto key and activate the feature */
1896 	dd->dd_crypto_obj = dsl_crypto_key_create_sync(crypt, wkey, tx);
1897 	VERIFY0(zap_add(dp->dp_meta_objset, dd->dd_object,
1898 	    DD_FIELD_CRYPTO_KEY_OBJ, sizeof (uint64_t), 1, &dd->dd_crypto_obj,
1899 	    tx));
1900 	dsl_dataset_activate_feature(dsobj, SPA_FEATURE_ENCRYPTION, tx);
1901 
1902 	/*
1903 	 * If we inherited the wrapping key we release our reference now.
1904 	 * Otherwise, this is a new key and we need to load it into the
1905 	 * keystore.
1906 	 */
1907 	if (dcp->cp_wkey == NULL) {
1908 		dsl_wrapping_key_rele(wkey, FTAG);
1909 	} else {
1910 		VERIFY0(spa_keystore_load_wkey_impl(dp->dp_spa, wkey));
1911 	}
1912 }
1913 
1914 typedef struct dsl_crypto_recv_key_arg {
1915 	uint64_t dcrka_dsobj;
1916 	uint64_t dcrka_fromobj;
1917 	dmu_objset_type_t dcrka_ostype;
1918 	nvlist_t *dcrka_nvl;
1919 	boolean_t dcrka_do_key;
1920 } dsl_crypto_recv_key_arg_t;
1921 
1922 static int
1923 dsl_crypto_recv_raw_objset_check(dsl_dataset_t *ds, dsl_dataset_t *fromds,
1924     dmu_objset_type_t ostype, nvlist_t *nvl, dmu_tx_t *tx)
1925 {
1926 	int ret;
1927 	objset_t *os;
1928 	dnode_t *mdn;
1929 	uint8_t *buf = NULL;
1930 	uint_t len;
1931 	uint64_t intval, nlevels, blksz, ibs;
1932 	uint64_t nblkptr, maxblkid;
1933 
1934 	if (ostype != DMU_OST_ZFS && ostype != DMU_OST_ZVOL)
1935 		return (SET_ERROR(EINVAL));
1936 
1937 	/* raw receives also need info about the structure of the metadnode */
1938 	ret = nvlist_lookup_uint64(nvl, "mdn_compress", &intval);
1939 	if (ret != 0 || intval >= ZIO_COMPRESS_LEGACY_FUNCTIONS)
1940 		return (SET_ERROR(EINVAL));
1941 
1942 	ret = nvlist_lookup_uint64(nvl, "mdn_checksum", &intval);
1943 	if (ret != 0 || intval >= ZIO_CHECKSUM_LEGACY_FUNCTIONS)
1944 		return (SET_ERROR(EINVAL));
1945 
1946 	ret = nvlist_lookup_uint64(nvl, "mdn_nlevels", &nlevels);
1947 	if (ret != 0 || nlevels > DN_MAX_LEVELS)
1948 		return (SET_ERROR(EINVAL));
1949 
1950 	ret = nvlist_lookup_uint64(nvl, "mdn_blksz", &blksz);
1951 	if (ret != 0 || blksz < SPA_MINBLOCKSIZE)
1952 		return (SET_ERROR(EINVAL));
1953 	else if (blksz > spa_maxblocksize(tx->tx_pool->dp_spa))
1954 		return (SET_ERROR(ENOTSUP));
1955 
1956 	ret = nvlist_lookup_uint64(nvl, "mdn_indblkshift", &ibs);
1957 	if (ret != 0 || ibs < DN_MIN_INDBLKSHIFT || ibs > DN_MAX_INDBLKSHIFT)
1958 		return (SET_ERROR(ENOTSUP));
1959 
1960 	ret = nvlist_lookup_uint64(nvl, "mdn_nblkptr", &nblkptr);
1961 	if (ret != 0 || nblkptr != DN_MAX_NBLKPTR)
1962 		return (SET_ERROR(ENOTSUP));
1963 
1964 	ret = nvlist_lookup_uint64(nvl, "mdn_maxblkid", &maxblkid);
1965 	if (ret != 0)
1966 		return (SET_ERROR(EINVAL));
1967 
1968 	ret = nvlist_lookup_uint8_array(nvl, "portable_mac", &buf, &len);
1969 	if (ret != 0 || len != ZIO_OBJSET_MAC_LEN)
1970 		return (SET_ERROR(EINVAL));
1971 
1972 	ret = dmu_objset_from_ds(ds, &os);
1973 	if (ret != 0)
1974 		return (ret);
1975 
1976 	/*
1977 	 * Useraccounting is not portable and must be done with the keys loaded.
1978 	 * Therefore, whenever we do any kind of receive the useraccounting
1979 	 * must not be present.
1980 	 */
1981 	ASSERT0(os->os_flags & OBJSET_FLAG_USERACCOUNTING_COMPLETE);
1982 
1983 	mdn = DMU_META_DNODE(os);
1984 
1985 	/*
1986 	 * If we already created the objset, make sure its unchangeable
1987 	 * properties match the ones received in the nvlist.
1988 	 */
1989 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1990 	if (!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)) &&
1991 	    (mdn->dn_nlevels != nlevels || mdn->dn_datablksz != blksz ||
1992 	    mdn->dn_indblkshift != ibs || mdn->dn_nblkptr != nblkptr)) {
1993 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
1994 		return (SET_ERROR(EINVAL));
1995 	}
1996 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1997 
1998 	/*
1999 	 * Check that the ivset guid of the fromds matches the one from the
2000 	 * send stream. Older versions of the encryption code did not have
2001 	 * an ivset guid on the from dataset and did not send one in the
2002 	 * stream. For these streams we provide the
2003 	 * zfs_disable_ivset_guid_check tunable to allow these datasets to
2004 	 * be received with a generated ivset guid.
2005 	 */
2006 	if (fromds != NULL && !zfs_disable_ivset_guid_check) {
2007 		uint64_t from_ivset_guid = 0;
2008 		intval = 0;
2009 
2010 		(void) nvlist_lookup_uint64(nvl, "from_ivset_guid", &intval);
2011 		(void) zap_lookup(tx->tx_pool->dp_meta_objset,
2012 		    fromds->ds_object, DS_FIELD_IVSET_GUID,
2013 		    sizeof (from_ivset_guid), 1, &from_ivset_guid);
2014 
2015 		if (intval == 0 || from_ivset_guid == 0)
2016 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISSING));
2017 
2018 		if (intval != from_ivset_guid)
2019 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISMATCH));
2020 	}
2021 
2022 	/*
2023 	 * Check that the ivset guid of the fromds matches the one from the
2024 	 * send stream. Older versions of the encryption code did not have
2025 	 * an ivset guid on the from dataset and did not send one in the
2026 	 * stream. For these streams we provide the
2027 	 * zfs_disable_ivset_guid_check tunable to allow these datasets to
2028 	 * be received with a generated ivset guid.
2029 	 */
2030 	if (fromds != NULL && !zfs_disable_ivset_guid_check) {
2031 		uint64_t from_ivset_guid = 0;
2032 		intval = 0;
2033 
2034 		(void) nvlist_lookup_uint64(nvl, "from_ivset_guid", &intval);
2035 		(void) zap_lookup(tx->tx_pool->dp_meta_objset,
2036 		    fromds->ds_object, DS_FIELD_IVSET_GUID,
2037 		    sizeof (from_ivset_guid), 1, &from_ivset_guid);
2038 
2039 		if (intval == 0 || from_ivset_guid == 0)
2040 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISSING));
2041 
2042 		if (intval != from_ivset_guid)
2043 			return (SET_ERROR(ZFS_ERR_FROM_IVSET_GUID_MISMATCH));
2044 	}
2045 
2046 	return (0);
2047 }
2048 
2049 static void
2050 dsl_crypto_recv_raw_objset_sync(dsl_dataset_t *ds, dmu_objset_type_t ostype,
2051     nvlist_t *nvl, dmu_tx_t *tx)
2052 {
2053 	dsl_pool_t *dp = tx->tx_pool;
2054 	objset_t *os;
2055 	dnode_t *mdn;
2056 	zio_t *zio;
2057 	uint8_t *portable_mac;
2058 	uint_t len;
2059 	uint64_t compress, checksum, nlevels, blksz, ibs, maxblkid;
2060 	boolean_t newds = B_FALSE;
2061 
2062 	VERIFY0(dmu_objset_from_ds(ds, &os));
2063 	mdn = DMU_META_DNODE(os);
2064 
2065 	/*
2066 	 * Fetch the values we need from the nvlist. "to_ivset_guid" must
2067 	 * be set on the snapshot, which doesn't exist yet. The receive
2068 	 * code will take care of this for us later.
2069 	 */
2070 	compress = fnvlist_lookup_uint64(nvl, "mdn_compress");
2071 	checksum = fnvlist_lookup_uint64(nvl, "mdn_checksum");
2072 	nlevels = fnvlist_lookup_uint64(nvl, "mdn_nlevels");
2073 	blksz = fnvlist_lookup_uint64(nvl, "mdn_blksz");
2074 	ibs = fnvlist_lookup_uint64(nvl, "mdn_indblkshift");
2075 	maxblkid = fnvlist_lookup_uint64(nvl, "mdn_maxblkid");
2076 	VERIFY0(nvlist_lookup_uint8_array(nvl, "portable_mac", &portable_mac,
2077 	    &len));
2078 
2079 	/* if we haven't created an objset for the ds yet, do that now */
2080 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2081 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(ds))) {
2082 		(void) dmu_objset_create_impl_dnstats(dp->dp_spa, ds,
2083 		    dsl_dataset_get_blkptr(ds), ostype, nlevels, blksz,
2084 		    ibs, tx);
2085 		newds = B_TRUE;
2086 	}
2087 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
2088 
2089 	/*
2090 	 * Set the portable MAC. The local MAC will always be zero since the
2091 	 * incoming data will all be portable and user accounting will be
2092 	 * deferred until the next mount. Afterwards, flag the os to be
2093 	 * written out raw next time.
2094 	 */
2095 	arc_release(os->os_phys_buf, &os->os_phys_buf);
2096 	bcopy(portable_mac, os->os_phys->os_portable_mac, ZIO_OBJSET_MAC_LEN);
2097 	bzero(os->os_phys->os_local_mac, ZIO_OBJSET_MAC_LEN);
2098 	os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
2099 
2100 	/* set metadnode compression and checksum */
2101 	mdn->dn_compress = compress;
2102 	mdn->dn_checksum = checksum;
2103 
2104 	rw_enter(&mdn->dn_struct_rwlock, RW_WRITER);
2105 	dnode_new_blkid(mdn, maxblkid, tx, B_FALSE, B_TRUE);
2106 	rw_exit(&mdn->dn_struct_rwlock);
2107 
2108 	/*
2109 	 * We can't normally dirty the dataset in syncing context unless
2110 	 * we are creating a new dataset. In this case, we perform a
2111 	 * pseudo txg sync here instead.
2112 	 */
2113 	if (newds) {
2114 		dsl_dataset_dirty(ds, tx);
2115 	} else {
2116 		zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
2117 		dsl_dataset_sync(ds, zio, tx);
2118 		VERIFY0(zio_wait(zio));
2119 
2120 		/* dsl_dataset_sync_done will drop this reference. */
2121 		dmu_buf_add_ref(ds->ds_dbuf, ds);
2122 		dsl_dataset_sync_done(ds, tx);
2123 	}
2124 }
2125 
2126 int
2127 dsl_crypto_recv_raw_key_check(dsl_dataset_t *ds, nvlist_t *nvl, dmu_tx_t *tx)
2128 {
2129 	int ret;
2130 	objset_t *mos = tx->tx_pool->dp_meta_objset;
2131 	uint8_t *buf = NULL;
2132 	uint_t len;
2133 	uint64_t intval, key_guid, version;
2134 	boolean_t is_passphrase = B_FALSE;
2135 
2136 	ASSERT(dsl_dataset_phys(ds)->ds_flags & DS_FLAG_INCONSISTENT);
2137 
2138 	/*
2139 	 * Read and check all the encryption values from the nvlist. We need
2140 	 * all of the fields of a DSL Crypto Key, as well as a fully specified
2141 	 * wrapping key.
2142 	 */
2143 	ret = nvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_CRYPTO_SUITE, &intval);
2144 	if (ret != 0 || intval >= ZIO_CRYPT_FUNCTIONS ||
2145 	    intval <= ZIO_CRYPT_OFF)
2146 		return (SET_ERROR(EINVAL));
2147 
2148 	ret = nvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_GUID, &intval);
2149 	if (ret != 0)
2150 		return (SET_ERROR(EINVAL));
2151 
2152 	/*
2153 	 * If this is an incremental receive make sure the given key guid
2154 	 * matches the one we already have.
2155 	 */
2156 	if (ds->ds_dir->dd_crypto_obj != 0) {
2157 		ret = zap_lookup(mos, ds->ds_dir->dd_crypto_obj,
2158 		    DSL_CRYPTO_KEY_GUID, 8, 1, &key_guid);
2159 		if (ret != 0)
2160 			return (ret);
2161 		if (intval != key_guid)
2162 			return (SET_ERROR(EACCES));
2163 	}
2164 
2165 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MASTER_KEY,
2166 	    &buf, &len);
2167 	if (ret != 0 || len != MASTER_KEY_MAX_LEN)
2168 		return (SET_ERROR(EINVAL));
2169 
2170 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_HMAC_KEY,
2171 	    &buf, &len);
2172 	if (ret != 0 || len != SHA512_HMAC_KEYLEN)
2173 		return (SET_ERROR(EINVAL));
2174 
2175 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_IV, &buf, &len);
2176 	if (ret != 0 || len != WRAPPING_IV_LEN)
2177 		return (SET_ERROR(EINVAL));
2178 
2179 	ret = nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MAC, &buf, &len);
2180 	if (ret != 0 || len != WRAPPING_MAC_LEN)
2181 		return (SET_ERROR(EINVAL));
2182 
2183 	/*
2184 	 * We don't support receiving old on-disk formats. The version 0
2185 	 * implementation protected several fields in an objset that were
2186 	 * not always portable during a raw receive. As a result, we call
2187 	 * the old version an on-disk errata #3.
2188 	 */
2189 	ret = nvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_VERSION, &version);
2190 	if (ret != 0 || version != ZIO_CRYPT_KEY_CURRENT_VERSION)
2191 		return (SET_ERROR(ENOTSUP));
2192 
2193 	ret = nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
2194 	    &intval);
2195 	if (ret != 0 || intval >= ZFS_KEYFORMAT_FORMATS ||
2196 	    intval == ZFS_KEYFORMAT_NONE)
2197 		return (SET_ERROR(EINVAL));
2198 
2199 	is_passphrase = (intval == ZFS_KEYFORMAT_PASSPHRASE);
2200 
2201 	/*
2202 	 * for raw receives we allow any number of pbkdf2iters since there
2203 	 * won't be a chance for the user to change it.
2204 	 */
2205 	ret = nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS),
2206 	    &intval);
2207 	if (ret != 0 || (is_passphrase == (intval == 0)))
2208 		return (SET_ERROR(EINVAL));
2209 
2210 	ret = nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT),
2211 	    &intval);
2212 	if (ret != 0 || (is_passphrase == (intval == 0)))
2213 		return (SET_ERROR(EINVAL));
2214 
2215 	return (0);
2216 }
2217 
2218 void
2219 dsl_crypto_recv_raw_key_sync(dsl_dataset_t *ds, nvlist_t *nvl, dmu_tx_t *tx)
2220 {
2221 	dsl_pool_t *dp = tx->tx_pool;
2222 	objset_t *mos = dp->dp_meta_objset;
2223 	dsl_dir_t *dd = ds->ds_dir;
2224 	uint_t len;
2225 	uint64_t rddobj, one = 1;
2226 	uint8_t *keydata, *hmac_keydata, *iv, *mac;
2227 	uint64_t crypt, key_guid, keyformat, iters, salt;
2228 	uint64_t version = ZIO_CRYPT_KEY_CURRENT_VERSION;
2229 	char *keylocation = "prompt";
2230 
2231 	/* lookup the values we need to create the DSL Crypto Key */
2232 	crypt = fnvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_CRYPTO_SUITE);
2233 	key_guid = fnvlist_lookup_uint64(nvl, DSL_CRYPTO_KEY_GUID);
2234 	keyformat = fnvlist_lookup_uint64(nvl,
2235 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT));
2236 	iters = fnvlist_lookup_uint64(nvl,
2237 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS));
2238 	salt = fnvlist_lookup_uint64(nvl,
2239 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT));
2240 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MASTER_KEY,
2241 	    &keydata, &len));
2242 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_HMAC_KEY,
2243 	    &hmac_keydata, &len));
2244 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_IV, &iv, &len));
2245 	VERIFY0(nvlist_lookup_uint8_array(nvl, DSL_CRYPTO_KEY_MAC, &mac, &len));
2246 
2247 	/* if this is a new dataset setup the DSL Crypto Key. */
2248 	if (dd->dd_crypto_obj == 0) {
2249 		/* zapify the dsl dir so we can add the key object to it */
2250 		dmu_buf_will_dirty(dd->dd_dbuf, tx);
2251 		dsl_dir_zapify(dd, tx);
2252 
2253 		/* create the DSL Crypto Key on disk and activate the feature */
2254 		dd->dd_crypto_obj = zap_create(mos,
2255 		    DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
2256 		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2257 		    dd->dd_crypto_obj, DSL_CRYPTO_KEY_REFCOUNT,
2258 		    sizeof (uint64_t), 1, &one, tx));
2259 		VERIFY0(zap_update(tx->tx_pool->dp_meta_objset,
2260 		    dd->dd_crypto_obj, DSL_CRYPTO_KEY_VERSION,
2261 		    sizeof (uint64_t), 1, &version, tx));
2262 
2263 		dsl_dataset_activate_feature(ds->ds_object,
2264 		    SPA_FEATURE_ENCRYPTION, tx);
2265 		ds->ds_feature_inuse[SPA_FEATURE_ENCRYPTION] = B_TRUE;
2266 
2267 		/* save the dd_crypto_obj on disk */
2268 		VERIFY0(zap_add(mos, dd->dd_object, DD_FIELD_CRYPTO_KEY_OBJ,
2269 		    sizeof (uint64_t), 1, &dd->dd_crypto_obj, tx));
2270 
2271 		/*
2272 		 * Set the keylocation to prompt by default. If keylocation
2273 		 * has been provided via the properties, this will be overridden
2274 		 * later.
2275 		 */
2276 		dsl_prop_set_sync_impl(ds,
2277 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
2278 		    ZPROP_SRC_LOCAL, 1, strlen(keylocation) + 1,
2279 		    keylocation, tx);
2280 
2281 		rddobj = dd->dd_object;
2282 	} else {
2283 		VERIFY0(dsl_dir_get_encryption_root_ddobj(dd, &rddobj));
2284 	}
2285 
2286 	/* sync the key data to the ZAP object on disk */
2287 	dsl_crypto_key_sync_impl(mos, dd->dd_crypto_obj, crypt,
2288 	    rddobj, key_guid, iv, mac, keydata, hmac_keydata, keyformat, salt,
2289 	    iters, tx);
2290 }
2291 
2292 int
2293 dsl_crypto_recv_key_check(void *arg, dmu_tx_t *tx)
2294 {
2295 	int ret;
2296 	dsl_crypto_recv_key_arg_t *dcrka = arg;
2297 	dsl_dataset_t *ds = NULL, *fromds = NULL;
2298 
2299 	ret = dsl_dataset_hold_obj(tx->tx_pool, dcrka->dcrka_dsobj,
2300 	    FTAG, &ds);
2301 	if (ret != 0)
2302 		goto out;
2303 
2304 	if (dcrka->dcrka_fromobj != 0) {
2305 		ret = dsl_dataset_hold_obj(tx->tx_pool, dcrka->dcrka_fromobj,
2306 		    FTAG, &fromds);
2307 		if (ret != 0)
2308 			goto out;
2309 	}
2310 
2311 	ret = dsl_crypto_recv_raw_objset_check(ds, fromds,
2312 	    dcrka->dcrka_ostype, dcrka->dcrka_nvl, tx);
2313 	if (ret != 0)
2314 		goto out;
2315 
2316 	/*
2317 	 * We run this check even if we won't be doing this part of
2318 	 * the receive now so that we don't make the user wait until
2319 	 * the receive finishes to fail.
2320 	 */
2321 	ret = dsl_crypto_recv_raw_key_check(ds, dcrka->dcrka_nvl, tx);
2322 	if (ret != 0)
2323 		goto out;
2324 
2325 out:
2326 	if (ds != NULL)
2327 		dsl_dataset_rele(ds, FTAG);
2328 	if (fromds != NULL)
2329 		dsl_dataset_rele(fromds, FTAG);
2330 	return (ret);
2331 }
2332 
2333 void
2334 dsl_crypto_recv_key_sync(void *arg, dmu_tx_t *tx)
2335 {
2336 	dsl_crypto_recv_key_arg_t *dcrka = arg;
2337 	dsl_dataset_t *ds;
2338 
2339 	VERIFY0(dsl_dataset_hold_obj(tx->tx_pool, dcrka->dcrka_dsobj,
2340 	    FTAG, &ds));
2341 	dsl_crypto_recv_raw_objset_sync(ds, dcrka->dcrka_ostype,
2342 	    dcrka->dcrka_nvl, tx);
2343 	if (dcrka->dcrka_do_key)
2344 		dsl_crypto_recv_raw_key_sync(ds, dcrka->dcrka_nvl, tx);
2345 	dsl_dataset_rele(ds, FTAG);
2346 }
2347 
2348 /*
2349  * This function is used to sync an nvlist representing a DSL Crypto Key and
2350  * the associated encryption parameters. The key will be written exactly as is
2351  * without wrapping it.
2352  */
2353 int
2354 dsl_crypto_recv_raw(const char *poolname, uint64_t dsobj, uint64_t fromobj,
2355     dmu_objset_type_t ostype, nvlist_t *nvl, boolean_t do_key)
2356 {
2357 	dsl_crypto_recv_key_arg_t dcrka;
2358 
2359 	dcrka.dcrka_dsobj = dsobj;
2360 	dcrka.dcrka_fromobj = fromobj;
2361 	dcrka.dcrka_ostype = ostype;
2362 	dcrka.dcrka_nvl = nvl;
2363 	dcrka.dcrka_do_key = do_key;
2364 
2365 	return (dsl_sync_task(poolname, dsl_crypto_recv_key_check,
2366 	    dsl_crypto_recv_key_sync, &dcrka, 1, ZFS_SPACE_CHECK_NORMAL));
2367 }
2368 
2369 int
2370 dsl_crypto_populate_key_nvlist(dsl_dataset_t *ds, uint64_t from_ivset_guid,
2371     nvlist_t **nvl_out)
2372 {
2373 	int ret;
2374 	objset_t *os;
2375 	dnode_t *mdn;
2376 	uint64_t rddobj;
2377 	nvlist_t *nvl = NULL;
2378 	uint64_t dckobj = ds->ds_dir->dd_crypto_obj;
2379 	dsl_dir_t *rdd = NULL;
2380 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
2381 	objset_t *mos = dp->dp_meta_objset;
2382 	uint64_t crypt = 0, key_guid = 0, format = 0;
2383 	uint64_t iters = 0, salt = 0, version = 0;
2384 	uint64_t to_ivset_guid = 0;
2385 	uint8_t raw_keydata[MASTER_KEY_MAX_LEN];
2386 	uint8_t raw_hmac_keydata[SHA512_HMAC_KEYLEN];
2387 	uint8_t iv[WRAPPING_IV_LEN];
2388 	uint8_t mac[WRAPPING_MAC_LEN];
2389 
2390 	ASSERT(dckobj != 0);
2391 
2392 	VERIFY0(dmu_objset_from_ds(ds, &os));
2393 	mdn = DMU_META_DNODE(os);
2394 
2395 	ret = nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP);
2396 	if (ret != 0)
2397 		goto error;
2398 
2399 	/* lookup values from the DSL Crypto Key */
2400 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_CRYPTO_SUITE, 8, 1,
2401 	    &crypt);
2402 	if (ret != 0)
2403 		goto error;
2404 
2405 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_GUID, 8, 1, &key_guid);
2406 	if (ret != 0)
2407 		goto error;
2408 
2409 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_MASTER_KEY, 1,
2410 	    MASTER_KEY_MAX_LEN, raw_keydata);
2411 	if (ret != 0)
2412 		goto error;
2413 
2414 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_HMAC_KEY, 1,
2415 	    SHA512_HMAC_KEYLEN, raw_hmac_keydata);
2416 	if (ret != 0)
2417 		goto error;
2418 
2419 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_IV, 1, WRAPPING_IV_LEN,
2420 	    iv);
2421 	if (ret != 0)
2422 		goto error;
2423 
2424 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_MAC, 1, WRAPPING_MAC_LEN,
2425 	    mac);
2426 	if (ret != 0)
2427 		goto error;
2428 
2429 	/* see zfs_disable_ivset_guid_check tunable for errata info */
2430 	ret = zap_lookup(mos, ds->ds_object, DS_FIELD_IVSET_GUID, 8, 1,
2431 	    &to_ivset_guid);
2432 	if (ret != 0)
2433 		ASSERT3U(dp->dp_spa->spa_errata, !=, 0);
2434 
2435 	/*
2436 	 * We don't support raw sends of legacy on-disk formats. See the
2437 	 * comment in dsl_crypto_recv_key_check() for details.
2438 	 */
2439 	ret = zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_VERSION, 8, 1, &version);
2440 	if (ret != 0 || version != ZIO_CRYPT_KEY_CURRENT_VERSION) {
2441 		dp->dp_spa->spa_errata = ZPOOL_ERRATA_ZOL_6845_ENCRYPTION;
2442 		ret = SET_ERROR(ENOTSUP);
2443 		goto error;
2444 	}
2445 
2446 	/*
2447 	 * Lookup wrapping key properties. An early version of the code did
2448 	 * not correctly add these values to the wrapping key or the DSL
2449 	 * Crypto Key on disk for non encryption roots, so to be safe we
2450 	 * always take the slightly circuitous route of looking it up from
2451 	 * the encryption root's key.
2452 	 */
2453 	ret = dsl_dir_get_encryption_root_ddobj(ds->ds_dir, &rddobj);
2454 	if (ret != 0)
2455 		goto error;
2456 
2457 	dsl_pool_config_enter(dp, FTAG);
2458 
2459 	ret = dsl_dir_hold_obj(dp, rddobj, NULL, FTAG, &rdd);
2460 	if (ret != 0)
2461 		goto error_unlock;
2462 
2463 	ret = zap_lookup(dp->dp_meta_objset, rdd->dd_crypto_obj,
2464 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), 8, 1, &format);
2465 	if (ret != 0)
2466 		goto error_unlock;
2467 
2468 	if (format == ZFS_KEYFORMAT_PASSPHRASE) {
2469 		ret = zap_lookup(dp->dp_meta_objset, rdd->dd_crypto_obj,
2470 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 8, 1, &iters);
2471 		if (ret != 0)
2472 			goto error_unlock;
2473 
2474 		ret = zap_lookup(dp->dp_meta_objset, rdd->dd_crypto_obj,
2475 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 8, 1, &salt);
2476 		if (ret != 0)
2477 			goto error_unlock;
2478 	}
2479 
2480 	dsl_dir_rele(rdd, FTAG);
2481 	dsl_pool_config_exit(dp, FTAG);
2482 
2483 	fnvlist_add_uint64(nvl, DSL_CRYPTO_KEY_CRYPTO_SUITE, crypt);
2484 	fnvlist_add_uint64(nvl, DSL_CRYPTO_KEY_GUID, key_guid);
2485 	fnvlist_add_uint64(nvl, DSL_CRYPTO_KEY_VERSION, version);
2486 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_MASTER_KEY,
2487 	    raw_keydata, MASTER_KEY_MAX_LEN));
2488 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_HMAC_KEY,
2489 	    raw_hmac_keydata, SHA512_HMAC_KEYLEN));
2490 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_IV, iv,
2491 	    WRAPPING_IV_LEN));
2492 	VERIFY0(nvlist_add_uint8_array(nvl, DSL_CRYPTO_KEY_MAC, mac,
2493 	    WRAPPING_MAC_LEN));
2494 	VERIFY0(nvlist_add_uint8_array(nvl, "portable_mac",
2495 	    os->os_phys->os_portable_mac, ZIO_OBJSET_MAC_LEN));
2496 	fnvlist_add_uint64(nvl, zfs_prop_to_name(ZFS_PROP_KEYFORMAT), format);
2497 	fnvlist_add_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), iters);
2498 	fnvlist_add_uint64(nvl, zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt);
2499 	fnvlist_add_uint64(nvl, "mdn_checksum", mdn->dn_checksum);
2500 	fnvlist_add_uint64(nvl, "mdn_compress", mdn->dn_compress);
2501 	fnvlist_add_uint64(nvl, "mdn_nlevels", mdn->dn_nlevels);
2502 	fnvlist_add_uint64(nvl, "mdn_blksz", mdn->dn_datablksz);
2503 	fnvlist_add_uint64(nvl, "mdn_indblkshift", mdn->dn_indblkshift);
2504 	fnvlist_add_uint64(nvl, "mdn_nblkptr", mdn->dn_nblkptr);
2505 	fnvlist_add_uint64(nvl, "mdn_maxblkid", mdn->dn_maxblkid);
2506 	fnvlist_add_uint64(nvl, "to_ivset_guid", to_ivset_guid);
2507 	fnvlist_add_uint64(nvl, "from_ivset_guid", from_ivset_guid);
2508 
2509 	*nvl_out = nvl;
2510 	return (0);
2511 
2512 error_unlock:
2513 	dsl_pool_config_exit(dp, FTAG);
2514 error:
2515 	if (rdd != NULL)
2516 		dsl_dir_rele(rdd, FTAG);
2517 	nvlist_free(nvl);
2518 
2519 	*nvl_out = NULL;
2520 	return (ret);
2521 }
2522 
2523 uint64_t
2524 dsl_crypto_key_create_sync(uint64_t crypt, dsl_wrapping_key_t *wkey,
2525     dmu_tx_t *tx)
2526 {
2527 	dsl_crypto_key_t dck;
2528 	uint64_t version = ZIO_CRYPT_KEY_CURRENT_VERSION;
2529 	uint64_t one = 1ULL;
2530 
2531 	ASSERT(dmu_tx_is_syncing(tx));
2532 	ASSERT3U(crypt, <, ZIO_CRYPT_FUNCTIONS);
2533 	ASSERT3U(crypt, >, ZIO_CRYPT_OFF);
2534 
2535 	/* create the DSL Crypto Key ZAP object */
2536 	dck.dck_obj = zap_create(tx->tx_pool->dp_meta_objset,
2537 	    DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
2538 
2539 	/* fill in the key (on the stack) and sync it to disk */
2540 	dck.dck_wkey = wkey;
2541 	VERIFY0(zio_crypt_key_init(crypt, &dck.dck_key));
2542 
2543 	dsl_crypto_key_sync(&dck, tx);
2544 	VERIFY0(zap_update(tx->tx_pool->dp_meta_objset, dck.dck_obj,
2545 	    DSL_CRYPTO_KEY_REFCOUNT, sizeof (uint64_t), 1, &one, tx));
2546 	VERIFY0(zap_update(tx->tx_pool->dp_meta_objset, dck.dck_obj,
2547 	    DSL_CRYPTO_KEY_VERSION, sizeof (uint64_t), 1, &version, tx));
2548 
2549 	zio_crypt_key_destroy(&dck.dck_key);
2550 	bzero(&dck.dck_key, sizeof (zio_crypt_key_t));
2551 
2552 	return (dck.dck_obj);
2553 }
2554 
2555 uint64_t
2556 dsl_crypto_key_clone_sync(dsl_dir_t *origindd, dmu_tx_t *tx)
2557 {
2558 	objset_t *mos = tx->tx_pool->dp_meta_objset;
2559 
2560 	ASSERT(dmu_tx_is_syncing(tx));
2561 
2562 	VERIFY0(zap_increment(mos, origindd->dd_crypto_obj,
2563 	    DSL_CRYPTO_KEY_REFCOUNT, 1, tx));
2564 
2565 	return (origindd->dd_crypto_obj);
2566 }
2567 
2568 void
2569 dsl_crypto_key_destroy_sync(uint64_t dckobj, dmu_tx_t *tx)
2570 {
2571 	objset_t *mos = tx->tx_pool->dp_meta_objset;
2572 	uint64_t refcnt;
2573 
2574 	/* Decrement the refcount, destroy if this is the last reference */
2575 	VERIFY0(zap_lookup(mos, dckobj, DSL_CRYPTO_KEY_REFCOUNT,
2576 	    sizeof (uint64_t), 1, &refcnt));
2577 
2578 	if (refcnt != 1) {
2579 		VERIFY0(zap_increment(mos, dckobj, DSL_CRYPTO_KEY_REFCOUNT,
2580 		    -1, tx));
2581 	} else {
2582 		VERIFY0(zap_destroy(mos, dckobj, tx));
2583 	}
2584 }
2585 
2586 void
2587 dsl_dataset_crypt_stats(dsl_dataset_t *ds, nvlist_t *nv)
2588 {
2589 	uint64_t intval;
2590 	dsl_dir_t *dd = ds->ds_dir;
2591 	dsl_dir_t *enc_root;
2592 	char buf[ZFS_MAX_DATASET_NAME_LEN];
2593 
2594 	if (dd->dd_crypto_obj == 0)
2595 		return;
2596 
2597 	intval = dsl_dataset_get_keystatus(dd);
2598 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_KEYSTATUS, intval);
2599 
2600 	if (dsl_dir_get_crypt(dd, &intval) == 0)
2601 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_ENCRYPTION, intval);
2602 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2603 	    DSL_CRYPTO_KEY_GUID, 8, 1, &intval) == 0) {
2604 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_KEY_GUID, intval);
2605 	}
2606 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2607 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), 8, 1, &intval) == 0) {
2608 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_KEYFORMAT, intval);
2609 	}
2610 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2611 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 8, 1, &intval) == 0) {
2612 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_PBKDF2_SALT, intval);
2613 	}
2614 	if (zap_lookup(dd->dd_pool->dp_meta_objset, dd->dd_crypto_obj,
2615 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 8, 1, &intval) == 0) {
2616 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_PBKDF2_ITERS, intval);
2617 	}
2618 	if (zap_lookup(dd->dd_pool->dp_meta_objset, ds->ds_object,
2619 	    DS_FIELD_IVSET_GUID, 8, 1, &intval) == 0) {
2620 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_IVSET_GUID, intval);
2621 	}
2622 
2623 	if (dsl_dir_get_encryption_root_ddobj(dd, &intval) == 0) {
2624 		VERIFY0(dsl_dir_hold_obj(dd->dd_pool, intval, NULL, FTAG,
2625 		    &enc_root));
2626 		dsl_dir_name(enc_root, buf);
2627 		dsl_dir_rele(enc_root, FTAG);
2628 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ENCRYPTION_ROOT, buf);
2629 	}
2630 }
2631 
2632 int
2633 spa_crypt_get_salt(spa_t *spa, uint64_t dsobj, uint8_t *salt)
2634 {
2635 	int ret;
2636 	dsl_crypto_key_t *dck = NULL;
2637 
2638 	/* look up the key from the spa's keystore */
2639 	ret = spa_keystore_lookup_key(spa, dsobj, FTAG, &dck);
2640 	if (ret != 0)
2641 		goto error;
2642 
2643 	ret = zio_crypt_key_get_salt(&dck->dck_key, salt);
2644 	if (ret != 0)
2645 		goto error;
2646 
2647 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2648 	return (0);
2649 
2650 error:
2651 	if (dck != NULL)
2652 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
2653 	return (ret);
2654 }
2655 
2656 /*
2657  * Objset blocks are a special case for MAC generation. These blocks have 2
2658  * 256-bit MACs which are embedded within the block itself, rather than a
2659  * single 128 bit MAC. As a result, this function handles encoding and decoding
2660  * the MACs on its own, unlike other functions in this file.
2661  */
2662 int
2663 spa_do_crypt_objset_mac_abd(boolean_t generate, spa_t *spa, uint64_t dsobj,
2664     abd_t *abd, uint_t datalen, boolean_t byteswap)
2665 {
2666 	int ret;
2667 	dsl_crypto_key_t *dck = NULL;
2668 	void *buf = abd_borrow_buf_copy(abd, datalen);
2669 	objset_phys_t *osp = buf;
2670 	uint8_t portable_mac[ZIO_OBJSET_MAC_LEN];
2671 	uint8_t local_mac[ZIO_OBJSET_MAC_LEN];
2672 
2673 	/* look up the key from the spa's keystore */
2674 	ret = spa_keystore_lookup_key(spa, dsobj, FTAG, &dck);
2675 	if (ret != 0)
2676 		goto error;
2677 
2678 	/* calculate both HMACs */
2679 	ret = zio_crypt_do_objset_hmacs(&dck->dck_key, buf, datalen,
2680 	    byteswap, portable_mac, local_mac);
2681 	if (ret != 0)
2682 		goto error;
2683 
2684 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2685 
2686 	/* if we are generating encode the HMACs in the objset_phys_t */
2687 	if (generate) {
2688 		bcopy(portable_mac, osp->os_portable_mac, ZIO_OBJSET_MAC_LEN);
2689 		bcopy(local_mac, osp->os_local_mac, ZIO_OBJSET_MAC_LEN);
2690 		abd_return_buf_copy(abd, buf, datalen);
2691 		return (0);
2692 	}
2693 
2694 	if (bcmp(portable_mac, osp->os_portable_mac, ZIO_OBJSET_MAC_LEN) != 0 ||
2695 	    bcmp(local_mac, osp->os_local_mac, ZIO_OBJSET_MAC_LEN) != 0) {
2696 		abd_return_buf(abd, buf, datalen);
2697 		return (SET_ERROR(ECKSUM));
2698 	}
2699 
2700 	abd_return_buf(abd, buf, datalen);
2701 
2702 	return (0);
2703 
2704 error:
2705 	if (dck != NULL)
2706 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
2707 	abd_return_buf(abd, buf, datalen);
2708 	return (ret);
2709 }
2710 
2711 int
2712 spa_do_crypt_mac_abd(boolean_t generate, spa_t *spa, uint64_t dsobj, abd_t *abd,
2713     uint_t datalen, uint8_t *mac)
2714 {
2715 	int ret;
2716 	dsl_crypto_key_t *dck = NULL;
2717 	uint8_t *buf = abd_borrow_buf_copy(abd, datalen);
2718 	uint8_t digestbuf[ZIO_DATA_MAC_LEN];
2719 
2720 	/* look up the key from the spa's keystore */
2721 	ret = spa_keystore_lookup_key(spa, dsobj, FTAG, &dck);
2722 	if (ret != 0)
2723 		goto error;
2724 
2725 	/* perform the hmac */
2726 	ret = zio_crypt_do_hmac(&dck->dck_key, buf, datalen,
2727 	    digestbuf, ZIO_DATA_MAC_LEN);
2728 	if (ret != 0)
2729 		goto error;
2730 
2731 	abd_return_buf(abd, buf, datalen);
2732 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2733 
2734 	/*
2735 	 * Truncate and fill in mac buffer if we were asked to generate a MAC.
2736 	 * Otherwise verify that the MAC matched what we expected.
2737 	 */
2738 	if (generate) {
2739 		bcopy(digestbuf, mac, ZIO_DATA_MAC_LEN);
2740 		return (0);
2741 	}
2742 
2743 	if (bcmp(digestbuf, mac, ZIO_DATA_MAC_LEN) != 0)
2744 		return (SET_ERROR(ECKSUM));
2745 
2746 	return (0);
2747 
2748 error:
2749 	if (dck != NULL)
2750 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
2751 	abd_return_buf(abd, buf, datalen);
2752 	return (ret);
2753 }
2754 
2755 /*
2756  * This function serves as a multiplexer for encryption and decryption of
2757  * all blocks (except the L2ARC). For encryption, it will populate the IV,
2758  * salt, MAC, and cabd (the ciphertext). On decryption it will simply use
2759  * these fields to populate pabd (the plaintext).
2760  */
2761 /* ARGSUSED */
2762 int
2763 spa_do_crypt_abd(boolean_t encrypt, spa_t *spa, const zbookmark_phys_t *zb,
2764     dmu_object_type_t ot, boolean_t dedup, boolean_t bswap, uint8_t *salt,
2765     uint8_t *iv, uint8_t *mac, uint_t datalen, abd_t *pabd, abd_t *cabd,
2766     boolean_t *no_crypt)
2767 {
2768 	int ret;
2769 	dsl_crypto_key_t *dck = NULL;
2770 	uint8_t *plainbuf = NULL, *cipherbuf = NULL;
2771 
2772 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_ENCRYPTION));
2773 
2774 	/* look up the key from the spa's keystore */
2775 	ret = spa_keystore_lookup_key(spa, zb->zb_objset, FTAG, &dck);
2776 	if (ret != 0) {
2777 		ret = SET_ERROR(EACCES);
2778 		return (ret);
2779 	}
2780 
2781 	if (encrypt) {
2782 		plainbuf = abd_borrow_buf_copy(pabd, datalen);
2783 		cipherbuf = abd_borrow_buf(cabd, datalen);
2784 	} else {
2785 		plainbuf = abd_borrow_buf(pabd, datalen);
2786 		cipherbuf = abd_borrow_buf_copy(cabd, datalen);
2787 	}
2788 
2789 	/*
2790 	 * Both encryption and decryption functions need a salt for key
2791 	 * generation and an IV. When encrypting a non-dedup block, we
2792 	 * generate the salt and IV randomly to be stored by the caller. Dedup
2793 	 * blocks perform a (more expensive) HMAC of the plaintext to obtain
2794 	 * the salt and the IV. ZIL blocks have their salt and IV generated
2795 	 * at allocation time in zio_alloc_zil(). On decryption, we simply use
2796 	 * the provided values.
2797 	 */
2798 	if (encrypt && ot != DMU_OT_INTENT_LOG && !dedup) {
2799 		ret = zio_crypt_key_get_salt(&dck->dck_key, salt);
2800 		if (ret != 0)
2801 			goto error;
2802 
2803 		ret = zio_crypt_generate_iv(iv);
2804 		if (ret != 0)
2805 			goto error;
2806 	} else if (encrypt && dedup) {
2807 		ret = zio_crypt_generate_iv_salt_dedup(&dck->dck_key,
2808 		    plainbuf, datalen, iv, salt);
2809 		if (ret != 0)
2810 			goto error;
2811 	}
2812 
2813 	/* call lower level function to perform encryption / decryption */
2814 	ret = zio_do_crypt_data(encrypt, &dck->dck_key, ot, bswap, salt, iv,
2815 	    mac, datalen, plainbuf, cipherbuf, no_crypt);
2816 
2817 	/*
2818 	 * Handle injected decryption faults. Unfortunately, we cannot inject
2819 	 * faults for dnode blocks because we might trigger the panic in
2820 	 * dbuf_prepare_encrypted_dnode_leaf(), which exists because syncing
2821 	 * context is not prepared to handle malicious decryption failures.
2822 	 */
2823 	if (zio_injection_enabled && !encrypt && ot != DMU_OT_DNODE && ret == 0)
2824 		ret = zio_handle_decrypt_injection(spa, zb, ot, ECKSUM);
2825 	if (ret != 0)
2826 		goto error;
2827 
2828 	if (encrypt) {
2829 		abd_return_buf(pabd, plainbuf, datalen);
2830 		abd_return_buf_copy(cabd, cipherbuf, datalen);
2831 	} else {
2832 		abd_return_buf_copy(pabd, plainbuf, datalen);
2833 		abd_return_buf(cabd, cipherbuf, datalen);
2834 	}
2835 
2836 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2837 
2838 	return (0);
2839 
2840 error:
2841 	if (encrypt) {
2842 		/* zero out any state we might have changed while encrypting */
2843 		bzero(salt, ZIO_DATA_SALT_LEN);
2844 		bzero(iv, ZIO_DATA_IV_LEN);
2845 		bzero(mac, ZIO_DATA_MAC_LEN);
2846 		abd_return_buf(pabd, plainbuf, datalen);
2847 		abd_return_buf_copy(cabd, cipherbuf, datalen);
2848 	} else {
2849 		abd_return_buf_copy(pabd, plainbuf, datalen);
2850 		abd_return_buf(cabd, cipherbuf, datalen);
2851 	}
2852 
2853 	spa_keystore_dsl_key_rele(spa, dck, FTAG);
2854 
2855 	return (ret);
2856 }
2857