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