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