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