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