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