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