Path: blob/main/sys/contrib/openzfs/lib/libzfs/libzfs_crypto.c
48378 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* This file and its contents are supplied under the terms of the5* Common Development and Distribution License ("CDDL"), version 1.0.6* You may only use this file in accordance with the terms of version7* 1.0 of the CDDL.8*9* A full copy of the text of the CDDL should have accompanied this10* source. A copy of the CDDL is also available via the Internet at11* http://www.illumos.org/license/CDDL.12*13* CDDL HEADER END14*/1516/*17* Copyright (c) 2017, Datto, Inc. All rights reserved.18* Copyright 2020 Joyent, Inc.19*/2021#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_DYNAMIC30#include <dlfcn.h>31#endif32#if LIBFETCH_IS_FETCH33#include <sys/param.h>34#include <stdio.h>35#include <fetch.h>36#elif LIBFETCH_IS_LIBCURL37#include <curl/curl.h>38#endif39#include <libzfs.h>40#include <libzutil.h>41#include "libzfs_impl.h"42#include "zfeature_common.h"4344/*45* User keys are used to decrypt the master encryption keys of a dataset. This46* indirection allows a user to change his / her access key without having to47* re-encrypt the entire dataset. User keys can be provided in one of several48* ways. Raw keys are simply given to the kernel as is. Similarly, hex keys49* are converted to binary and passed into the kernel. Password based keys are50* a bit more complicated. Passwords alone do not provide suitable entropy for51* encryption and may be too short or too long to be used. In order to derive52* a more appropriate key we use a PBKDF2 function. This function is designed53* to take a (relatively) long time to calculate in order to discourage54* attackers from guessing from a list of common passwords. PBKDF2 requires55* 2 additional parameters. The first is the number of iterations to run, which56* will ultimately determine how long it takes to derive the resulting key from57* the password. The second parameter is a salt that is randomly generated for58* each dataset. The salt is used to "tweak" PBKDF2 such that a group of59* attackers cannot reasonably generate a table of commonly known passwords to60* 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 is62* technically ok if the salt is known to the attacker).63*/6465#define MIN_PASSPHRASE_LEN 866#define MAX_PASSPHRASE_LEN 51267#define MAX_KEY_PROMPT_ATTEMPTS 36869static int caught_interrupt;7071static int get_key_material_file(libzfs_handle_t *, const char *, const char *,72zfs_keyformat_t, boolean_t, uint8_t **, size_t *);73static int get_key_material_https(libzfs_handle_t *, const char *, const char *,74zfs_keyformat_t, boolean_t, uint8_t **, size_t *);7576static 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 }81};8283static int84pkcs11_get_urandom(uint8_t *buf, size_t bytes)85{86int rand;87ssize_t bytes_read = 0;8889rand = open("/dev/urandom", O_RDONLY | O_CLOEXEC);9091if (rand < 0)92return (rand);9394while (bytes_read < bytes) {95ssize_t rc = read(rand, buf + bytes_read, bytes - bytes_read);96if (rc < 0)97break;98bytes_read += rc;99}100101(void) close(rand);102103return (bytes_read);104}105106static int107zfs_prop_parse_keylocation(libzfs_handle_t *restrict hdl, const char *str,108zfs_keylocation_t *restrict locp, char **restrict schemep)109{110*locp = ZFS_KEYLOCATION_NONE;111*schemep = NULL;112113if (strcmp("prompt", str) == 0) {114*locp = ZFS_KEYLOCATION_PROMPT;115return (0);116}117118regmatch_t pmatch[2];119120if (regexec(&hdl->libzfs_urire, str, ARRAY_SIZE(pmatch),121pmatch, 0) == 0) {122size_t scheme_len;123124if (pmatch[1].rm_so == -1) {125zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,126"Invalid URI"));127return (EINVAL);128}129130scheme_len = pmatch[1].rm_eo - pmatch[1].rm_so;131132*schemep = calloc(1, scheme_len + 1);133if (*schemep == NULL) {134int ret = errno;135136errno = 0;137zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,138"Invalid URI"));139return (ret);140}141142(void) memcpy(*schemep, str + pmatch[1].rm_so, scheme_len);143*locp = ZFS_KEYLOCATION_URI;144return (0);145}146147zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Invalid keylocation"));148return (EINVAL);149}150151static int152hex_key_to_raw(char *hex, int hexlen, uint8_t *out)153{154int ret, i;155unsigned int c;156157for (i = 0; i < hexlen; i += 2) {158if (!isxdigit(hex[i]) || !isxdigit(hex[i + 1])) {159ret = EINVAL;160goto error;161}162163ret = sscanf(&hex[i], "%02x", &c);164if (ret != 1) {165ret = EINVAL;166goto error;167}168169out[i / 2] = c;170}171172return (0);173174error:175return (ret);176}177178179static void180catch_signal(int sig)181{182caught_interrupt = sig;183}184185static const char *186get_format_prompt_string(zfs_keyformat_t format)187{188switch (format) {189case ZFS_KEYFORMAT_RAW:190return ("raw key");191case ZFS_KEYFORMAT_HEX:192return ("hex key");193case ZFS_KEYFORMAT_PASSPHRASE:194return ("passphrase");195default:196/* shouldn't happen */197return (NULL);198}199}200201/* do basic validation of the key material */202static int203validate_key(libzfs_handle_t *hdl, zfs_keyformat_t keyformat,204const char *key, size_t keylen, boolean_t do_verify)205{206switch (keyformat) {207case ZFS_KEYFORMAT_RAW:208/* verify the key length is correct */209if (keylen < WRAPPING_KEY_LEN) {210zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,211"Raw key too short (expected %u)."),212WRAPPING_KEY_LEN);213return (EINVAL);214}215216if (keylen > WRAPPING_KEY_LEN) {217zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,218"Raw key too long (expected %u)."),219WRAPPING_KEY_LEN);220return (EINVAL);221}222break;223case ZFS_KEYFORMAT_HEX:224/* verify the key length is correct */225if (keylen < WRAPPING_KEY_LEN * 2) {226zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,227"Hex key too short (expected %u)."),228WRAPPING_KEY_LEN * 2);229return (EINVAL);230}231232if (keylen > WRAPPING_KEY_LEN * 2) {233zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,234"Hex key too long (expected %u)."),235WRAPPING_KEY_LEN * 2);236return (EINVAL);237}238239/* check for invalid hex digits */240for (size_t i = 0; i < WRAPPING_KEY_LEN * 2; i++) {241if (!isxdigit(key[i])) {242zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,243"Invalid hex character detected."));244return (EINVAL);245}246}247break;248case ZFS_KEYFORMAT_PASSPHRASE:249/*250* Verify the length is within bounds when setting a new key,251* but not when loading an existing key.252*/253if (!do_verify)254break;255if (keylen > MAX_PASSPHRASE_LEN) {256zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,257"Passphrase too long (max %u)."),258MAX_PASSPHRASE_LEN);259return (EINVAL);260}261262if (keylen < MIN_PASSPHRASE_LEN) {263zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,264"Passphrase too short (min %u)."),265MIN_PASSPHRASE_LEN);266return (EINVAL);267}268break;269default:270/* can't happen, checked above */271break;272}273274return (0);275}276277static int278libzfs_getpassphrase(zfs_keyformat_t keyformat, boolean_t is_reenter,279boolean_t new_key, const char *fsname,280char **restrict res, size_t *restrict reslen)281{282FILE *f = stdin;283size_t buflen = 0;284ssize_t bytes;285int ret = 0;286struct termios old_term, new_term;287struct sigaction act, osigint, osigtstp;288289*res = NULL;290*reslen = 0;291292/*293* handle SIGINT and ignore SIGSTP. This is necessary to294* restore the state of the terminal.295*/296caught_interrupt = 0;297act.sa_flags = 0;298(void) sigemptyset(&act.sa_mask);299act.sa_handler = catch_signal;300301(void) sigaction(SIGINT, &act, &osigint);302act.sa_handler = SIG_IGN;303(void) sigaction(SIGTSTP, &act, &osigtstp);304305(void) printf("%s %s%s",306is_reenter ? "Re-enter" : "Enter",307new_key ? "new " : "",308get_format_prompt_string(keyformat));309if (fsname != NULL)310(void) printf(" for '%s'", fsname);311(void) fputc(':', stdout);312(void) fflush(stdout);313314/* disable the terminal echo for key input */315(void) tcgetattr(fileno(f), &old_term);316317new_term = old_term;318new_term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);319320ret = tcsetattr(fileno(f), TCSAFLUSH, &new_term);321if (ret != 0) {322ret = errno;323errno = 0;324goto out;325}326327bytes = getline(res, &buflen, f);328if (bytes < 0) {329ret = errno;330errno = 0;331goto out;332}333334/* trim the ending newline if it exists */335if (bytes > 0 && (*res)[bytes - 1] == '\n') {336(*res)[bytes - 1] = '\0';337bytes--;338}339340*reslen = bytes;341342out:343/* reset the terminal */344(void) tcsetattr(fileno(f), TCSAFLUSH, &old_term);345(void) sigaction(SIGINT, &osigint, NULL);346(void) sigaction(SIGTSTP, &osigtstp, NULL);347348/* if we caught a signal, re-throw it now */349if (caught_interrupt != 0)350(void) kill(getpid(), caught_interrupt);351352/* print the newline that was not echo'd */353(void) printf("\n");354355return (ret);356}357358static int359get_key_interactive(libzfs_handle_t *restrict hdl, const char *fsname,360zfs_keyformat_t keyformat, boolean_t confirm_key, boolean_t newkey,361uint8_t **restrict outbuf, size_t *restrict len_out)362{363char *buf = NULL, *buf2 = NULL;364size_t buflen = 0, buf2len = 0;365int ret = 0;366367ASSERT(isatty(fileno(stdin)));368369/* raw keys cannot be entered on the terminal */370if (keyformat == ZFS_KEYFORMAT_RAW) {371ret = EINVAL;372zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,373"Cannot enter raw keys on the terminal"));374goto out;375}376377/* prompt for the key */378if ((ret = libzfs_getpassphrase(keyformat, B_FALSE, newkey, fsname,379&buf, &buflen)) != 0) {380free(buf);381buf = NULL;382buflen = 0;383goto out;384}385386if (!confirm_key)387goto out;388389if ((ret = validate_key(hdl, keyformat, buf, buflen, confirm_key)) !=3900) {391free(buf);392return (ret);393}394395ret = libzfs_getpassphrase(keyformat, B_TRUE, newkey, fsname, &buf2,396&buf2len);397if (ret != 0) {398free(buf);399free(buf2);400buf = buf2 = NULL;401buflen = buf2len = 0;402goto out;403}404405if (buflen != buf2len || strcmp(buf, buf2) != 0) {406free(buf);407buf = NULL;408buflen = 0;409410ret = EINVAL;411zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,412"Provided keys do not match."));413}414415free(buf2);416417out:418*outbuf = (uint8_t *)buf;419*len_out = buflen;420return (ret);421}422423static int424get_key_material_raw(FILE *fd, zfs_keyformat_t keyformat,425uint8_t **buf, size_t *len_out)426{427int ret = 0;428size_t buflen = 0;429430*len_out = 0;431432/* read the key material */433if (keyformat != ZFS_KEYFORMAT_RAW) {434ssize_t bytes;435436bytes = getline((char **)buf, &buflen, fd);437if (bytes < 0) {438ret = errno;439errno = 0;440goto out;441}442443/* trim the ending newline if it exists */444if (bytes > 0 && (*buf)[bytes - 1] == '\n') {445(*buf)[bytes - 1] = '\0';446bytes--;447}448449*len_out = bytes;450} else {451size_t n;452453/*454* Raw keys may have newline characters in them and so can't455* use getline(). Here we attempt to read 33 bytes so that we456* can properly check the key length (the file should only have457* 32 bytes).458*/459*buf = malloc((WRAPPING_KEY_LEN + 1) * sizeof (uint8_t));460if (*buf == NULL) {461ret = ENOMEM;462goto out;463}464465n = fread(*buf, 1, WRAPPING_KEY_LEN + 1, fd);466if (n == 0 || ferror(fd)) {467/* size errors are handled by the calling function */468free(*buf);469*buf = NULL;470ret = errno;471errno = 0;472goto out;473}474475*len_out = n;476}477out:478return (ret);479}480481static int482get_key_material_file(libzfs_handle_t *hdl, const char *uri,483const char *fsname, zfs_keyformat_t keyformat, boolean_t newkey,484uint8_t **restrict buf, size_t *restrict len_out)485{486(void) fsname, (void) newkey;487FILE *f = NULL;488int ret = 0;489490if (strlen(uri) < 7)491return (EINVAL);492493if ((f = fopen(uri + 7, "re")) == NULL) {494ret = errno;495errno = 0;496zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,497"Failed to open key material file: %s"), zfs_strerror(ret));498return (ret);499}500501ret = get_key_material_raw(f, keyformat, buf, len_out);502503(void) fclose(f);504505return (ret);506}507508static int509get_key_material_https(libzfs_handle_t *hdl, const char *uri,510const char *fsname, zfs_keyformat_t keyformat, boolean_t newkey,511uint8_t **restrict buf, size_t *restrict len_out)512{513(void) fsname, (void) newkey;514int ret = 0;515FILE *key = NULL;516boolean_t is_http = strncmp(uri, "http:", strlen("http:")) == 0;517518if (strlen(uri) < (is_http ? 7 : 8)) {519ret = EINVAL;520goto end;521}522523#if LIBFETCH_DYNAMIC524#define LOAD_FUNCTION(func) \525__typeof__(func) *func = dlsym(hdl->libfetch, #func);526527if (hdl->libfetch == NULL)528hdl->libfetch = dlopen(LIBFETCH_SONAME, RTLD_LAZY);529530if (hdl->libfetch == NULL) {531hdl->libfetch = (void *)-1;532char *err = dlerror();533if (err)534hdl->libfetch_load_error = strdup(err);535}536537if (hdl->libfetch == (void *)-1) {538ret = ENOSYS;539zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,540"Couldn't load %s: %s"),541LIBFETCH_SONAME, hdl->libfetch_load_error ?: "(?)");542goto end;543}544545boolean_t ok;546#if LIBFETCH_IS_FETCH547LOAD_FUNCTION(fetchGetURL);548char *fetchLastErrString = dlsym(hdl->libfetch, "fetchLastErrString");549550ok = fetchGetURL && fetchLastErrString;551#elif LIBFETCH_IS_LIBCURL552LOAD_FUNCTION(curl_easy_init);553LOAD_FUNCTION(curl_easy_setopt);554LOAD_FUNCTION(curl_easy_perform);555LOAD_FUNCTION(curl_easy_cleanup);556LOAD_FUNCTION(curl_easy_strerror);557LOAD_FUNCTION(curl_easy_getinfo);558559ok = curl_easy_init && curl_easy_setopt && curl_easy_perform &&560curl_easy_cleanup && curl_easy_strerror && curl_easy_getinfo;561#endif562if (!ok) {563zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,564"keylocation=%s back-end %s missing symbols."),565is_http ? "http://" : "https://", LIBFETCH_SONAME);566ret = ENOSYS;567goto end;568}569#endif570571#if LIBFETCH_IS_FETCH572key = fetchGetURL(uri, "");573if (key == NULL) {574zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,575"Couldn't GET %s: %s"),576uri, fetchLastErrString);577ret = ENETDOWN;578}579#elif LIBFETCH_IS_LIBCURL580CURL *curl = curl_easy_init();581if (curl == NULL) {582ret = ENOTSUP;583goto end;584}585586int kfd;587#ifdef O_TMPFILE588kfd = open(getenv("TMPDIR") ?: "/tmp",589O_RDWR | O_TMPFILE | O_EXCL | O_CLOEXEC, 0600);590if (kfd != -1)591goto kfdok;592#endif593594char *path;595if (asprintf(&path,596"%s/libzfs-XXXXXXXX.https", getenv("TMPDIR") ?: "/tmp") == -1) {597ret = ENOMEM;598zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s"),599zfs_strerror(ret));600goto end;601}602603kfd = mkostemps(path, strlen(".https"), O_CLOEXEC);604if (kfd == -1) {605ret = errno;606zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,607"Couldn't create temporary file %s: %s"),608path, zfs_strerror(ret));609free(path);610goto end;611}612(void) unlink(path);613free(path);614615kfdok:616if ((key = fdopen(kfd, "r+")) == NULL) {617ret = errno;618(void) close(kfd);619zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,620"Couldn't reopen temporary file: %s"), zfs_strerror(ret));621goto end;622}623624char errbuf[CURL_ERROR_SIZE] = "";625char *cainfo = getenv("SSL_CA_CERT_FILE"); /* matches fetch(3) */626char *capath = getenv("SSL_CA_CERT_PATH"); /* matches fetch(3) */627char *clcert = getenv("SSL_CLIENT_CERT_FILE"); /* matches fetch(3) */628char *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);634if (cainfo != NULL)635(void) curl_easy_setopt(curl, CURLOPT_CAINFO, cainfo);636if (capath != NULL)637(void) curl_easy_setopt(curl, CURLOPT_CAPATH, capath);638if (clcert != NULL)639(void) curl_easy_setopt(curl, CURLOPT_SSLCERT, clcert);640if (clkey != NULL)641(void) curl_easy_setopt(curl, CURLOPT_SSLKEY, clkey);642643CURLcode res = curl_easy_perform(curl);644645if (res != CURLE_OK) {646zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,647"Failed to connect to %s: %s"),648uri, strlen(errbuf) ? errbuf : curl_easy_strerror(res));649ret = ENETDOWN;650} else {651long resp = 200;652(void) curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &resp);653654if (resp < 200 || resp >= 300) {655zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,656"Couldn't GET %s: %ld"),657uri, resp);658ret = ENOENT;659} else660rewind(key);661}662663curl_easy_cleanup(curl);664#else665zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,666"No keylocation=%s back-end."), is_http ? "http://" : "https://");667ret = ENOSYS;668#endif669670end:671if (ret == 0)672ret = get_key_material_raw(key, keyformat, buf, len_out);673674if (key != NULL)675fclose(key);676677return (ret);678}679680/*681* Attempts to fetch key material, no matter where it might live. The key682* material is allocated and returned in km_out. *can_retry_out will be set683* to B_TRUE if the user is providing the key material interactively, allowing684* for re-entry attempts.685*/686static int687get_key_material(libzfs_handle_t *hdl, boolean_t do_verify, boolean_t newkey,688zfs_keyformat_t keyformat, const char *keylocation, const char *fsname,689uint8_t **km_out, size_t *kmlen_out, boolean_t *can_retry_out)690{691int ret;692zfs_keylocation_t keyloc = ZFS_KEYLOCATION_NONE;693uint8_t *km = NULL;694size_t kmlen = 0;695char *uri_scheme = NULL;696zfs_uri_handler_t *handler = NULL;697boolean_t can_retry = B_FALSE;698699/* verify and parse the keylocation */700ret = zfs_prop_parse_keylocation(hdl, keylocation, &keyloc,701&uri_scheme);702if (ret != 0)703goto error;704705/* open the appropriate file descriptor */706switch (keyloc) {707case ZFS_KEYLOCATION_PROMPT:708if (isatty(fileno(stdin))) {709can_retry = keyformat != ZFS_KEYFORMAT_RAW;710ret = get_key_interactive(hdl, fsname, keyformat,711do_verify, newkey, &km, &kmlen);712} else {713/* fetch the key material into the buffer */714ret = get_key_material_raw(stdin, keyformat, &km,715&kmlen);716}717718if (ret != 0)719goto error;720721break;722case ZFS_KEYLOCATION_URI:723ret = ENOTSUP;724725for (handler = uri_handlers; handler->zuh_scheme != NULL;726handler++) {727if (strcmp(handler->zuh_scheme, uri_scheme) != 0)728continue;729730if ((ret = handler->zuh_handler(hdl, keylocation,731fsname, keyformat, newkey, &km, &kmlen)) != 0)732goto error;733734break;735}736737if (ret == ENOTSUP) {738zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,739"URI scheme is not supported"));740goto error;741}742743break;744default:745ret = EINVAL;746zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,747"Invalid keylocation."));748goto error;749}750751if ((ret = validate_key(hdl, keyformat, (const char *)km, kmlen,752do_verify)) != 0)753goto error;754755*km_out = km;756*kmlen_out = kmlen;757if (can_retry_out != NULL)758*can_retry_out = can_retry;759760free(uri_scheme);761return (0);762763error:764free(km);765766*km_out = NULL;767*kmlen_out = 0;768769if (can_retry_out != NULL)770*can_retry_out = can_retry;771772free(uri_scheme);773return (ret);774}775776static int777derive_key(libzfs_handle_t *hdl, zfs_keyformat_t format, uint64_t iters,778uint8_t *key_material, uint64_t salt,779uint8_t **key_out)780{781int ret;782uint8_t *key;783784*key_out = NULL;785786key = zfs_alloc(hdl, WRAPPING_KEY_LEN);787788switch (format) {789case ZFS_KEYFORMAT_RAW:790memcpy(key, key_material, WRAPPING_KEY_LEN);791break;792case ZFS_KEYFORMAT_HEX:793ret = hex_key_to_raw((char *)key_material,794WRAPPING_KEY_LEN * 2, key);795if (ret != 0) {796zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,797"Invalid hex key provided."));798goto error;799}800break;801case ZFS_KEYFORMAT_PASSPHRASE:802salt = LE_64(salt);803804ret = PKCS5_PBKDF2_HMAC_SHA1((char *)key_material,805strlen((char *)key_material), ((uint8_t *)&salt),806sizeof (uint64_t), iters, WRAPPING_KEY_LEN, key);807if (ret != 1) {808ret = EIO;809zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,810"Failed to generate key from passphrase."));811goto error;812}813break;814default:815ret = EINVAL;816goto error;817}818819*key_out = key;820return (0);821822error:823free(key);824825*key_out = NULL;826return (ret);827}828829static boolean_t830encryption_feature_is_enabled(zpool_handle_t *zph)831{832nvlist_t *features;833uint64_t feat_refcount;834835/* check that features can be enabled */836if (zpool_get_prop_int(zph, ZPOOL_PROP_VERSION, NULL)837< SPA_VERSION_FEATURES)838return (B_FALSE);839840/* check for crypto feature */841features = zpool_get_features(zph);842if (!features || nvlist_lookup_uint64(features,843spa_feature_table[SPA_FEATURE_ENCRYPTION].fi_guid,844&feat_refcount) != 0)845return (B_FALSE);846847return (B_TRUE);848}849850static int851populate_create_encryption_params_nvlists(libzfs_handle_t *hdl,852zfs_handle_t *zhp, boolean_t newkey, zfs_keyformat_t keyformat,853const char *keylocation, nvlist_t *props, uint8_t **wkeydata,854uint_t *wkeylen)855{856int ret;857uint64_t iters = 0, salt = 0;858uint8_t *key_material = NULL;859size_t key_material_len = 0;860uint8_t *key_data = NULL;861const char *fsname = (zhp) ? zfs_get_name(zhp) : NULL;862863/* get key material from keyformat and keylocation */864ret = get_key_material(hdl, B_TRUE, newkey, keyformat, keylocation,865fsname, &key_material, &key_material_len, NULL);866if (ret != 0)867goto error;868869/* passphrase formats require a salt and pbkdf2 iters property */870if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {871/* always generate a new salt */872ret = pkcs11_get_urandom((uint8_t *)&salt, sizeof (uint64_t));873if (ret != sizeof (uint64_t)) {874zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,875"Failed to generate salt."));876goto error;877}878879ret = nvlist_add_uint64(props,880zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt);881if (ret != 0) {882zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,883"Failed to add salt to properties."));884goto error;885}886887/*888* If not otherwise specified, use the default number of889* pbkdf2 iterations. If specified, we have already checked890* that the given value is greater than MIN_PBKDF2_ITERATIONS891* during zfs_valid_proplist().892*/893ret = nvlist_lookup_uint64(props,894zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);895if (ret == ENOENT) {896iters = DEFAULT_PBKDF2_ITERATIONS;897ret = nvlist_add_uint64(props,898zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), iters);899if (ret != 0)900goto error;901} else if (ret != 0) {902zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,903"Failed to get pbkdf2 iterations."));904goto error;905}906} else {907/* check that pbkdf2iters was not specified by the user */908ret = nvlist_lookup_uint64(props,909zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);910if (ret == 0) {911ret = EINVAL;912zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,913"Cannot specify pbkdf2iters with a non-passphrase "914"keyformat."));915goto error;916}917}918919/* derive a key from the key material */920ret = derive_key(hdl, keyformat, iters, key_material, salt, &key_data);921if (ret != 0)922goto error;923924free(key_material);925926*wkeydata = key_data;927*wkeylen = WRAPPING_KEY_LEN;928return (0);929930error:931if (key_material != NULL)932free(key_material);933if (key_data != NULL)934free(key_data);935936*wkeydata = NULL;937*wkeylen = 0;938return (ret);939}940941static boolean_t942proplist_has_encryption_props(nvlist_t *props)943{944int ret;945uint64_t intval;946const char *strval;947948ret = nvlist_lookup_uint64(props,949zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &intval);950if (ret == 0 && intval != ZIO_CRYPT_OFF)951return (B_TRUE);952953ret = nvlist_lookup_string(props,954zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &strval);955if (ret == 0 && strcmp(strval, "none") != 0)956return (B_TRUE);957958ret = nvlist_lookup_uint64(props,959zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &intval);960if (ret == 0)961return (B_TRUE);962963ret = nvlist_lookup_uint64(props,964zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &intval);965if (ret == 0)966return (B_TRUE);967968return (B_FALSE);969}970971int972zfs_crypto_get_encryption_root(zfs_handle_t *zhp, boolean_t *is_encroot,973char *buf)974{975int ret;976char prop_encroot[MAXNAMELEN];977978/* if the dataset isn't encrypted, just return */979if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) == ZIO_CRYPT_OFF) {980*is_encroot = B_FALSE;981if (buf != NULL)982buf[0] = '\0';983return (0);984}985986ret = zfs_prop_get(zhp, ZFS_PROP_ENCRYPTION_ROOT, prop_encroot,987sizeof (prop_encroot), NULL, NULL, 0, B_TRUE);988if (ret != 0) {989*is_encroot = B_FALSE;990if (buf != NULL)991buf[0] = '\0';992return (ret);993}994995*is_encroot = strcmp(prop_encroot, zfs_get_name(zhp)) == 0;996if (buf != NULL)997strcpy(buf, prop_encroot);998999return (0);1000}10011002int1003zfs_crypto_create(libzfs_handle_t *hdl, char *parent_name, nvlist_t *props,1004nvlist_t *pool_props, boolean_t stdin_available, uint8_t **wkeydata_out,1005uint_t *wkeylen_out)1006{1007int ret;1008char errbuf[ERRBUFLEN];1009uint64_t crypt = ZIO_CRYPT_INHERIT, pcrypt = ZIO_CRYPT_INHERIT;1010uint64_t keyformat = ZFS_KEYFORMAT_NONE;1011const char *keylocation = NULL;1012zfs_handle_t *pzhp = NULL;1013uint8_t *wkeydata = NULL;1014uint_t wkeylen = 0;1015boolean_t local_crypt = B_TRUE;10161017(void) snprintf(errbuf, sizeof (errbuf),1018dgettext(TEXT_DOMAIN, "Encryption create error"));10191020/* lookup crypt from props */1021ret = nvlist_lookup_uint64(props,1022zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &crypt);1023if (ret != 0)1024local_crypt = B_FALSE;10251026/* lookup key location and format from props */1027(void) nvlist_lookup_uint64(props,1028zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);1029(void) nvlist_lookup_string(props,1030zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);10311032if (parent_name != NULL) {1033/* get a reference to parent dataset */1034pzhp = make_dataset_handle(hdl, parent_name);1035if (pzhp == NULL) {1036ret = ENOENT;1037zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,1038"Failed to lookup parent."));1039goto out;1040}10411042/* Lookup parent's crypt */1043pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);10441045/* Params require the encryption feature */1046if (!encryption_feature_is_enabled(pzhp->zpool_hdl)) {1047if (proplist_has_encryption_props(props)) {1048ret = EINVAL;1049zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,1050"Encryption feature not enabled."));1051goto out;1052}10531054ret = 0;1055goto out;1056}1057} else {1058/*1059* special case for root dataset where encryption feature1060* feature won't be on disk yet1061*/1062if (!nvlist_exists(pool_props, "feature@encryption")) {1063if (proplist_has_encryption_props(props)) {1064ret = EINVAL;1065zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,1066"Encryption feature not enabled."));1067goto out;1068}10691070ret = 0;1071goto out;1072}10731074pcrypt = ZIO_CRYPT_OFF;1075}10761077/* Get the inherited encryption property if we don't have it locally */1078if (!local_crypt)1079crypt = pcrypt;10801081/*1082* At this point crypt should be the actual encryption value. If1083* encryption is off just verify that no encryption properties have1084* been specified and return.1085*/1086if (crypt == ZIO_CRYPT_OFF) {1087if (proplist_has_encryption_props(props)) {1088ret = EINVAL;1089zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,1090"Encryption must be turned on to set encryption "1091"properties."));1092goto out;1093}10941095ret = 0;1096goto out;1097}10981099/*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 chosen1102* encryption suite that will also inherit the parent's key. If1103* the parent is not encrypted we need an encryption suite provided.1104*/1105if (pcrypt == ZIO_CRYPT_OFF && keylocation == NULL &&1106keyformat == ZFS_KEYFORMAT_NONE) {1107ret = EINVAL;1108zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,1109"Keyformat required for new encryption root."));1110goto out;1111}11121113/*1114* Specifying a keylocation implies this will be a new encryption root.1115* Check that a keyformat is also specified.1116*/1117if (keylocation != NULL && keyformat == ZFS_KEYFORMAT_NONE) {1118ret = EINVAL;1119zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,1120"Keyformat required for new encryption root."));1121goto out;1122}11231124/* default to prompt if no keylocation is specified */1125if (keyformat != ZFS_KEYFORMAT_NONE && keylocation == NULL) {1126keylocation = (char *)"prompt";1127ret = nvlist_add_string(props,1128zfs_prop_to_name(ZFS_PROP_KEYLOCATION), keylocation);1129if (ret != 0)1130goto out;1131}11321133/*1134* If a local key is provided, this dataset will be a new1135* encryption root. Populate the encryption params.1136*/1137if (keylocation != NULL) {1138/*1139* 'zfs recv -o keylocation=prompt' won't work because stdin1140* is being used by the send stream, so we disallow it.1141*/1142if (!stdin_available && strcmp(keylocation, "prompt") == 0) {1143ret = EINVAL;1144zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Cannot use "1145"'prompt' keylocation because stdin is in use."));1146goto out;1147}11481149ret = populate_create_encryption_params_nvlists(hdl, NULL,1150B_TRUE, keyformat, keylocation, props, &wkeydata,1151&wkeylen);1152if (ret != 0)1153goto out;1154}11551156if (pzhp != NULL)1157zfs_close(pzhp);11581159*wkeydata_out = wkeydata;1160*wkeylen_out = wkeylen;1161return (0);11621163out:1164if (pzhp != NULL)1165zfs_close(pzhp);1166if (wkeydata != NULL)1167free(wkeydata);11681169*wkeydata_out = NULL;1170*wkeylen_out = 0;1171return (ret);1172}11731174int1175zfs_crypto_clone_check(libzfs_handle_t *hdl, zfs_handle_t *origin_zhp,1176char *parent_name, nvlist_t *props)1177{1178(void) origin_zhp, (void) parent_name;1179char errbuf[ERRBUFLEN];11801181(void) snprintf(errbuf, sizeof (errbuf),1182dgettext(TEXT_DOMAIN, "Encryption clone error"));11831184/*1185* No encryption properties should be specified. They will all be1186* inherited from the origin dataset.1187*/1188if (nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYFORMAT)) ||1189nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYLOCATION)) ||1190nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_ENCRYPTION)) ||1191nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS))) {1192zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,1193"Encryption properties must inherit from origin dataset."));1194return (EINVAL);1195}11961197return (0);1198}11991200typedef struct loadkeys_cbdata {1201uint64_t cb_numfailed;1202uint64_t cb_numattempted;1203} loadkey_cbdata_t;12041205static int1206load_keys_cb(zfs_handle_t *zhp, void *arg)1207{1208int ret;1209boolean_t is_encroot;1210loadkey_cbdata_t *cb = arg;1211uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);12121213/* only attempt to load keys for encryption roots */1214ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);1215if (ret != 0 || !is_encroot)1216goto out;12171218/* don't attempt to load already loaded keys */1219if (keystatus == ZFS_KEYSTATUS_AVAILABLE)1220goto out;12211222/* Attempt to load the key. Record status in cb. */1223cb->cb_numattempted++;12241225ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);1226if (ret)1227cb->cb_numfailed++;12281229out:1230(void) zfs_iter_filesystems_v2(zhp, 0, load_keys_cb, cb);1231zfs_close(zhp);12321233/* always return 0, since this function is best effort */1234return (0);1235}12361237/*1238* This function is best effort. It attempts to load all the keys for the given1239* filesystem and all of its children.1240*/1241int1242zfs_crypto_attempt_load_keys(libzfs_handle_t *hdl, const char *fsname)1243{1244int ret;1245zfs_handle_t *zhp = NULL;1246loadkey_cbdata_t cb = { 0 };12471248zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);1249if (zhp == NULL) {1250ret = ENOENT;1251goto error;1252}12531254ret = load_keys_cb(zfs_handle_dup(zhp), &cb);1255if (ret)1256goto error;12571258(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);12611262if (cb.cb_numfailed != 0) {1263ret = -1;1264goto error;1265}12661267zfs_close(zhp);1268return (0);12691270error:1271if (zhp != NULL)1272zfs_close(zhp);1273return (ret);1274}12751276int1277zfs_crypto_load_key(zfs_handle_t *zhp, boolean_t noop,1278const char *alt_keylocation)1279{1280int ret, attempts = 0;1281char errbuf[ERRBUFLEN];1282uint64_t keystatus, iters = 0, salt = 0;1283uint64_t keyformat = ZFS_KEYFORMAT_NONE;1284char prop_keylocation[MAXNAMELEN];1285char prop_encroot[MAXNAMELEN];1286const char *keylocation = NULL;1287uint8_t *key_material = NULL, *key_data = NULL;1288size_t key_material_len;1289boolean_t is_encroot, can_retry = B_FALSE, correctible = B_FALSE;12901291(void) snprintf(errbuf, sizeof (errbuf),1292dgettext(TEXT_DOMAIN, "Key load error"));12931294/* check that encryption is enabled for the pool */1295if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {1296zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1297"Encryption feature not enabled."));1298ret = EINVAL;1299goto error;1300}13011302/* Fetch the keyformat. Check that the dataset is encrypted. */1303keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);1304if (keyformat == ZFS_KEYFORMAT_NONE) {1305zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1306"'%s' is not encrypted."), zfs_get_name(zhp));1307ret = EINVAL;1308goto error;1309}13101311/*1312* Fetch the key location. Check that we are working with an1313* encryption root.1314*/1315ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);1316if (ret != 0) {1317zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1318"Failed to get encryption root for '%s'."),1319zfs_get_name(zhp));1320goto error;1321} else if (!is_encroot) {1322zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1323"Keys must be loaded for encryption root of '%s' (%s)."),1324zfs_get_name(zhp), prop_encroot);1325ret = EINVAL;1326goto error;1327}13281329/*1330* if the caller has elected to override the keylocation property1331* use that instead1332*/1333if (alt_keylocation != NULL) {1334keylocation = alt_keylocation;1335} else {1336ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION, prop_keylocation,1337sizeof (prop_keylocation), NULL, NULL, 0, B_TRUE);1338if (ret != 0) {1339zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1340"Failed to get keylocation for '%s'."),1341zfs_get_name(zhp));1342goto error;1343}13441345keylocation = prop_keylocation;1346}13471348/* check that the key is unloaded unless this is a noop */1349if (!noop) {1350keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);1351if (keystatus == ZFS_KEYSTATUS_AVAILABLE) {1352zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1353"Key already loaded for '%s'."), zfs_get_name(zhp));1354ret = EEXIST;1355goto error;1356}1357}13581359/* passphrase formats require a salt and pbkdf2_iters property */1360if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {1361salt = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_SALT);1362iters = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_ITERS);1363}13641365try_again:1366/* fetching and deriving the key are correctable errors. set the flag */1367correctible = B_TRUE;13681369/* get key material from key format and location */1370ret = get_key_material(zhp->zfs_hdl, B_FALSE, B_FALSE, keyformat,1371keylocation, zfs_get_name(zhp), &key_material, &key_material_len,1372&can_retry);1373if (ret != 0)1374goto error;13751376/* derive a key from the key material */1377ret = derive_key(zhp->zfs_hdl, keyformat, iters, key_material, salt,1378&key_data);1379if (ret != 0)1380goto error;13811382correctible = B_FALSE;13831384/* pass the wrapping key and noop flag to the ioctl */1385ret = lzc_load_key(zhp->zfs_name, noop, key_data, WRAPPING_KEY_LEN);1386if (ret != 0) {1387switch (ret) {1388case EPERM:1389zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1390"Permission denied."));1391break;1392case EINVAL:1393zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1394"Invalid parameters provided for dataset %s."),1395zfs_get_name(zhp));1396break;1397case EEXIST:1398zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1399"Key already loaded for '%s'."), zfs_get_name(zhp));1400break;1401case EBUSY:1402zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1403"'%s' is busy."), zfs_get_name(zhp));1404break;1405case EACCES:1406correctible = B_TRUE;1407zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1408"Incorrect key provided for '%s'."),1409zfs_get_name(zhp));1410break;1411case ZFS_ERR_CRYPTO_NOTSUP:1412zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1413"'%s' uses an unsupported encryption suite."),1414zfs_get_name(zhp));1415break;1416}1417goto error;1418}14191420free(key_material);1421free(key_data);14221423return (0);14241425error:1426zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);1427if (key_material != NULL) {1428free(key_material);1429key_material = NULL;1430}1431if (key_data != NULL) {1432free(key_data);1433key_data = NULL;1434}14351436/*1437* Here we decide if it is ok to allow the user to retry entering their1438* key. The can_retry flag will be set if the user is entering their1439* key from an interactive prompt. The correctable flag will only be1440* set if an error that occurred could be corrected by retrying. Both1441* flags are needed to allow the user to attempt key entry again1442*/1443attempts++;1444if (can_retry && correctible && attempts < MAX_KEY_PROMPT_ATTEMPTS)1445goto try_again;14461447return (ret);1448}14491450int1451zfs_crypto_unload_key(zfs_handle_t *zhp)1452{1453int ret;1454char errbuf[ERRBUFLEN];1455char prop_encroot[MAXNAMELEN];1456uint64_t keystatus, keyformat;1457boolean_t is_encroot;14581459(void) snprintf(errbuf, sizeof (errbuf),1460dgettext(TEXT_DOMAIN, "Key unload error"));14611462/* check that encryption is enabled for the pool */1463if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {1464zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1465"Encryption feature not enabled."));1466ret = EINVAL;1467goto error;1468}14691470/* Fetch the keyformat. Check that the dataset is encrypted. */1471keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);1472if (keyformat == ZFS_KEYFORMAT_NONE) {1473zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1474"'%s' is not encrypted."), zfs_get_name(zhp));1475ret = EINVAL;1476goto error;1477}14781479/*1480* Fetch the key location. Check that we are working with an1481* encryption root.1482*/1483ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);1484if (ret != 0) {1485zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1486"Failed to get encryption root for '%s'."),1487zfs_get_name(zhp));1488goto error;1489} else if (!is_encroot) {1490zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1491"Keys must be unloaded for encryption root of '%s' (%s)."),1492zfs_get_name(zhp), prop_encroot);1493ret = EINVAL;1494goto error;1495}14961497/* check that the key is loaded */1498keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);1499if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {1500zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1501"Key already unloaded for '%s'."), zfs_get_name(zhp));1502ret = EACCES;1503goto error;1504}15051506/* call the ioctl */1507ret = lzc_unload_key(zhp->zfs_name);15081509if (ret != 0) {1510switch (ret) {1511case EPERM:1512zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1513"Permission denied."));1514break;1515case EACCES:1516zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1517"Key already unloaded for '%s'."),1518zfs_get_name(zhp));1519break;1520case EBUSY:1521zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1522"'%s' is busy."), zfs_get_name(zhp));1523break;1524}1525zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);1526}15271528return (ret);15291530error:1531zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);1532return (ret);1533}15341535static int1536zfs_crypto_verify_rewrap_nvlist(zfs_handle_t *zhp, nvlist_t *props,1537nvlist_t **props_out, char *errbuf)1538{1539int ret;1540nvpair_t *elem = NULL;1541zfs_prop_t prop;1542nvlist_t *new_props = NULL;15431544new_props = fnvlist_alloc();15451546/*1547* loop through all provided properties, we should only have1548* keyformat, keylocation and pbkdf2iters. The actual validation of1549* values is done by zfs_valid_proplist().1550*/1551while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {1552const char *propname = nvpair_name(elem);1553prop = zfs_name_to_prop(propname);15541555switch (prop) {1556case ZFS_PROP_PBKDF2_ITERS:1557case ZFS_PROP_KEYFORMAT:1558case ZFS_PROP_KEYLOCATION:1559break;1560default:1561ret = EINVAL;1562zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1563"Only keyformat, keylocation and pbkdf2iters may "1564"be set with this command."));1565goto error;1566}1567}15681569new_props = zfs_valid_proplist(zhp->zfs_hdl, zhp->zfs_type, props,1570zfs_prop_get_int(zhp, ZFS_PROP_ZONED), NULL, zhp->zpool_hdl,1571B_TRUE, errbuf);1572if (new_props == NULL) {1573ret = EINVAL;1574goto error;1575}15761577*props_out = new_props;1578return (0);15791580error:1581nvlist_free(new_props);1582*props_out = NULL;1583return (ret);1584}15851586int1587zfs_crypto_rewrap(zfs_handle_t *zhp, nvlist_t *raw_props, boolean_t inheritkey)1588{1589int ret;1590char errbuf[ERRBUFLEN];1591boolean_t is_encroot;1592nvlist_t *props = NULL;1593uint8_t *wkeydata = NULL;1594uint_t wkeylen = 0;1595dcp_cmd_t cmd = (inheritkey) ? DCP_CMD_INHERIT : DCP_CMD_NEW_KEY;1596uint64_t crypt, pcrypt, keystatus, pkeystatus;1597uint64_t keyformat = ZFS_KEYFORMAT_NONE;1598zfs_handle_t *pzhp = NULL;1599const char *keylocation = NULL;1600char origin_name[MAXNAMELEN];1601char prop_keylocation[MAXNAMELEN];1602char parent_name[ZFS_MAX_DATASET_NAME_LEN];16031604(void) snprintf(errbuf, sizeof (errbuf),1605dgettext(TEXT_DOMAIN, "Key change error"));16061607/* check that encryption is enabled for the pool */1608if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {1609zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1610"Encryption feature not enabled."));1611ret = EINVAL;1612goto error;1613}16141615/* get crypt from dataset */1616crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);1617if (crypt == ZIO_CRYPT_OFF) {1618zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1619"Dataset not encrypted."));1620ret = EINVAL;1621goto error;1622}16231624/* get the encryption root of the dataset */1625ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);1626if (ret != 0) {1627zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1628"Failed to get encryption root for '%s'."),1629zfs_get_name(zhp));1630goto error;1631}16321633/* Clones use their origin's key and cannot rewrap it */1634ret = zfs_prop_get(zhp, ZFS_PROP_ORIGIN, origin_name,1635sizeof (origin_name), NULL, NULL, 0, B_TRUE);1636if (ret == 0 && strcmp(origin_name, "") != 0) {1637zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1638"Keys cannot be changed on clones."));1639ret = EINVAL;1640goto error;1641}16421643/*1644* If the user wants to use the inheritkey variant of this function1645* we don't need to collect any crypto arguments.1646*/1647if (!inheritkey) {1648/* validate the provided properties */1649ret = zfs_crypto_verify_rewrap_nvlist(zhp, raw_props, &props,1650errbuf);1651if (ret != 0)1652goto error;16531654/*1655* Load keyformat and keylocation from the nvlist. Fetch from1656* the dataset properties if not specified.1657*/1658(void) nvlist_lookup_uint64(props,1659zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);1660(void) nvlist_lookup_string(props,1661zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);16621663if (is_encroot) {1664/*1665* If this is already an encryption root, just keep1666* any properties not set by the user.1667*/1668if (keyformat == ZFS_KEYFORMAT_NONE) {1669keyformat = zfs_prop_get_int(zhp,1670ZFS_PROP_KEYFORMAT);1671ret = nvlist_add_uint64(props,1672zfs_prop_to_name(ZFS_PROP_KEYFORMAT),1673keyformat);1674if (ret != 0) {1675zfs_error_aux(zhp->zfs_hdl,1676dgettext(TEXT_DOMAIN, "Failed to "1677"get existing keyformat "1678"property."));1679goto error;1680}1681}16821683if (keylocation == NULL) {1684ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,1685prop_keylocation, sizeof (prop_keylocation),1686NULL, NULL, 0, B_TRUE);1687if (ret != 0) {1688zfs_error_aux(zhp->zfs_hdl,1689dgettext(TEXT_DOMAIN, "Failed to "1690"get existing keylocation "1691"property."));1692goto error;1693}16941695keylocation = prop_keylocation;1696}1697} else {1698/* need a new key for non-encryption roots */1699if (keyformat == ZFS_KEYFORMAT_NONE) {1700ret = EINVAL;1701zfs_error_aux(zhp->zfs_hdl,1702dgettext(TEXT_DOMAIN, "Keyformat required "1703"for new encryption root."));1704goto error;1705}17061707/* default to prompt if no keylocation is specified */1708if (keylocation == NULL) {1709keylocation = "prompt";1710ret = nvlist_add_string(props,1711zfs_prop_to_name(ZFS_PROP_KEYLOCATION),1712keylocation);1713if (ret != 0)1714goto error;1715}1716}17171718/* fetch the new wrapping key and associated properties */1719ret = populate_create_encryption_params_nvlists(zhp->zfs_hdl,1720zhp, B_TRUE, keyformat, keylocation, props, &wkeydata,1721&wkeylen);1722if (ret != 0)1723goto error;1724} else {1725/* check that zhp is an encryption root */1726if (!is_encroot) {1727zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1728"Key inheritting can only be performed on "1729"encryption roots."));1730ret = EINVAL;1731goto error;1732}17331734/* get the parent's name */1735ret = zfs_parent_name(zhp, parent_name, sizeof (parent_name));1736if (ret != 0) {1737zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1738"Root dataset cannot inherit key."));1739ret = EINVAL;1740goto error;1741}17421743/* get a handle to the parent */1744pzhp = make_dataset_handle(zhp->zfs_hdl, parent_name);1745if (pzhp == NULL) {1746zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1747"Failed to lookup parent."));1748ret = ENOENT;1749goto error;1750}17511752/* parent must be encrypted */1753pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);1754if (pcrypt == ZIO_CRYPT_OFF) {1755zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,1756"Parent must be encrypted."));1757ret = EINVAL;1758goto error;1759}17601761/* check that the parent's key is loaded */1762pkeystatus = zfs_prop_get_int(pzhp, ZFS_PROP_KEYSTATUS);1763if (pkeystatus == ZFS_KEYSTATUS_UNAVAILABLE) {1764zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,1765"Parent key must be loaded."));1766ret = EACCES;1767goto error;1768}1769}17701771/* check that the key is loaded */1772keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);1773if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {1774zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1775"Key must be loaded."));1776ret = EACCES;1777goto error;1778}17791780/* call the ioctl */1781ret = lzc_change_key(zhp->zfs_name, cmd, props, wkeydata, wkeylen);1782if (ret != 0) {1783switch (ret) {1784case EPERM:1785zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1786"Permission denied."));1787break;1788case EINVAL:1789zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1790"Invalid properties for key change."));1791break;1792case EACCES:1793zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,1794"Key is not currently loaded."));1795break;1796}1797zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);1798}17991800if (pzhp != NULL)1801zfs_close(pzhp);1802if (props != NULL)1803nvlist_free(props);1804if (wkeydata != NULL)1805free(wkeydata);18061807return (ret);18081809error:1810if (pzhp != NULL)1811zfs_close(pzhp);1812if (props != NULL)1813nvlist_free(props);1814if (wkeydata != NULL)1815free(wkeydata);18161817zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);1818return (ret);1819}18201821boolean_t1822zfs_is_encrypted(zfs_handle_t *zhp)1823{1824uint8_t flags = zhp->zfs_dmustats.dds_flags;18251826if (flags & DDS_FLAG_HAS_ENCRYPTED)1827return ((flags & DDS_FLAG_ENCRYPTED) != 0);18281829return (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF);1830}183118321833