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
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.
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>
28 #include <openssl/evp.h>
33 #include <sys/param.h>
36 #elif LIBFETCH_IS_LIBCURL
37 #include <curl/curl.h>
40 #include "libzfs_impl.h"
41 #include "zfeature_common.h"
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).
64 #define MIN_PASSPHRASE_LEN 8
65 #define MAX_PASSPHRASE_LEN 512
66 #define MAX_KEY_PROMPT_ATTEMPTS 3
68 static int caught_interrupt;
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 *);
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 },
83 pkcs11_get_urandom(uint8_t *buf, size_t bytes)
86 ssize_t bytes_read = 0;
88 rand = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
93 while (bytes_read < bytes) {
94 ssize_t rc = read(rand, buf + bytes_read, bytes - bytes_read);
106 zfs_prop_parse_keylocation(libzfs_handle_t *restrict hdl, const char *str,
107 zfs_keylocation_t *restrict locp, char **restrict schemep)
109 *locp = ZFS_KEYLOCATION_NONE;
112 if (strcmp("prompt", str) == 0) {
113 *locp = ZFS_KEYLOCATION_PROMPT;
117 regmatch_t pmatch[2];
119 if (regexec(&hdl->libzfs_urire, str, ARRAY_SIZE(pmatch),
123 if (pmatch[1].rm_so == -1) {
124 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
129 scheme_len = pmatch[1].rm_eo - pmatch[1].rm_so;
131 *schemep = calloc(1, scheme_len + 1);
132 if (*schemep == NULL) {
136 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
141 (void) memcpy(*schemep, str + pmatch[1].rm_so, scheme_len);
142 *locp = ZFS_KEYLOCATION_URI;
146 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Invalid keylocation"));
151 hex_key_to_raw(char *hex, int hexlen, uint8_t *out)
156 for (i = 0; i < hexlen; i += 2) {
157 if (!isxdigit(hex[i]) || !isxdigit(hex[i + 1])) {
162 ret = sscanf(&hex[i], "%02x", &c);
179 catch_signal(int sig)
181 caught_interrupt = sig;
185 get_format_prompt_string(zfs_keyformat_t format)
188 case ZFS_KEYFORMAT_RAW:
190 case ZFS_KEYFORMAT_HEX:
192 case ZFS_KEYFORMAT_PASSPHRASE:
193 return ("passphrase");
195 /* shouldn't happen */
200 /* do basic validation of the key material */
202 validate_key(libzfs_handle_t *hdl, zfs_keyformat_t keyformat,
203 const char *key, size_t keylen, boolean_t do_verify)
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)."),
215 if (keylen > WRAPPING_KEY_LEN) {
216 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
217 "Raw key too long (expected %u)."),
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);
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);
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."));
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 */
252 if (keylen > MAX_PASSPHRASE_LEN) {
253 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
254 "Passphrase too long (max %u)."),
259 if (keylen < MIN_PASSPHRASE_LEN) {
260 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
261 "Passphrase too short (min %u)."),
267 /* can't happen, checked above */
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)
283 struct termios old_term, new_term;
284 struct sigaction act, osigint, osigtstp;
290 * handle SIGINT and ignore SIGSTP. This is necessary to
291 * restore the state of the terminal.
293 caught_interrupt = 0;
295 (void) sigemptyset(&act.sa_mask);
296 act.sa_handler = catch_signal;
298 (void) sigaction(SIGINT, &act, &osigint);
299 act.sa_handler = SIG_IGN;
300 (void) sigaction(SIGTSTP, &act, &osigtstp);
302 (void) printf("%s %s%s",
303 is_reenter ? "Re-enter" : "Enter",
304 new_key ? "new " : "",
305 get_format_prompt_string(keyformat));
307 (void) printf(" for '%s'", fsname);
308 (void) fputc(':', stdout);
309 (void) fflush(stdout);
311 /* disable the terminal echo for key input */
312 (void) tcgetattr(fileno(f), &old_term);
315 new_term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
317 ret = tcsetattr(fileno(f), TCSAFLUSH, &new_term);
324 bytes = getline(res, &buflen, f);
331 /* trim the ending newline if it exists */
332 if (bytes > 0 && (*res)[bytes - 1] == '\n') {
333 (*res)[bytes - 1] = '\0';
340 /* reset the terminal */
341 (void) tcsetattr(fileno(f), TCSAFLUSH, &old_term);
342 (void) sigaction(SIGINT, &osigint, NULL);
343 (void) sigaction(SIGTSTP, &osigtstp, NULL);
345 /* if we caught a signal, re-throw it now */
346 if (caught_interrupt != 0)
347 (void) kill(getpid(), caught_interrupt);
349 /* print the newline that was not echo'd */
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)
360 char *buf = NULL, *buf2 = NULL;
361 size_t buflen = 0, buf2len = 0;
364 ASSERT(isatty(fileno(stdin)));
366 /* raw keys cannot be entered on the terminal */
367 if (keyformat == ZFS_KEYFORMAT_RAW) {
369 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
370 "Cannot enter raw keys on the terminal"));
374 /* prompt for the key */
375 if ((ret = libzfs_getpassphrase(keyformat, B_FALSE, newkey, fsname,
376 &buf, &buflen)) != 0) {
386 if ((ret = validate_key(hdl, keyformat, buf, buflen, confirm_key)) !=
392 ret = libzfs_getpassphrase(keyformat, B_TRUE, newkey, fsname, &buf2,
398 buflen = buf2len = 0;
402 if (buflen != buf2len || strcmp(buf, buf2) != 0) {
408 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
409 "Provided keys do not match."));
415 *outbuf = (uint8_t *)buf;
421 get_key_material_raw(FILE *fd, zfs_keyformat_t keyformat,
422 uint8_t **buf, size_t *len_out)
429 /* read the key material */
430 if (keyformat != ZFS_KEYFORMAT_RAW) {
433 bytes = getline((char **)buf, &buflen, fd);
440 /* trim the ending newline if it exists */
441 if (bytes > 0 && (*buf)[bytes - 1] == '\n') {
442 (*buf)[bytes - 1] = '\0';
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
456 *buf = malloc((WRAPPING_KEY_LEN + 1) * sizeof (uint8_t));
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 */
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)
489 if ((f = fopen(uri + 7, "re")) == NULL) {
492 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
493 "Failed to open key material file: %s"), strerror(ret));
497 ret = get_key_material_raw(f, keyformat, buf, len_out);
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)
511 boolean_t is_http = strncmp(uri, "http:", strlen("http:")) == 0;
513 if (strlen(uri) < (is_http ? 7 : 8)) {
519 #define LOAD_FUNCTION(func) \
520 __typeof__(func) *func = dlsym(hdl->libfetch, #func);
522 if (hdl->libfetch == NULL)
523 hdl->libfetch = dlopen(LIBFETCH_SONAME, RTLD_LAZY);
525 if (hdl->libfetch == NULL) {
526 hdl->libfetch = (void *)-1;
527 char *err = dlerror();
529 hdl->libfetch_load_error = strdup(err);
532 if (hdl->libfetch == (void *)-1) {
534 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
535 "Couldn't load %s: %s"),
536 LIBFETCH_SONAME, hdl->libfetch_load_error ?: "(?)");
541 #if LIBFETCH_IS_FETCH
542 LOAD_FUNCTION(fetchGetURL);
543 char *fetchLastErrString = dlsym(hdl->libfetch, "fetchLastErrString");
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);
554 ok = curl_easy_init && curl_easy_setopt && curl_easy_perform &&
555 curl_easy_cleanup && curl_easy_strerror && curl_easy_getinfo;
558 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
559 "keylocation=%s back-end %s missing symbols."),
560 is_http ? "http://" : "https://", LIBFETCH_SONAME);
566 #if LIBFETCH_IS_FETCH
567 key = fetchGetURL(uri, "");
569 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
570 "Couldn't GET %s: %s"),
571 uri, fetchLastErrString);
574 #elif LIBFETCH_IS_LIBCURL
575 CURL *curl = curl_easy_init();
583 kfd = open(getenv("TMPDIR") ?: "/tmp",
584 O_RDWR | O_TMPFILE | O_EXCL | O_CLOEXEC, 0600);
591 "%s/libzfs-XXXXXXXX.https", getenv("TMPDIR") ?: "/tmp") == -1) {
593 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s"),
598 kfd = mkostemps(path, strlen(".https"), O_CLOEXEC);
601 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
602 "Couldn't create temporary file %s: %s"),
603 path, strerror(ret));
611 if ((key = fdopen(kfd, "r+")) == NULL) {
615 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
616 "Couldn't reopen temporary file: %s"), strerror(ret));
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);
631 (void) curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo);
633 (void) curl_easy_setopt(curl, CURLOPT_CAPATH, capath);
635 (void) curl_easy_setopt(curl, CURLOPT_SSLCERT, clcert);
637 (void) curl_easy_setopt(curl, CURLOPT_SSLKEY, clkey);
639 CURLcode res = curl_easy_perform(curl);
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));
648 (void) curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &resp);
650 if (resp < 200 || resp >= 300) {
651 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
652 "Couldn't GET %s: %ld"),
659 curl_easy_cleanup(curl);
661 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
662 "No keylocation=%s back-end."), is_http ? "http://" : "https://");
668 ret = get_key_material_raw(key, keyformat, buf, len_out);
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.
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)
688 zfs_keylocation_t keyloc = ZFS_KEYLOCATION_NONE;
691 char *uri_scheme = NULL;
692 zfs_uri_handler_t *handler = NULL;
693 boolean_t can_retry = B_FALSE;
695 /* verify and parse the keylocation */
696 ret = zfs_prop_parse_keylocation(hdl, keylocation, &keyloc,
701 /* open the appropriate file descriptor */
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);
709 /* fetch the key material into the buffer */
710 ret = get_key_material_raw(stdin, keyformat, &km,
718 case ZFS_KEYLOCATION_URI:
721 for (handler = uri_handlers; handler->zuh_scheme != NULL;
723 if (strcmp(handler->zuh_scheme, uri_scheme) != 0)
726 if ((ret = handler->zuh_handler(hdl, keylocation,
727 fsname, keyformat, newkey, &km, &kmlen)) != 0)
733 if (ret == ENOTSUP) {
734 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
735 "URI scheme is not supported"));
742 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
743 "Invalid keylocation."));
747 if ((ret = validate_key(hdl, keyformat, (const char *)km, kmlen,
753 if (can_retry_out != NULL)
754 *can_retry_out = can_retry;
765 if (can_retry_out != NULL)
766 *can_retry_out = can_retry;
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,
782 key = zfs_alloc(hdl, WRAPPING_KEY_LEN);
787 case ZFS_KEYFORMAT_RAW:
788 bcopy(key_material, key, WRAPPING_KEY_LEN);
790 case ZFS_KEYFORMAT_HEX:
791 ret = hex_key_to_raw((char *)key_material,
792 WRAPPING_KEY_LEN * 2, key);
794 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
795 "Invalid hex key provided."));
799 case ZFS_KEYFORMAT_PASSPHRASE:
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);
807 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
808 "Failed to generate key from passphrase."));
828 encryption_feature_is_enabled(zpool_handle_t *zph)
831 uint64_t feat_refcount;
833 /* check that features can be enabled */
834 if (zpool_get_prop_int(zph, ZPOOL_PROP_VERSION, NULL)
835 < SPA_VERSION_FEATURES)
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)
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)
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;
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);
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."));
876 ret = nvlist_add_uint64(props,
877 zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt);
879 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
880 "Failed to add salt to properties."));
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().
890 ret = nvlist_lookup_uint64(props,
891 zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
893 iters = DEFAULT_PBKDF2_ITERATIONS;
894 ret = nvlist_add_uint64(props,
895 zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), iters);
898 } else if (ret != 0) {
899 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
900 "Failed to get pbkdf2 iterations."));
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);
909 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
910 "Cannot specify pbkdf2iters with a non-passphrase "
916 /* derive a key from the key material */
917 ret = derive_key(hdl, keyformat, iters, key_material, key_material_len,
924 *wkeydata = key_data;
925 *wkeylen = WRAPPING_KEY_LEN;
929 if (key_material != NULL)
931 if (key_data != NULL)
940 proplist_has_encryption_props(nvlist_t *props)
946 ret = nvlist_lookup_uint64(props,
947 zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &intval);
948 if (ret == 0 && intval != ZIO_CRYPT_OFF)
951 ret = nvlist_lookup_string(props,
952 zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &strval);
953 if (ret == 0 && strcmp(strval, "none") != 0)
956 ret = nvlist_lookup_uint64(props,
957 zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &intval);
961 ret = nvlist_lookup_uint64(props,
962 zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &intval);
970 zfs_crypto_get_encryption_root(zfs_handle_t *zhp, boolean_t *is_encroot,
974 char prop_encroot[MAXNAMELEN];
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;
984 ret = zfs_prop_get(zhp, ZFS_PROP_ENCRYPTION_ROOT, prop_encroot,
985 sizeof (prop_encroot), NULL, NULL, 0, B_TRUE);
987 *is_encroot = B_FALSE;
993 *is_encroot = strcmp(prop_encroot, zfs_get_name(zhp)) == 0;
995 strcpy(buf, prop_encroot);
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)
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;
1013 boolean_t local_crypt = B_TRUE;
1015 (void) snprintf(errbuf, sizeof (errbuf),
1016 dgettext(TEXT_DOMAIN, "Encryption create error"));
1018 /* lookup crypt from props */
1019 ret = nvlist_lookup_uint64(props,
1020 zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &crypt);
1022 local_crypt = B_FALSE;
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);
1030 if (parent_name != NULL) {
1031 /* get a reference to parent dataset */
1032 pzhp = make_dataset_handle(hdl, parent_name);
1035 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1036 "Failed to lookup parent."));
1040 /* Lookup parent's crypt */
1041 pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
1043 /* Params require the encryption feature */
1044 if (!encryption_feature_is_enabled(pzhp->zpool_hdl)) {
1045 if (proplist_has_encryption_props(props)) {
1047 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1048 "Encryption feature not enabled."));
1057 * special case for root dataset where encryption feature
1058 * feature won't be on disk yet
1060 if (!nvlist_exists(pool_props, "feature@encryption")) {
1061 if (proplist_has_encryption_props(props)) {
1063 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1064 "Encryption feature not enabled."));
1072 pcrypt = ZIO_CRYPT_OFF;
1075 /* Get the inherited encryption property if we don't have it locally */
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.
1084 if (crypt == ZIO_CRYPT_OFF) {
1085 if (proplist_has_encryption_props(props)) {
1087 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1088 "Encryption must be turned on to set encryption "
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.
1103 if (pcrypt == ZIO_CRYPT_OFF && keylocation == NULL &&
1104 keyformat == ZFS_KEYFORMAT_NONE) {
1106 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1107 "Keyformat required for new encryption root."));
1112 * Specifying a keylocation implies this will be a new encryption root.
1113 * Check that a keyformat is also specified.
1115 if (keylocation != NULL && keyformat == ZFS_KEYFORMAT_NONE) {
1117 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1118 "Keyformat required for new encryption root."));
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);
1132 * If a local key is provided, this dataset will be a new
1133 * encryption root. Populate the encryption params.
1135 if (keylocation != NULL) {
1137 * 'zfs recv -o keylocation=prompt' won't work because stdin
1138 * is being used by the send stream, so we disallow it.
1140 if (!stdin_available && strcmp(keylocation, "prompt") == 0) {
1142 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Cannot use "
1143 "'prompt' keylocation because stdin is in use."));
1147 ret = populate_create_encryption_params_nvlists(hdl, NULL,
1148 B_TRUE, keyformat, keylocation, props, &wkeydata,
1157 *wkeydata_out = wkeydata;
1158 *wkeylen_out = wkeylen;
1164 if (wkeydata != NULL)
1167 *wkeydata_out = NULL;
1173 zfs_crypto_clone_check(libzfs_handle_t *hdl, zfs_handle_t *origin_zhp,
1174 char *parent_name, nvlist_t *props)
1178 (void) snprintf(errbuf, sizeof (errbuf),
1179 dgettext(TEXT_DOMAIN, "Encryption clone error"));
1182 * No encryption properties should be specified. They will all be
1183 * inherited from the origin dataset.
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."));
1197 typedef struct loadkeys_cbdata {
1198 uint64_t cb_numfailed;
1199 uint64_t cb_numattempted;
1203 load_keys_cb(zfs_handle_t *zhp, void *arg)
1206 boolean_t is_encroot;
1207 loadkey_cbdata_t *cb = arg;
1208 uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
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)
1215 /* don't attempt to load already loaded keys */
1216 if (keystatus == ZFS_KEYSTATUS_AVAILABLE)
1219 /* Attempt to load the key. Record status in cb. */
1220 cb->cb_numattempted++;
1222 ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
1227 (void) zfs_iter_filesystems(zhp, load_keys_cb, cb);
1230 /* always return 0, since this function is best effort */
1235 * This function is best effort. It attempts to load all the keys for the given
1236 * filesystem and all of its children.
1239 zfs_crypto_attempt_load_keys(libzfs_handle_t *hdl, char *fsname)
1242 zfs_handle_t *zhp = NULL;
1243 loadkey_cbdata_t cb = { 0 };
1245 zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1251 ret = load_keys_cb(zfs_handle_dup(zhp), &cb);
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);
1259 if (cb.cb_numfailed != 0) {
1274 zfs_crypto_load_key(zfs_handle_t *zhp, boolean_t noop, char *alt_keylocation)
1276 int ret, attempts = 0;
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;
1287 (void) snprintf(errbuf, sizeof (errbuf),
1288 dgettext(TEXT_DOMAIN, "Key load error"));
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."));
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));
1308 * Fetch the key location. Check that we are working with an
1311 ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1313 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1314 "Failed to get encryption root for '%s'."),
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);
1326 * if the caller has elected to override the keylocation property
1329 if (alt_keylocation != NULL) {
1330 keylocation = alt_keylocation;
1332 ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION, prop_keylocation,
1333 sizeof (prop_keylocation), NULL, NULL, 0, B_TRUE);
1335 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1336 "Failed to get keylocation for '%s'."),
1341 keylocation = prop_keylocation;
1344 /* check that the key is unloaded unless this is a 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));
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);
1362 /* fetching and deriving the key are correctable errors. set the flag */
1363 correctible = B_TRUE;
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,
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);
1378 correctible = B_FALSE;
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);
1385 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1386 "Permission denied."));
1389 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1390 "Invalid parameters provided for dataset %s."),
1394 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1395 "Key already loaded for '%s'."), zfs_get_name(zhp));
1398 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1399 "'%s' is busy."), zfs_get_name(zhp));
1402 correctible = B_TRUE;
1403 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1404 "Incorrect key provided for '%s'."),
1417 zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1418 if (key_material != NULL) {
1420 key_material = NULL;
1422 if (key_data != NULL) {
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
1435 if (can_retry && correctible && attempts < MAX_KEY_PROMPT_ATTEMPTS)
1442 zfs_crypto_unload_key(zfs_handle_t *zhp)
1446 char prop_encroot[MAXNAMELEN];
1447 uint64_t keystatus, keyformat;
1448 boolean_t is_encroot;
1450 (void) snprintf(errbuf, sizeof (errbuf),
1451 dgettext(TEXT_DOMAIN, "Key unload error"));
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."));
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));
1471 * Fetch the key location. Check that we are working with an
1474 ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1476 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1477 "Failed to get encryption root for '%s'."),
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);
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));
1497 /* call the ioctl */
1498 ret = lzc_unload_key(zhp->zfs_name);
1503 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1504 "Permission denied."));
1507 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1508 "Key already unloaded for '%s'."),
1512 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1513 "'%s' is busy."), zfs_get_name(zhp));
1516 zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1522 zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1527 zfs_crypto_verify_rewrap_nvlist(zfs_handle_t *zhp, nvlist_t *props,
1528 nvlist_t **props_out, char *errbuf)
1531 nvpair_t *elem = NULL;
1533 nvlist_t *new_props = NULL;
1535 new_props = fnvlist_alloc();
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().
1542 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
1543 const char *propname = nvpair_name(elem);
1544 prop = zfs_name_to_prop(propname);
1547 case ZFS_PROP_PBKDF2_ITERS:
1548 case ZFS_PROP_KEYFORMAT:
1549 case ZFS_PROP_KEYLOCATION:
1553 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1554 "Only keyformat, keylocation and pbkdf2iters may "
1555 "be set with this command."));
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,
1563 if (new_props == NULL) {
1568 *props_out = new_props;
1572 nvlist_free(new_props);
1578 zfs_crypto_rewrap(zfs_handle_t *zhp, nvlist_t *raw_props, boolean_t inheritkey)
1582 boolean_t is_encroot;
1583 nvlist_t *props = NULL;
1584 uint8_t *wkeydata = NULL;
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];
1595 (void) snprintf(errbuf, sizeof (errbuf),
1596 dgettext(TEXT_DOMAIN, "Key change error"));
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."));
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."));
1615 /* get the encryption root of the dataset */
1616 ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
1618 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1619 "Failed to get encryption root for '%s'."),
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."));
1635 * If the user wants to use the inheritkey variant of this function
1636 * we don't need to collect any crypto arguments.
1639 /* validate the provided properties */
1640 ret = zfs_crypto_verify_rewrap_nvlist(zhp, raw_props, &props,
1646 * Load keyformat and keylocation from the nvlist. Fetch from
1647 * the dataset properties if not specified.
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);
1656 * If this is already an encryption root, just keep
1657 * any properties not set by the user.
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),
1666 zfs_error_aux(zhp->zfs_hdl,
1667 dgettext(TEXT_DOMAIN, "Failed to "
1668 "get existing keyformat "
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);
1679 zfs_error_aux(zhp->zfs_hdl,
1680 dgettext(TEXT_DOMAIN, "Failed to "
1681 "get existing keylocation "
1686 keylocation = prop_keylocation;
1689 /* need a new key for non-encryption roots */
1690 if (keyformat == ZFS_KEYFORMAT_NONE) {
1692 zfs_error_aux(zhp->zfs_hdl,
1693 dgettext(TEXT_DOMAIN, "Keyformat required "
1694 "for new encryption root."));
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),
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,
1716 /* check that zhp is an encryption root */
1718 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1719 "Key inheritting can only be performed on "
1720 "encryption roots."));
1725 /* get the parent's name */
1726 ret = zfs_parent_name(zhp, parent_name, sizeof (parent_name));
1728 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1729 "Root dataset cannot inherit key."));
1734 /* get a handle to the parent */
1735 pzhp = make_dataset_handle(zhp->zfs_hdl, parent_name);
1737 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1738 "Failed to lookup parent."));
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."));
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."));
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."));
1771 /* call the ioctl */
1772 ret = lzc_change_key(zhp->zfs_name, cmd, props, wkeydata, wkeylen);
1776 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1777 "Permission denied."));
1780 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1781 "Invalid properties for key change."));
1784 zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1785 "Key is not currently loaded."));
1788 zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1795 if (wkeydata != NULL)
1805 if (wkeydata != NULL)
1808 zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);