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