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