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