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