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