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