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