]> granicus.if.org Git - zfs/blob - lib/libzfs/libzfs_crypto.c
Change functions which return literals to return `const char*`
[zfs] / lib / libzfs / libzfs_crypto.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/zfs_context.h>
21 #include <sys/fs/zfs.h>
22 #include <sys/dsl_crypt.h>
23 #include <libintl.h>
24 #include <termios.h>
25 #include <signal.h>
26 #include <errno.h>
27 #include <openssl/evp.h>
28 #include <libzfs.h>
29 #include "libzfs_impl.h"
30 #include "zfeature_common.h"
31
32 /*
33  * User keys are used to decrypt the master encryption keys of a dataset. This
34  * indirection allows a user to change his / her access key without having to
35  * re-encrypt the entire dataset. User keys can be provided in one of several
36  * ways. Raw keys are simply given to the kernel as is. Similarly, hex keys
37  * are converted to binary and passed into the kernel. Password based keys are
38  * a bit more complicated. Passwords alone do not provide suitable entropy for
39  * encryption and may be too short or too long to be used. In order to derive
40  * a more appropriate key we use a PBKDF2 function. This function is designed
41  * to take a (relatively) long time to calculate in order to discourage
42  * attackers from guessing from a list of common passwords. PBKDF2 requires
43  * 2 additional parameters. The first is the number of iterations to run, which
44  * will ultimately determine how long it takes to derive the resulting key from
45  * the password. The second parameter is a salt that is randomly generated for
46  * each dataset. The salt is used to "tweak" PBKDF2 such that a group of
47  * attackers cannot reasonably generate a table of commonly known passwords to
48  * their output keys and expect it work for all past and future PBKDF2 users.
49  * We store the salt as a hidden property of the dataset (although it is
50  * technically ok if the salt is known to the attacker).
51  */
52
53 typedef enum key_locator {
54         KEY_LOCATOR_NONE,
55         KEY_LOCATOR_PROMPT,
56         KEY_LOCATOR_URI
57 } key_locator_t;
58
59 #define MIN_PASSPHRASE_LEN 8
60 #define MAX_PASSPHRASE_LEN 512
61 #define MAX_KEY_PROMPT_ATTEMPTS 3
62
63 static int caught_interrupt;
64
65 static int
66 pkcs11_get_urandom(uint8_t *buf, size_t bytes)
67 {
68         int rand;
69         ssize_t bytes_read = 0;
70
71         rand = open("/dev/urandom", O_RDONLY);
72
73         if (rand < 0)
74                 return (rand);
75
76         while (bytes_read < bytes) {
77                 ssize_t rc = read(rand, buf + bytes_read, bytes - bytes_read);
78                 if (rc < 0)
79                         break;
80                 bytes_read += rc;
81         }
82
83         (void) close(rand);
84
85         return (bytes_read);
86 }
87
88 static zfs_keylocation_t
89 zfs_prop_parse_keylocation(const char *str)
90 {
91         if (strcmp("prompt", str) == 0)
92                 return (ZFS_KEYLOCATION_PROMPT);
93         else if (strlen(str) > 8 && strncmp("file:///", str, 8) == 0)
94                 return (ZFS_KEYLOCATION_URI);
95
96         return (ZFS_KEYLOCATION_NONE);
97 }
98
99 static int
100 hex_key_to_raw(char *hex, int hexlen, uint8_t *out)
101 {
102         int ret, i;
103         unsigned int c;
104
105         for (i = 0; i < hexlen; i += 2) {
106                 if (!isxdigit(hex[i]) || !isxdigit(hex[i + 1])) {
107                         ret = EINVAL;
108                         goto error;
109                 }
110
111                 ret = sscanf(&hex[i], "%02x", &c);
112                 if (ret != 1) {
113                         ret = EINVAL;
114                         goto error;
115                 }
116
117                 out[i / 2] = c;
118         }
119
120         return (0);
121
122 error:
123         return (ret);
124 }
125
126
127 static void
128 catch_signal(int sig)
129 {
130         caught_interrupt = sig;
131 }
132
133 static const char *
134 get_format_prompt_string(zfs_keyformat_t format)
135 {
136         switch (format) {
137         case ZFS_KEYFORMAT_RAW:
138                 return ("raw key");
139         case ZFS_KEYFORMAT_HEX:
140                 return ("hex key");
141         case ZFS_KEYFORMAT_PASSPHRASE:
142                 return ("passphrase");
143         default:
144                 /* shouldn't happen */
145                 return (NULL);
146         }
147 }
148
149 static int
150 get_key_material_raw(FILE *fd, const char *fsname, zfs_keyformat_t keyformat,
151     boolean_t again, boolean_t newkey, uint8_t **buf, size_t *len_out)
152 {
153         int ret = 0, bytes;
154         size_t buflen = 0;
155         struct termios old_term, new_term;
156         struct sigaction act, osigint, osigtstp;
157
158         *len_out = 0;
159
160         if (isatty(fileno(fd))) {
161                 /*
162                  * handle SIGINT and ignore SIGSTP. This is necessary to
163                  * restore the state of the terminal.
164                  */
165                 caught_interrupt = 0;
166                 act.sa_flags = 0;
167                 (void) sigemptyset(&act.sa_mask);
168                 act.sa_handler = catch_signal;
169
170                 (void) sigaction(SIGINT, &act, &osigint);
171                 act.sa_handler = SIG_IGN;
172                 (void) sigaction(SIGTSTP, &act, &osigtstp);
173
174                 /* prompt for the key */
175                 if (fsname != NULL) {
176                         (void) printf("%s %s%s for '%s': ",
177                             (again) ? "Re-enter" : "Enter",
178                             (newkey) ? "new " : "",
179                             get_format_prompt_string(keyformat), fsname);
180                 } else {
181                         (void) printf("%s %s%s: ",
182                             (again) ? "Re-enter" : "Enter",
183                             (newkey) ? "new " : "",
184                             get_format_prompt_string(keyformat));
185
186                 }
187                 (void) fflush(stdout);
188
189                 /* disable the terminal echo for key input */
190                 (void) tcgetattr(fileno(fd), &old_term);
191
192                 new_term = old_term;
193                 new_term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
194
195                 ret = tcsetattr(fileno(fd), TCSAFLUSH, &new_term);
196                 if (ret != 0) {
197                         ret = errno;
198                         errno = 0;
199                         goto out;
200                 }
201         }
202
203         /* read the key material */
204         if (keyformat != ZFS_KEYFORMAT_RAW) {
205                 bytes = getline((char **)buf, &buflen, fd);
206                 if (bytes < 0) {
207                         ret = errno;
208                         errno = 0;
209                         goto out;
210                 }
211
212                 /* trim the ending newline if it exists */
213                 if ((*buf)[bytes - 1] == '\n') {
214                         (*buf)[bytes - 1] = '\0';
215                         bytes--;
216                 }
217         } else {
218                 /*
219                  * Raw keys may have newline characters in them and so can't
220                  * use getline(). Here we attempt to read 33 bytes so that we
221                  * can properly check the key length (the file should only have
222                  * 32 bytes).
223                  */
224                 *buf = malloc((WRAPPING_KEY_LEN + 1) * sizeof (char));
225                 if (*buf == NULL) {
226                         ret = ENOMEM;
227                         goto out;
228                 }
229
230                 bytes = fread(*buf, 1, WRAPPING_KEY_LEN + 1, fd);
231                 if (bytes < 0) {
232                         /* size errors are handled by the calling function */
233                         free(*buf);
234                         *buf = NULL;
235                         ret = errno;
236                         errno = 0;
237                         goto out;
238                 }
239         }
240
241         *len_out = bytes;
242
243 out:
244         if (isatty(fileno(fd))) {
245                 /* reset the teminal */
246                 (void) tcsetattr(fileno(fd), TCSAFLUSH, &old_term);
247                 (void) sigaction(SIGINT, &osigint, NULL);
248                 (void) sigaction(SIGTSTP, &osigtstp, NULL);
249
250                 /* if we caught a signal, re-throw it now */
251                 if (caught_interrupt != 0) {
252                         (void) kill(getpid(), caught_interrupt);
253                 }
254
255                 /* print the newline that was not echo'd */
256                 printf("\n");
257         }
258
259         return (ret);
260
261 }
262
263 /*
264  * Attempts to fetch key material, no matter where it might live. The key
265  * material is allocated and returned in km_out. *can_retry_out will be set
266  * to B_TRUE if the user is providing the key material interactively, allowing
267  * for re-entry attempts.
268  */
269 static int
270 get_key_material(libzfs_handle_t *hdl, boolean_t do_verify, boolean_t newkey,
271     zfs_keyformat_t keyformat, char *keylocation, const char *fsname,
272     uint8_t **km_out, size_t *kmlen_out, boolean_t *can_retry_out)
273 {
274         int ret, i;
275         zfs_keylocation_t keyloc = ZFS_KEYLOCATION_NONE;
276         FILE *fd = NULL;
277         uint8_t *km = NULL, *km2 = NULL;
278         size_t kmlen, kmlen2;
279         boolean_t can_retry = B_FALSE;
280
281         /* verify and parse the keylocation */
282         keyloc = zfs_prop_parse_keylocation(keylocation);
283
284         /* open the appropriate file descriptor */
285         switch (keyloc) {
286         case ZFS_KEYLOCATION_PROMPT:
287                 fd = stdin;
288                 if (isatty(fileno(fd))) {
289                         can_retry = B_TRUE;
290
291                         /* raw keys cannot be entered on the terminal */
292                         if (keyformat == ZFS_KEYFORMAT_RAW) {
293                                 ret = EINVAL;
294                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
295                                     "Cannot enter raw keys on the terminal"));
296                                 goto error;
297                         }
298                 }
299                 break;
300         case ZFS_KEYLOCATION_URI:
301                 fd = fopen(&keylocation[7], "r");
302                 if (!fd) {
303                         ret = errno;
304                         errno = 0;
305                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
306                             "Failed to open key material file"));
307                         goto error;
308                 }
309                 break;
310         default:
311                 ret = EINVAL;
312                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
313                     "Invalid keylocation."));
314                 goto error;
315         }
316
317         /* fetch the key material into the buffer */
318         ret = get_key_material_raw(fd, fsname, keyformat, B_FALSE, newkey,
319             &km, &kmlen);
320         if (ret != 0)
321                 goto error;
322
323         /* do basic validation of the key material */
324         switch (keyformat) {
325         case ZFS_KEYFORMAT_RAW:
326                 /* verify the key length is correct */
327                 if (kmlen < WRAPPING_KEY_LEN) {
328                         ret = EINVAL;
329                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
330                             "Raw key too short (expected %u)."),
331                             WRAPPING_KEY_LEN);
332                         goto error;
333                 }
334
335                 if (kmlen > WRAPPING_KEY_LEN) {
336                         ret = EINVAL;
337                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
338                             "Raw key too long (expected %u)."),
339                             WRAPPING_KEY_LEN);
340                         goto error;
341                 }
342                 break;
343         case ZFS_KEYFORMAT_HEX:
344                 /* verify the key length is correct */
345                 if (kmlen < WRAPPING_KEY_LEN * 2) {
346                         ret = EINVAL;
347                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
348                             "Hex key too short (expected %u)."),
349                             WRAPPING_KEY_LEN * 2);
350                         goto error;
351                 }
352
353                 if (kmlen > WRAPPING_KEY_LEN * 2) {
354                         ret = EINVAL;
355                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
356                             "Hex key too long (expected %u)."),
357                             WRAPPING_KEY_LEN * 2);
358                         goto error;
359                 }
360
361                 /* check for invalid hex digits */
362                 for (i = 0; i < WRAPPING_KEY_LEN * 2; i++) {
363                         if (!isxdigit((char)km[i])) {
364                                 ret = EINVAL;
365                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
366                                     "Invalid hex character detected."));
367                                 goto error;
368                         }
369                 }
370                 break;
371         case ZFS_KEYFORMAT_PASSPHRASE:
372                 /* verify the length is within bounds */
373                 if (kmlen > MAX_PASSPHRASE_LEN) {
374                         ret = EINVAL;
375                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
376                             "Passphrase too long (max %u)."),
377                             MAX_PASSPHRASE_LEN);
378                         goto error;
379                 }
380
381                 if (kmlen < MIN_PASSPHRASE_LEN) {
382                         ret = EINVAL;
383                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
384                             "Passphrase too short (min %u)."),
385                             MIN_PASSPHRASE_LEN);
386                         goto error;
387                 }
388                 break;
389         default:
390                 /* can't happen, checked above */
391                 break;
392         }
393
394         if (do_verify && isatty(fileno(fd))) {
395                 ret = get_key_material_raw(fd, fsname, keyformat, B_TRUE,
396                     newkey, &km2, &kmlen2);
397                 if (ret != 0)
398                         goto error;
399
400                 if (kmlen2 != kmlen ||
401                     (memcmp((char *)km, (char *)km2, kmlen) != 0)) {
402                         ret = EINVAL;
403                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
404                             "Provided keys do not match."));
405                         goto error;
406                 }
407         }
408
409         if (fd != stdin)
410                 fclose(fd);
411
412         if (km2 != NULL)
413                 free(km2);
414
415         *km_out = km;
416         *kmlen_out = kmlen;
417         if (can_retry_out != NULL)
418                 *can_retry_out = can_retry;
419
420         return (0);
421
422 error:
423         if (km != NULL)
424                 free(km);
425
426         if (km2 != NULL)
427                 free(km2);
428
429         if (fd != NULL && fd != stdin)
430                 fclose(fd);
431
432         *km_out = NULL;
433         *kmlen_out = 0;
434         if (can_retry_out != NULL)
435                 *can_retry_out = can_retry;
436
437         return (ret);
438 }
439
440 static int
441 derive_key(libzfs_handle_t *hdl, zfs_keyformat_t format, uint64_t iters,
442     uint8_t *key_material, size_t key_material_len, uint64_t salt,
443     uint8_t **key_out)
444 {
445         int ret;
446         uint8_t *key;
447
448         *key_out = NULL;
449
450         key = zfs_alloc(hdl, WRAPPING_KEY_LEN);
451         if (!key)
452                 return (ENOMEM);
453
454         switch (format) {
455         case ZFS_KEYFORMAT_RAW:
456                 bcopy(key_material, key, WRAPPING_KEY_LEN);
457                 break;
458         case ZFS_KEYFORMAT_HEX:
459                 ret = hex_key_to_raw((char *)key_material,
460                     WRAPPING_KEY_LEN * 2, key);
461                 if (ret != 0) {
462                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
463                             "Invalid hex key provided."));
464                         goto error;
465                 }
466                 break;
467         case ZFS_KEYFORMAT_PASSPHRASE:
468                 salt = LE_64(salt);
469
470                 ret = PKCS5_PBKDF2_HMAC_SHA1((char *)key_material,
471                     strlen((char *)key_material), ((uint8_t *)&salt),
472                     sizeof (uint64_t), iters, WRAPPING_KEY_LEN, key);
473                 if (ret != 1) {
474                         ret = EIO;
475                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
476                             "Failed to generate key from passphrase."));
477                         goto error;
478                 }
479                 break;
480         default:
481                 ret = EINVAL;
482                 goto error;
483         }
484
485         *key_out = key;
486         return (0);
487
488 error:
489         free(key);
490
491         *key_out = NULL;
492         return (ret);
493 }
494
495 static boolean_t
496 encryption_feature_is_enabled(zpool_handle_t *zph)
497 {
498         nvlist_t *features;
499         uint64_t feat_refcount;
500
501         /* check that features can be enabled */
502         if (zpool_get_prop_int(zph, ZPOOL_PROP_VERSION, NULL)
503             < SPA_VERSION_FEATURES)
504                 return (B_FALSE);
505
506         /* check for crypto feature */
507         features = zpool_get_features(zph);
508         if (!features || nvlist_lookup_uint64(features,
509             spa_feature_table[SPA_FEATURE_ENCRYPTION].fi_guid,
510             &feat_refcount) != 0)
511                 return (B_FALSE);
512
513         return (B_TRUE);
514 }
515
516 static int
517 populate_create_encryption_params_nvlists(libzfs_handle_t *hdl,
518     zfs_handle_t *zhp, boolean_t newkey, zfs_keyformat_t keyformat,
519     char *keylocation, nvlist_t *props, uint8_t **wkeydata, uint_t *wkeylen)
520 {
521         int ret;
522         uint64_t iters = 0, salt = 0;
523         uint8_t *key_material = NULL;
524         size_t key_material_len = 0;
525         uint8_t *key_data = NULL;
526         const char *fsname = (zhp) ? zfs_get_name(zhp) : NULL;
527
528         /* get key material from keyformat and keylocation */
529         ret = get_key_material(hdl, B_TRUE, newkey, keyformat, keylocation,
530             fsname, &key_material, &key_material_len, NULL);
531         if (ret != 0)
532                 goto error;
533
534         /* passphrase formats require a salt and pbkdf2 iters property */
535         if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
536                 /* always generate a new salt */
537                 ret = pkcs11_get_urandom((uint8_t *)&salt, sizeof (uint64_t));
538                 if (ret != sizeof (uint64_t)) {
539                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
540                             "Failed to generate salt."));
541                         goto error;
542                 }
543
544                 ret = nvlist_add_uint64(props,
545                     zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt);
546                 if (ret != 0) {
547                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
548                             "Failed to add salt to properties."));
549                         goto error;
550                 }
551
552                 /*
553                  * If not otherwise specified, use the default number of
554                  * pbkdf2 iterations. If specified, we have already checked
555                  * that the given value is greater than MIN_PBKDF2_ITERATIONS
556                  * during zfs_valid_proplist().
557                  */
558                 ret = nvlist_lookup_uint64(props,
559                     zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
560                 if (ret == ENOENT) {
561                         iters = DEFAULT_PBKDF2_ITERATIONS;
562                         ret = nvlist_add_uint64(props,
563                             zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), iters);
564                         if (ret != 0)
565                                 goto error;
566                 } else if (ret != 0) {
567                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
568                             "Failed to get pbkdf2 iterations."));
569                         goto error;
570                 }
571         } else {
572                 /* check that pbkdf2iters was not specified by the user */
573                 ret = nvlist_lookup_uint64(props,
574                     zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
575                 if (ret == 0) {
576                         ret = EINVAL;
577                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
578                             "Cannot specify pbkdf2iters with a non-passphrase "
579                             "keyformat."));
580                         goto error;
581                 }
582         }
583
584         /* derive a key from the key material */
585         ret = derive_key(hdl, keyformat, iters, key_material, key_material_len,
586             salt, &key_data);
587         if (ret != 0)
588                 goto error;
589
590         free(key_material);
591
592         *wkeydata = key_data;
593         *wkeylen = WRAPPING_KEY_LEN;
594         return (0);
595
596 error:
597         if (key_material != NULL)
598                 free(key_material);
599         if (key_data != NULL)
600                 free(key_data);
601
602         *wkeydata = NULL;
603         *wkeylen = 0;
604         return (ret);
605 }
606
607 static boolean_t
608 proplist_has_encryption_props(nvlist_t *props)
609 {
610         int ret;
611         uint64_t intval;
612         char *strval;
613
614         ret = nvlist_lookup_uint64(props,
615             zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &intval);
616         if (ret == 0 && intval != ZIO_CRYPT_OFF)
617                 return (B_TRUE);
618
619         ret = nvlist_lookup_string(props,
620             zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &strval);
621         if (ret == 0 && strcmp(strval, "none") != 0)
622                 return (B_TRUE);
623
624         ret = nvlist_lookup_uint64(props,
625             zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &intval);
626         if (ret == 0)
627                 return (B_TRUE);
628
629         ret = nvlist_lookup_uint64(props,
630             zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &intval);
631         if (ret == 0)
632                 return (B_TRUE);
633
634         return (B_FALSE);
635 }
636
637 int
638 zfs_crypto_get_encryption_root(zfs_handle_t *zhp, boolean_t *is_encroot,
639     char *buf)
640 {
641         int ret;
642         char prop_encroot[MAXNAMELEN];
643
644         /* if the dataset isn't encrypted, just return */
645         if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) == ZIO_CRYPT_OFF) {
646                 *is_encroot = B_FALSE;
647                 if (buf != NULL)
648                         buf[0] = '\0';
649                 return (0);
650         }
651
652         ret = zfs_prop_get(zhp, ZFS_PROP_ENCRYPTION_ROOT, prop_encroot,
653             sizeof (prop_encroot), NULL, NULL, 0, B_TRUE);
654         if (ret != 0) {
655                 *is_encroot = B_FALSE;
656                 if (buf != NULL)
657                         buf[0] = '\0';
658                 return (ret);
659         }
660
661         *is_encroot = strcmp(prop_encroot, zfs_get_name(zhp)) == 0;
662         if (buf != NULL)
663                 strcpy(buf, prop_encroot);
664
665         return (0);
666 }
667
668 int
669 zfs_crypto_create(libzfs_handle_t *hdl, char *parent_name, nvlist_t *props,
670     nvlist_t *pool_props, uint8_t **wkeydata_out, uint_t *wkeylen_out)
671 {
672         int ret;
673         char errbuf[1024];
674         uint64_t crypt = ZIO_CRYPT_INHERIT, pcrypt = ZIO_CRYPT_INHERIT;
675         uint64_t keyformat = ZFS_KEYFORMAT_NONE;
676         char *keylocation = NULL;
677         zfs_handle_t *pzhp = NULL;
678         uint8_t *wkeydata = NULL;
679         uint_t wkeylen = 0;
680         boolean_t local_crypt = B_TRUE;
681
682         (void) snprintf(errbuf, sizeof (errbuf),
683             dgettext(TEXT_DOMAIN, "Encryption create error"));
684
685         /* lookup crypt from props */
686         ret = nvlist_lookup_uint64(props,
687             zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &crypt);
688         if (ret != 0)
689                 local_crypt = B_FALSE;
690
691         /* lookup key location and format from props */
692         (void) nvlist_lookup_uint64(props,
693             zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
694         (void) nvlist_lookup_string(props,
695             zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
696
697         if (parent_name != NULL) {
698                 /* get a reference to parent dataset */
699                 pzhp = make_dataset_handle(hdl, parent_name);
700                 if (pzhp == NULL) {
701                         ret = ENOENT;
702                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
703                             "Failed to lookup parent."));
704                         goto out;
705                 }
706
707                 /* Lookup parent's crypt */
708                 pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
709
710                 /* Params require the encryption feature */
711                 if (!encryption_feature_is_enabled(pzhp->zpool_hdl)) {
712                         if (proplist_has_encryption_props(props)) {
713                                 ret = EINVAL;
714                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
715                                     "Encryption feature not enabled."));
716                                 goto out;
717                         }
718
719                         ret = 0;
720                         goto out;
721                 }
722         } else {
723                 /*
724                  * special case for root dataset where encryption feature
725                  * feature won't be on disk yet
726                  */
727                 if (!nvlist_exists(pool_props, "feature@encryption")) {
728                         if (proplist_has_encryption_props(props)) {
729                                 ret = EINVAL;
730                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
731                                     "Encryption feature not enabled."));
732                                 goto out;
733                         }
734
735                         ret = 0;
736                         goto out;
737                 }
738
739                 pcrypt = ZIO_CRYPT_OFF;
740         }
741
742         /* Check for encryption being explicitly truned off */
743         if (crypt == ZIO_CRYPT_OFF && pcrypt != ZIO_CRYPT_OFF) {
744                 ret = EINVAL;
745                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
746                     "Invalid encryption value. Dataset must be encrypted."));
747                 goto out;
748         }
749
750         /* Get the inherited encryption property if we don't have it locally */
751         if (!local_crypt)
752                 crypt = pcrypt;
753
754         /*
755          * At this point crypt should be the actual encryption value. If
756          * encryption is off just verify that no encryption properties have
757          * been specified and return.
758          */
759         if (crypt == ZIO_CRYPT_OFF) {
760                 if (proplist_has_encryption_props(props)) {
761                         ret = EINVAL;
762                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
763                             "Encryption must be turned on to set encryption "
764                             "properties."));
765                         goto out;
766                 }
767
768                 ret = 0;
769                 goto out;
770         }
771
772         /*
773          * If we have a parent crypt it is valid to specify encryption alone.
774          * This will result in a child that is encrypted with the chosen
775          * encryption suite that will also inherit the parent's key. If
776          * the parent is not encrypted we need an encryption suite provided.
777          */
778         if (pcrypt == ZIO_CRYPT_OFF && keylocation == NULL &&
779             keyformat == ZFS_KEYFORMAT_NONE) {
780                 ret = EINVAL;
781                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
782                     "Keyformat required for new encryption root."));
783                 goto out;
784         }
785
786         /*
787          * Specifying a keylocation implies this will be a new encryption root.
788          * Check that a keyformat is also specified.
789          */
790         if (keylocation != NULL && keyformat == ZFS_KEYFORMAT_NONE) {
791                 ret = EINVAL;
792                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
793                     "Keyformat required for new encryption root."));
794                 goto out;
795         }
796
797         /* default to prompt if no keylocation is specified */
798         if (keyformat != ZFS_KEYFORMAT_NONE && keylocation == NULL) {
799                 keylocation = "prompt";
800                 ret = nvlist_add_string(props,
801                     zfs_prop_to_name(ZFS_PROP_KEYLOCATION), keylocation);
802                 if (ret != 0)
803                         goto out;
804         }
805
806         /*
807          * If a local key is provided, this dataset will be a new
808          * encryption root. Populate the encryption params.
809          */
810         if (keylocation != NULL) {
811                 ret = populate_create_encryption_params_nvlists(hdl, NULL,
812                     B_FALSE, keyformat, keylocation, props, &wkeydata,
813                     &wkeylen);
814                 if (ret != 0)
815                         goto out;
816         }
817
818         if (pzhp != NULL)
819                 zfs_close(pzhp);
820
821         *wkeydata_out = wkeydata;
822         *wkeylen_out = wkeylen;
823         return (0);
824
825 out:
826         if (pzhp != NULL)
827                 zfs_close(pzhp);
828         if (wkeydata != NULL)
829                 free(wkeydata);
830
831         *wkeydata_out = NULL;
832         *wkeylen_out = 0;
833         return (ret);
834 }
835
836 int
837 zfs_crypto_clone_check(libzfs_handle_t *hdl, zfs_handle_t *origin_zhp,
838     char *parent_name, nvlist_t *props)
839 {
840         int ret;
841         char errbuf[1024];
842         zfs_handle_t *pzhp = NULL;
843         uint64_t pcrypt, ocrypt;
844
845         (void) snprintf(errbuf, sizeof (errbuf),
846             dgettext(TEXT_DOMAIN, "Encryption clone error"));
847
848         /*
849          * No encryption properties should be specified. They will all be
850          * inherited from the origin dataset.
851          */
852         if (nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYFORMAT)) ||
853             nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYLOCATION)) ||
854             nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_ENCRYPTION)) ||
855             nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS))) {
856                 ret = EINVAL;
857                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
858                     "Encryption properties must inherit from origin dataset."));
859                 goto out;
860         }
861
862         /* get a reference to parent dataset, should never be NULL */
863         pzhp = make_dataset_handle(hdl, parent_name);
864         if (pzhp == NULL) {
865                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
866                     "Failed to lookup parent."));
867                 return (ENOENT);
868         }
869
870         /* Lookup parent's crypt */
871         pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
872         ocrypt = zfs_prop_get_int(origin_zhp, ZFS_PROP_ENCRYPTION);
873
874         /* all children of encrypted parents must be encrypted */
875         if (pcrypt != ZIO_CRYPT_OFF && ocrypt == ZIO_CRYPT_OFF) {
876                 ret = EINVAL;
877                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
878                     "Cannot create unencrypted clone as a child "
879                     "of encrypted parent."));
880                 goto out;
881         }
882
883         zfs_close(pzhp);
884         return (0);
885
886 out:
887         if (pzhp != NULL)
888                 zfs_close(pzhp);
889         return (ret);
890 }
891
892 typedef struct loadkeys_cbdata {
893         uint64_t cb_numfailed;
894         uint64_t cb_numattempted;
895 } loadkey_cbdata_t;
896
897 static int
898 load_keys_cb(zfs_handle_t *zhp, void *arg)
899 {
900         int ret;
901         boolean_t is_encroot;
902         loadkey_cbdata_t *cb = arg;
903         uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
904
905         /* only attempt to load keys for encryption roots */
906         ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
907         if (ret != 0 || !is_encroot)
908                 goto out;
909
910         /* don't attempt to load already loaded keys */
911         if (keystatus == ZFS_KEYSTATUS_AVAILABLE)
912                 goto out;
913
914         /* Attempt to load the key. Record status in cb. */
915         cb->cb_numattempted++;
916
917         ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
918         if (ret)
919                 cb->cb_numfailed++;
920
921 out:
922         (void) zfs_iter_filesystems(zhp, load_keys_cb, cb);
923         zfs_close(zhp);
924
925         /* always return 0, since this function is best effort */
926         return (0);
927 }
928
929 /*
930  * This function is best effort. It attempts to load all the keys for the given
931  * filesystem and all of its children.
932  */
933 int
934 zfs_crypto_attempt_load_keys(libzfs_handle_t *hdl, char *fsname)
935 {
936         int ret;
937         zfs_handle_t *zhp = NULL;
938         loadkey_cbdata_t cb = { 0 };
939
940         zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
941         if (zhp == NULL) {
942                 ret = ENOENT;
943                 goto error;
944         }
945
946         ret = load_keys_cb(zfs_handle_dup(zhp), &cb);
947         if (ret)
948                 goto error;
949
950         (void) printf(gettext("%llu / %llu keys successfully loaded\n"),
951             (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
952             (u_longlong_t)cb.cb_numattempted);
953
954         if (cb.cb_numfailed != 0) {
955                 ret = -1;
956                 goto error;
957         }
958
959         zfs_close(zhp);
960         return (0);
961
962 error:
963         if (zhp != NULL)
964                 zfs_close(zhp);
965         return (ret);
966 }
967
968 int
969 zfs_crypto_load_key(zfs_handle_t *zhp, boolean_t noop, char *alt_keylocation)
970 {
971         int ret, attempts = 0;
972         char errbuf[1024];
973         uint64_t keystatus, iters = 0, salt = 0;
974         uint64_t keyformat = ZFS_KEYFORMAT_NONE;
975         char prop_keylocation[MAXNAMELEN];
976         char prop_encroot[MAXNAMELEN];
977         char *keylocation = NULL;
978         uint8_t *key_material = NULL, *key_data = NULL;
979         size_t key_material_len;
980         boolean_t is_encroot, can_retry = B_FALSE, correctible = B_FALSE;
981
982         (void) snprintf(errbuf, sizeof (errbuf),
983             dgettext(TEXT_DOMAIN, "Key load error"));
984
985         /* check that encryption is enabled for the pool */
986         if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
987                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
988                     "Encryption feature not enabled."));
989                 ret = EINVAL;
990                 goto error;
991         }
992
993         /* Fetch the keyformat. Check that the dataset is encrypted. */
994         keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
995         if (keyformat == ZFS_KEYFORMAT_NONE) {
996                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
997                     "'%s' is not encrypted."), zfs_get_name(zhp));
998                 ret = EINVAL;
999                 goto error;
1000         }
1001
1002         /*
1003          * Fetch the key location. Check that we are working with an
1004          * encryption root.
1005          */
1006         ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1007         if (ret != 0) {
1008                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1009                     "Failed to get encryption root for '%s'."),
1010                     zfs_get_name(zhp));
1011                 goto error;
1012         } else if (!is_encroot) {
1013                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1014                     "Keys must be loaded for encryption root of '%s' (%s)."),
1015                     zfs_get_name(zhp), prop_encroot);
1016                 ret = EINVAL;
1017                 goto error;
1018         }
1019
1020         /*
1021          * if the caller has elected to override the keylocation property
1022          * use that instead
1023          */
1024         if (alt_keylocation != NULL) {
1025                 keylocation = alt_keylocation;
1026         } else {
1027                 ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION, prop_keylocation,
1028                     sizeof (prop_keylocation), NULL, NULL, 0, B_TRUE);
1029                 if (ret != 0) {
1030                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1031                             "Failed to get keylocation for '%s'."),
1032                             zfs_get_name(zhp));
1033                         goto error;
1034                 }
1035
1036                 keylocation = prop_keylocation;
1037         }
1038
1039         /* check that the key is unloaded unless this is a noop */
1040         if (!noop) {
1041                 keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1042                 if (keystatus == ZFS_KEYSTATUS_AVAILABLE) {
1043                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1044                             "Key already loaded for '%s'."), zfs_get_name(zhp));
1045                         ret = EEXIST;
1046                         goto error;
1047                 }
1048         }
1049
1050         /* passphrase formats require a salt and pbkdf2_iters property */
1051         if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
1052                 salt = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_SALT);
1053                 iters = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_ITERS);
1054         }
1055
1056 try_again:
1057         /* fetching and deriving the key are correctable errors. set the flag */
1058         correctible = B_TRUE;
1059
1060         /* get key material from key format and location */
1061         ret = get_key_material(zhp->zfs_hdl, B_FALSE, B_FALSE, keyformat,
1062             keylocation, zfs_get_name(zhp), &key_material, &key_material_len,
1063             &can_retry);
1064         if (ret != 0)
1065                 goto error;
1066
1067         /* derive a key from the key material */
1068         ret = derive_key(zhp->zfs_hdl, keyformat, iters, key_material,
1069             key_material_len, salt, &key_data);
1070         if (ret != 0)
1071                 goto error;
1072
1073         correctible = B_FALSE;
1074
1075         /* pass the wrapping key and noop flag to the ioctl */
1076         ret = lzc_load_key(zhp->zfs_name, noop, key_data, WRAPPING_KEY_LEN);
1077         if (ret != 0) {
1078                 switch (ret) {
1079                 case EPERM:
1080                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1081                             "Permission denied."));
1082                         break;
1083                 case EINVAL:
1084                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1085                             "Invalid parameters provided for dataset %s."),
1086                             zfs_get_name(zhp));
1087                         break;
1088                 case EEXIST:
1089                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1090                             "Key already loaded for '%s'."), zfs_get_name(zhp));
1091                         break;
1092                 case EBUSY:
1093                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1094                             "'%s' is busy."), zfs_get_name(zhp));
1095                         break;
1096                 case EACCES:
1097                         correctible = B_TRUE;
1098                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1099                             "Incorrect key provided for '%s'."),
1100                             zfs_get_name(zhp));
1101                         break;
1102                 }
1103                 goto error;
1104         }
1105
1106         free(key_material);
1107         free(key_data);
1108
1109         return (0);
1110
1111 error:
1112         zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1113         if (key_material != NULL) {
1114                 free(key_material);
1115                 key_material = NULL;
1116         }
1117         if (key_data != NULL) {
1118                 free(key_data);
1119                 key_data = NULL;
1120         }
1121
1122         /*
1123          * Here we decide if it is ok to allow the user to retry entering their
1124          * key. The can_retry flag will be set if the user is entering their
1125          * key from an interactive prompt. The correctable flag will only be
1126          * set if an error that occurred could be corrected by retrying. Both
1127          * flags are needed to allow the user to attempt key entry again
1128          */
1129         attempts++;
1130         if (can_retry && correctible && attempts < MAX_KEY_PROMPT_ATTEMPTS)
1131                 goto try_again;
1132
1133         return (ret);
1134 }
1135
1136 int
1137 zfs_crypto_unload_key(zfs_handle_t *zhp)
1138 {
1139         int ret;
1140         char errbuf[1024];
1141         char prop_encroot[MAXNAMELEN];
1142         uint64_t keystatus, keyformat;
1143         boolean_t is_encroot;
1144
1145         (void) snprintf(errbuf, sizeof (errbuf),
1146             dgettext(TEXT_DOMAIN, "Key unload error"));
1147
1148         /* check that encryption is enabled for the pool */
1149         if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1150                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1151                     "Encryption feature not enabled."));
1152                 ret = EINVAL;
1153                 goto error;
1154         }
1155
1156         /* Fetch the keyformat. Check that the dataset is encrypted. */
1157         keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
1158         if (keyformat == ZFS_KEYFORMAT_NONE) {
1159                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1160                     "'%s' is not encrypted."), zfs_get_name(zhp));
1161                 ret = EINVAL;
1162                 goto error;
1163         }
1164
1165         /*
1166          * Fetch the key location. Check that we are working with an
1167          * encryption root.
1168          */
1169         ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1170         if (ret != 0) {
1171                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1172                     "Failed to get encryption root for '%s'."),
1173                     zfs_get_name(zhp));
1174                 goto error;
1175         } else if (!is_encroot) {
1176                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1177                     "Keys must be unloaded for encryption root of '%s' (%s)."),
1178                     zfs_get_name(zhp), prop_encroot);
1179                 ret = EINVAL;
1180                 goto error;
1181         }
1182
1183         /* check that the key is loaded */
1184         keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1185         if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1186                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1187                     "Key already unloaded for '%s'."), zfs_get_name(zhp));
1188                 ret = ENOENT;
1189                 goto error;
1190         }
1191
1192         /* call the ioctl */
1193         ret = lzc_unload_key(zhp->zfs_name);
1194
1195         if (ret != 0) {
1196                 switch (ret) {
1197                 case EPERM:
1198                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1199                             "Permission denied."));
1200                         break;
1201                 case ENOENT:
1202                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1203                             "Key already unloaded for '%s'."),
1204                             zfs_get_name(zhp));
1205                         break;
1206                 case EBUSY:
1207                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1208                             "'%s' is busy."), zfs_get_name(zhp));
1209                         break;
1210                 }
1211                 zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1212         }
1213
1214         return (ret);
1215
1216 error:
1217         zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1218         return (ret);
1219 }
1220
1221 static int
1222 zfs_crypto_verify_rewrap_nvlist(zfs_handle_t *zhp, nvlist_t *props,
1223     nvlist_t **props_out, char *errbuf)
1224 {
1225         int ret;
1226         nvpair_t *elem = NULL;
1227         zfs_prop_t prop;
1228         nvlist_t *new_props = NULL;
1229
1230         new_props = fnvlist_alloc();
1231
1232         /*
1233          * loop through all provided properties, we should only have
1234          * keyformat, keylocation and pbkdf2iters. The actual validation of
1235          * values is done by zfs_valid_proplist().
1236          */
1237         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
1238                 const char *propname = nvpair_name(elem);
1239                 prop = zfs_name_to_prop(propname);
1240
1241                 switch (prop) {
1242                 case ZFS_PROP_PBKDF2_ITERS:
1243                 case ZFS_PROP_KEYFORMAT:
1244                 case ZFS_PROP_KEYLOCATION:
1245                         break;
1246                 default:
1247                         ret = EINVAL;
1248                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1249                             "Only keyformat, keylocation and pbkdf2iters may "
1250                             "be set with this command."));
1251                         goto error;
1252                 }
1253         }
1254
1255         new_props = zfs_valid_proplist(zhp->zfs_hdl, zhp->zfs_type, props,
1256             zfs_prop_get_int(zhp, ZFS_PROP_ZONED), NULL, zhp->zpool_hdl,
1257             B_TRUE, errbuf);
1258         if (new_props == NULL) {
1259                 ret = EINVAL;
1260                 goto error;
1261         }
1262
1263         *props_out = new_props;
1264         return (0);
1265
1266 error:
1267         nvlist_free(new_props);
1268         *props_out = NULL;
1269         return (ret);
1270 }
1271
1272 int
1273 zfs_crypto_rewrap(zfs_handle_t *zhp, nvlist_t *raw_props, boolean_t inheritkey)
1274 {
1275         int ret;
1276         char errbuf[1024];
1277         boolean_t is_encroot;
1278         nvlist_t *props = NULL;
1279         uint8_t *wkeydata = NULL;
1280         uint_t wkeylen = 0;
1281         dcp_cmd_t cmd = (inheritkey) ? DCP_CMD_INHERIT : DCP_CMD_NEW_KEY;
1282         uint64_t crypt, pcrypt, keystatus, pkeystatus;
1283         uint64_t keyformat = ZFS_KEYFORMAT_NONE;
1284         zfs_handle_t *pzhp = NULL;
1285         char *keylocation = NULL;
1286         char origin_name[MAXNAMELEN];
1287         char prop_keylocation[MAXNAMELEN];
1288         char parent_name[ZFS_MAX_DATASET_NAME_LEN];
1289
1290         (void) snprintf(errbuf, sizeof (errbuf),
1291             dgettext(TEXT_DOMAIN, "Key change error"));
1292
1293         /* check that encryption is enabled for the pool */
1294         if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1295                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1296                     "Encryption feature not enabled."));
1297                 ret = EINVAL;
1298                 goto error;
1299         }
1300
1301         /* get crypt from dataset */
1302         crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
1303         if (crypt == ZIO_CRYPT_OFF) {
1304                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1305                     "Dataset not encrypted."));
1306                 ret = EINVAL;
1307                 goto error;
1308         }
1309
1310         /* get the encryption root of the dataset */
1311         ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
1312         if (ret != 0) {
1313                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1314                     "Failed to get encryption root for '%s'."),
1315                     zfs_get_name(zhp));
1316                 goto error;
1317         }
1318
1319         /* Clones use their origin's key and cannot rewrap it */
1320         ret = zfs_prop_get(zhp, ZFS_PROP_ORIGIN, origin_name,
1321             sizeof (origin_name), NULL, NULL, 0, B_TRUE);
1322         if (ret == 0 && strcmp(origin_name, "") != 0) {
1323                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1324                     "Keys cannot be changed on clones."));
1325                 ret = EINVAL;
1326                 goto error;
1327         }
1328
1329         /*
1330          * If the user wants to use the inheritkey variant of this function
1331          * we don't need to collect any crypto arguments.
1332          */
1333         if (!inheritkey) {
1334                 /* validate the provided properties */
1335                 ret = zfs_crypto_verify_rewrap_nvlist(zhp, raw_props, &props,
1336                     errbuf);
1337                 if (ret != 0)
1338                         goto error;
1339
1340                 /*
1341                  * Load keyformat and keylocation from the nvlist. Fetch from
1342                  * the dataset properties if not specified.
1343                  */
1344                 (void) nvlist_lookup_uint64(props,
1345                     zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
1346                 (void) nvlist_lookup_string(props,
1347                     zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
1348
1349                 if (is_encroot) {
1350                         /*
1351                          * If this is already an ecryption root, just keep
1352                          * any properties not set by the user.
1353                          */
1354                         if (keyformat == ZFS_KEYFORMAT_NONE) {
1355                                 keyformat = zfs_prop_get_int(zhp,
1356                                     ZFS_PROP_KEYFORMAT);
1357                                 ret = nvlist_add_uint64(props,
1358                                     zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
1359                                     keyformat);
1360                                 if (ret != 0) {
1361                                         zfs_error_aux(zhp->zfs_hdl,
1362                                             dgettext(TEXT_DOMAIN, "Failed to "
1363                                             "get existing keyformat "
1364                                             "property."));
1365                                         goto error;
1366                                 }
1367                         }
1368
1369                         if (keylocation == NULL) {
1370                                 ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,
1371                                     prop_keylocation, sizeof (prop_keylocation),
1372                                     NULL, NULL, 0, B_TRUE);
1373                                 if (ret != 0) {
1374                                         zfs_error_aux(zhp->zfs_hdl,
1375                                             dgettext(TEXT_DOMAIN, "Failed to "
1376                                             "get existing keylocation "
1377                                             "property."));
1378                                         goto error;
1379                                 }
1380
1381                                 keylocation = prop_keylocation;
1382                         }
1383                 } else {
1384                         /* need a new key for non-encryption roots */
1385                         if (keyformat == ZFS_KEYFORMAT_NONE) {
1386                                 ret = EINVAL;
1387                                 zfs_error_aux(zhp->zfs_hdl,
1388                                     dgettext(TEXT_DOMAIN, "Keyformat required "
1389                                     "for new encryption root."));
1390                                 goto error;
1391                         }
1392
1393                         /* default to prompt if no keylocation is specified */
1394                         if (keylocation == NULL) {
1395                                 keylocation = "prompt";
1396                                 ret = nvlist_add_string(props,
1397                                     zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1398                                     keylocation);
1399                                 if (ret != 0)
1400                                         goto error;
1401                         }
1402                 }
1403
1404                 /* fetch the new wrapping key and associated properties */
1405                 ret = populate_create_encryption_params_nvlists(zhp->zfs_hdl,
1406                     zhp, B_TRUE, keyformat, keylocation, props, &wkeydata,
1407                     &wkeylen);
1408                 if (ret != 0)
1409                         goto error;
1410         } else {
1411                 /* check that zhp is an encryption root */
1412                 if (!is_encroot) {
1413                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1414                             "Key inheritting can only be performed on "
1415                             "encryption roots."));
1416                         ret = EINVAL;
1417                         goto error;
1418                 }
1419
1420                 /* get the parent's name */
1421                 ret = zfs_parent_name(zhp, parent_name, sizeof (parent_name));
1422                 if (ret != 0) {
1423                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1424                             "Root dataset cannot inherit key."));
1425                         ret = EINVAL;
1426                         goto error;
1427                 }
1428
1429                 /* get a handle to the parent */
1430                 pzhp = make_dataset_handle(zhp->zfs_hdl, parent_name);
1431                 if (pzhp == NULL) {
1432                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1433                             "Failed to lookup parent."));
1434                         ret = ENOENT;
1435                         goto error;
1436                 }
1437
1438                 /* parent must be encrypted */
1439                 pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
1440                 if (pcrypt == ZIO_CRYPT_OFF) {
1441                         zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1442                             "Parent must be encrypted."));
1443                         ret = EINVAL;
1444                         goto error;
1445                 }
1446
1447                 /* check that the parent's key is loaded */
1448                 pkeystatus = zfs_prop_get_int(pzhp, ZFS_PROP_KEYSTATUS);
1449                 if (pkeystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1450                         zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1451                             "Parent key must be loaded."));
1452                         ret = EACCES;
1453                         goto error;
1454                 }
1455         }
1456
1457         /* check that the key is loaded */
1458         keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1459         if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1460                 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1461                     "Key must be loaded."));
1462                 ret = EACCES;
1463                 goto error;
1464         }
1465
1466         /* call the ioctl */
1467         ret = lzc_change_key(zhp->zfs_name, cmd, props, wkeydata, wkeylen);
1468         if (ret != 0) {
1469                 switch (ret) {
1470                 case EPERM:
1471                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1472                             "Permission denied."));
1473                         break;
1474                 case EINVAL:
1475                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1476                             "Invalid properties for key change."));
1477                         break;
1478                 case EACCES:
1479                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1480                             "Key is not currently loaded."));
1481                         break;
1482                 }
1483                 zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1484         }
1485
1486         if (pzhp != NULL)
1487                 zfs_close(pzhp);
1488         if (props != NULL)
1489                 nvlist_free(props);
1490         if (wkeydata != NULL)
1491                 free(wkeydata);
1492
1493         return (ret);
1494
1495 error:
1496         if (pzhp != NULL)
1497                 zfs_close(pzhp);
1498         if (props != NULL)
1499                 nvlist_free(props);
1500         if (wkeydata != NULL)
1501                 free(wkeydata);
1502
1503         zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1504         return (ret);
1505 }