xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_crypto.c (revision 142d813a06c6f9a6142e2c276b62129a17a31a65)
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  */
19 
20 #include <string.h>
21 #include <strings.h>
22 #include <ctype.h>
23 #include <unistd.h>
24 #include <sys/zfs_context.h>
25 #include <sys/fs/zfs.h>
26 #include <sys/dsl_crypt.h>
27 #ifdef sun
28 #include <kmfapi.h>
29 #include <security/pkcs11.h>
30 #include <cryptoutil.h>
31 #else
32 #include <sys/crypto/icp.h>
33 #endif
34 #include <libintl.h>
35 #include <termios.h>
36 #include <signal.h>
37 #include <errno.h>
38 #include <libzfs.h>
39 #include "libzfs_impl.h"
40 #include "zfeature_common.h"
41 
42 /*
43  * User keys are used to decrypt the master encryption keys of a dataset. This
44  * indirection allows a user to change his / her access key without having to
45  * re-encrypt the entire dataset. User keys can be provided in one of several
46  * ways. Raw keys are simply given to the kernel as is. Similarly, hex keys
47  * are converted to binary and passed into the kernel. Password based keys are
48  * a bit more complicated. Passwords alone do not provide suitable entropy for
49  * encryption and may be too short or too long to be used. In order to derive
50  * a more appropriate key we use a PBKDF2 function. This function is designed
51  * to take a (relatively) long time to calculate in order to discourage
52  * attackers from guessing from a list of common passwords. PBKDF2 requires
53  * 2 additional parameters. The first is the number of iterations to run, which
54  * will ultimately determine how long it takes to derive the resulting key from
55  * the password. The second parameter is a salt that is randomly generated for
56  * each dataset. The salt is used to "tweak" PBKDF2 such that a group of
57  * attackers cannot reasonably generate a table of commonly known passwords to
58  * their output keys and expect it work for all past and future PBKDF2 users.
59  * We store the salt as a hidden property of the dataset (although it is
60  * technically ok if the salt is known to the attacker).
61  */
62 
63 typedef enum key_locator {
64 	KEY_LOCATOR_NONE,
65 	KEY_LOCATOR_PROMPT,
66 	KEY_LOCATOR_URI
67 } key_locator_t;
68 
69 #define	MIN_PASSPHRASE_LEN 8
70 #define	MAX_PASSPHRASE_LEN 512
71 #define	MAX_KEY_PROMPT_ATTEMPTS 3
72 
73 static int caught_interrupt;
74 
75 static zfs_keylocation_t
76 zfs_prop_parse_keylocation(const char *str)
77 {
78 	if (strcmp("prompt", str) == 0)
79 		return (ZFS_KEYLOCATION_PROMPT);
80 	else if (strlen(str) > 8 && strncmp("file:///", str, 8) == 0)
81 		return (ZFS_KEYLOCATION_URI);
82 
83 	return (ZFS_KEYLOCATION_NONE);
84 }
85 
86 static int
87 hex_key_to_raw(char *hex, int hexlen, uint8_t *out)
88 {
89 	int ret, i;
90 	unsigned int c;
91 
92 	for (i = 0; i < hexlen; i += 2) {
93 		if (!isxdigit(hex[i]) || !isxdigit(hex[i + 1])) {
94 			ret = EINVAL;
95 			goto error;
96 		}
97 
98 		ret = sscanf(&hex[i], "%02x", &c);
99 		if (ret != 1) {
100 			ret = EINVAL;
101 			goto error;
102 		}
103 
104 		out[i / 2] = c;
105 	}
106 
107 	return (0);
108 
109 error:
110 	return (ret);
111 }
112 
113 
114 static void
115 catch_signal(int sig)
116 {
117 	caught_interrupt = sig;
118 }
119 
120 static char *
121 get_format_prompt_string(zfs_keyformat_t format)
122 {
123 	switch (format) {
124 	case ZFS_KEYFORMAT_RAW:
125 		return ("raw key");
126 	case ZFS_KEYFORMAT_HEX:
127 		return ("hex key");
128 	case ZFS_KEYFORMAT_PASSPHRASE:
129 		return ("passphrase");
130 	default:
131 		/* shouldn't happen */
132 		return (NULL);
133 	}
134 }
135 
136 static int
137 get_key_material_raw(FILE *fd, const char *fsname, zfs_keyformat_t keyformat,
138     boolean_t again, boolean_t newkey, uint8_t **buf, size_t *len_out)
139 {
140 	int ret = 0, bytes;
141 	size_t buflen = 0;
142 	struct termios old_term, new_term;
143 	struct sigaction act, osigint, osigtstp;
144 
145 	*len_out = 0;
146 
147 	if (isatty(fileno(fd))) {
148 		/*
149 		 * handle SIGINT and ignore SIGSTP. This is necessary to
150 		 * restore the state of the terminal.
151 		 */
152 		caught_interrupt = 0;
153 		act.sa_flags = 0;
154 		(void) sigemptyset(&act.sa_mask);
155 		act.sa_handler = catch_signal;
156 
157 		(void) sigaction(SIGINT, &act, &osigint);
158 		act.sa_handler = SIG_IGN;
159 		(void) sigaction(SIGTSTP, &act, &osigtstp);
160 
161 		/* prompt for the key */
162 		if (fsname != NULL) {
163 			(void) printf("%s %s%s for '%s': ",
164 			    (again) ? "Re-enter" : "Enter",
165 			    (newkey) ? "new " : "",
166 			    get_format_prompt_string(
167 			    (zfs_keyformat_t)keyformat),
168 			    fsname);
169 		} else {
170 			(void) printf("%s %s%s: ",
171 			    (again) ? "Re-enter" : "Enter",
172 			    (newkey) ? "new " : "",
173 			    get_format_prompt_string(
174 			    (zfs_keyformat_t)keyformat));
175 
176 		}
177 		(void) fflush(stdout);
178 
179 		/* disable the terminal echo for key input */
180 		(void) tcgetattr(fileno(fd), &old_term);
181 
182 		new_term = old_term;
183 		new_term.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
184 
185 		ret = tcsetattr(fileno(fd), TCSAFLUSH, &new_term);
186 		if (ret != 0) {
187 			ret = errno;
188 			errno = 0;
189 			goto out;
190 		}
191 	}
192 
193 	/* read the key material */
194 	if (keyformat != ZFS_KEYFORMAT_RAW) {
195 		bytes = getline((char **)buf, &buflen, fd);
196 		if (bytes < 0) {
197 			ret = errno;
198 			errno = 0;
199 			goto out;
200 		}
201 
202 		/* trim the ending newline if it exists */
203 		if ((*buf)[bytes - 1] == '\n') {
204 			(*buf)[bytes - 1] = '\0';
205 			bytes--;
206 		}
207 	} else {
208 		/*
209 		 * Raw keys may have newline characters in them and so can't
210 		 * use getline(). Here we attempt to read 33 bytes so that we
211 		 * can properly check the key length (the file should only have
212 		 * 32 bytes).
213 		 */
214 		*buf = malloc((WRAPPING_KEY_LEN + 1) * sizeof (char));
215 		if (*buf == NULL) {
216 			ret = ENOMEM;
217 			goto out;
218 		}
219 
220 		bytes = fread(*buf, 1, WRAPPING_KEY_LEN + 1, fd);
221 		if (bytes < 0) {
222 			/* size errors are handled by the calling function */
223 			free(*buf);
224 			*buf = NULL;
225 			ret = errno;
226 			errno = 0;
227 			goto out;
228 		}
229 	}
230 
231 	*len_out = bytes;
232 
233 out:
234 	if (isatty(fileno(fd))) {
235 		/* reset the teminal */
236 		(void) tcsetattr(fileno(fd), TCSAFLUSH, &old_term);
237 		(void) sigaction(SIGINT, &osigint, NULL);
238 		(void) sigaction(SIGTSTP, &osigtstp, NULL);
239 
240 		/* if we caught a signal, re-throw it now */
241 		if (caught_interrupt != 0) {
242 			(void) kill(getpid(), caught_interrupt);
243 		}
244 
245 		/* print the newline that was not echo'd */
246 		(void) printf("\n");
247 	}
248 
249 	return (ret);
250 
251 }
252 
253 /*
254  * Attempts to fetch key material, no matter where it might live. The key
255  * material is allocated and returned in km_out. *can_retry_out will be set
256  * to B_TRUE if the user is providing the key material interactively, allowing
257  * for re-entry attempts.
258  */
259 static int
260 get_key_material(libzfs_handle_t *hdl, boolean_t do_verify, boolean_t newkey,
261     zfs_keyformat_t keyformat, char *keylocation, const char *fsname,
262     uint8_t **km_out, size_t *kmlen_out, boolean_t *can_retry_out)
263 {
264 	int ret, i;
265 	zfs_keylocation_t keyloc = ZFS_KEYLOCATION_NONE;
266 	FILE *fd = NULL;
267 	uint8_t *km = NULL, *km2 = NULL;
268 	size_t kmlen, kmlen2;
269 	boolean_t can_retry = B_FALSE;
270 
271 	/* verify and parse the keylocation */
272 	keyloc = zfs_prop_parse_keylocation(keylocation);
273 
274 	/* open the appropriate file descriptor */
275 	switch (keyloc) {
276 	case ZFS_KEYLOCATION_PROMPT:
277 		fd = stdin;
278 		if (isatty(fileno(fd))) {
279 			can_retry = B_TRUE;
280 
281 			/* raw keys cannot be entered on the terminal */
282 			if (keyformat == ZFS_KEYFORMAT_RAW) {
283 				ret = EINVAL;
284 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
285 				    "Cannot enter raw keys on the terminal"));
286 				goto error;
287 			}
288 		}
289 		break;
290 	case ZFS_KEYLOCATION_URI:
291 		fd = fopen(&keylocation[7], "r");
292 		if (!fd) {
293 			ret = errno;
294 			errno = 0;
295 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
296 			    "Failed to open key material file"));
297 			goto error;
298 		}
299 		break;
300 	default:
301 		ret = EINVAL;
302 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
303 		    "Invalid keylocation."));
304 		goto error;
305 	}
306 
307 	/* fetch the key material into the buffer */
308 	ret = get_key_material_raw(fd, fsname, keyformat, B_FALSE, newkey,
309 	    &km, &kmlen);
310 	if (ret != 0)
311 		goto error;
312 
313 	/* do basic validation of the key material */
314 	switch (keyformat) {
315 	case ZFS_KEYFORMAT_RAW:
316 		/* verify the key length is correct */
317 		if (kmlen < WRAPPING_KEY_LEN) {
318 			ret = EINVAL;
319 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
320 			    "Raw key too short (expected %u)."),
321 			    WRAPPING_KEY_LEN);
322 			goto error;
323 		}
324 
325 		if (kmlen > WRAPPING_KEY_LEN) {
326 			ret = EINVAL;
327 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
328 			    "Raw key too long (expected %u)."),
329 			    WRAPPING_KEY_LEN);
330 			goto error;
331 		}
332 		break;
333 	case ZFS_KEYFORMAT_HEX:
334 		/* verify the key length is correct */
335 		if (kmlen < WRAPPING_KEY_LEN * 2) {
336 			ret = EINVAL;
337 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
338 			    "Hex key too short (expected %u)."),
339 			    WRAPPING_KEY_LEN * 2);
340 			goto error;
341 		}
342 
343 		if (kmlen > WRAPPING_KEY_LEN * 2) {
344 			ret = EINVAL;
345 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
346 			    "Hex key too long (expected %u)."),
347 			    WRAPPING_KEY_LEN * 2);
348 			goto error;
349 		}
350 
351 		/* check for invalid hex digits */
352 		for (i = 0; i < WRAPPING_KEY_LEN * 2; i++) {
353 			if (!isxdigit((char)km[i])) {
354 				ret = EINVAL;
355 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
356 				    "Invalid hex character detected."));
357 				goto error;
358 			}
359 		}
360 		break;
361 	case ZFS_KEYFORMAT_PASSPHRASE:
362 		/* verify the length is within bounds */
363 		if (kmlen > MAX_PASSPHRASE_LEN) {
364 			ret = EINVAL;
365 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
366 			    "Passphrase too long (max %u)."),
367 			    MAX_PASSPHRASE_LEN);
368 			goto error;
369 		}
370 
371 		if (kmlen < MIN_PASSPHRASE_LEN) {
372 			ret = EINVAL;
373 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
374 			    "Passphrase too short (min %u)."),
375 			    MIN_PASSPHRASE_LEN);
376 			goto error;
377 		}
378 		break;
379 	default:
380 		/* can't happen, checked above */
381 		break;
382 	}
383 
384 	if (do_verify && isatty(fileno(fd))) {
385 		ret = get_key_material_raw(fd, fsname, keyformat, B_TRUE,
386 		    newkey, &km2, &kmlen2);
387 		if (ret != 0)
388 			goto error;
389 
390 		if (kmlen2 != kmlen ||
391 		    (memcmp((char *)km, (char *)km2, kmlen) != 0)) {
392 			ret = EINVAL;
393 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
394 			    "Provided keys do not match."));
395 			goto error;
396 		}
397 	}
398 
399 	if (fd != stdin)
400 		(void) fclose(fd);
401 
402 	if (km2 != NULL)
403 		free(km2);
404 
405 	*km_out = km;
406 	*kmlen_out = kmlen;
407 	if (can_retry_out != NULL)
408 		*can_retry_out = can_retry;
409 
410 	return (0);
411 
412 error:
413 	if (km != NULL)
414 		free(km);
415 
416 	if (km2 != NULL)
417 		free(km2);
418 
419 	if (fd != NULL && fd != stdin)
420 		(void) fclose(fd);
421 
422 	*km_out = NULL;
423 	*kmlen_out = 0;
424 
425 	if (can_retry_out != NULL)
426 		*can_retry_out = can_retry;
427 
428 	return (ret);
429 }
430 
431 /* This needs to be fixed to be compatible with other platforms */
432 
433 static int
434 pbkdf2(uint8_t *passphrase, size_t passphraselen, uint8_t *salt,
435     size_t saltlen, uint64_t iterations, uint8_t *output,
436     size_t outputlen)
437 {
438 	int ret = 0;
439 	CK_SESSION_HANDLE session;
440 	char *tmpkeydata = NULL;
441 	size_t tmpkeydatalen = 0;
442 	CK_OBJECT_HANDLE obj;
443 
444 	/* initialize output */
445 	(void) memset(output, 0, outputlen);
446 
447 	ret = SUNW_C_GetMechSession(CKM_PKCS5_PBKD2, &session);
448 	if (ret) {
449 		(void) fprintf(stderr, "failed to connect to pkcs5: %s\n",
450 		    pkcs11_strerror(ret));
451 		return (ret);
452 	}
453 
454 	ret = pkcs11_PasswdToPBKD2Object(session, (char *)passphrase,
455 	    passphraselen, salt, saltlen, iterations, CKK_AES, outputlen, 0,
456 	    &obj);
457 
458 	if (ret == CKR_OK)
459 		ret = pkcs11_ObjectToKey(session, obj, (void **)&tmpkeydata,
460 		    &tmpkeydatalen, B_TRUE);
461 
462 	(void) C_CloseSession(session);
463 	if (ret) {
464 		(void) fprintf(stderr, "unable to generate key: %s\n",
465 		    pkcs11_strerror(ret));
466 		return (ret);
467 	}
468 
469 	/*
470 	 * Because it allocates an area for the passphrase, we copy it out
471 	 * then zero the original
472 	 */
473 	(void) memcpy(output, tmpkeydata, tmpkeydatalen);
474 	(void) memset(tmpkeydata, 0, tmpkeydatalen);
475 	free(tmpkeydata);
476 
477 	return (ret);
478 }
479 
480 /* ARGSUSED */
481 static int
482 derive_key(libzfs_handle_t *hdl, zfs_keyformat_t format, uint64_t iters,
483     uint8_t *key_material, size_t key_material_len, uint64_t salt,
484     uint8_t **key_out)
485 {
486 	int ret;
487 	uint8_t *key;
488 
489 	*key_out = NULL;
490 
491 	key = zfs_alloc(hdl, WRAPPING_KEY_LEN);
492 	if (!key)
493 		return (ENOMEM);
494 
495 	switch (format) {
496 	case ZFS_KEYFORMAT_RAW:
497 		bcopy(key_material, key, WRAPPING_KEY_LEN);
498 		break;
499 	case ZFS_KEYFORMAT_HEX:
500 		ret = hex_key_to_raw((char *)key_material,
501 		    WRAPPING_KEY_LEN * 2, key);
502 		if (ret != 0) {
503 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
504 			    "Invalid hex key provided."));
505 			goto error;
506 		}
507 		break;
508 	case ZFS_KEYFORMAT_PASSPHRASE:
509 		salt = LE_64(salt);
510 		ret = pbkdf2(key_material, strlen((char *)key_material),
511 		    ((uint8_t *)&salt), sizeof (uint64_t), iters,
512 		    key, WRAPPING_KEY_LEN);
513 		if (ret != 0) {
514 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
515 			    "Failed to generate key from passphrase."));
516 			goto error;
517 		}
518 		break;
519 	default:
520 		ret = EINVAL;
521 		goto error;
522 	}
523 
524 	*key_out = key;
525 	return (0);
526 
527 error:
528 	free(key);
529 
530 	*key_out = NULL;
531 	return (ret);
532 }
533 
534 static boolean_t
535 encryption_feature_is_enabled(zpool_handle_t *zph)
536 {
537 	nvlist_t *features;
538 	uint64_t feat_refcount;
539 
540 	/* check that features can be enabled */
541 	if (zpool_get_prop_int(zph, ZPOOL_PROP_VERSION, NULL)
542 	    < SPA_VERSION_FEATURES)
543 		return (B_FALSE);
544 
545 	/* check for crypto feature */
546 	features = zpool_get_features(zph);
547 	if (!features || nvlist_lookup_uint64(features,
548 	    spa_feature_table[SPA_FEATURE_ENCRYPTION].fi_guid,
549 	    &feat_refcount) != 0)
550 		return (B_FALSE);
551 
552 	return (B_TRUE);
553 }
554 
555 static int
556 populate_create_encryption_params_nvlists(libzfs_handle_t *hdl,
557     zfs_handle_t *zhp, boolean_t newkey, zfs_keyformat_t keyformat,
558     char *keylocation, nvlist_t *props, uint8_t **wkeydata, uint_t *wkeylen)
559 {
560 	int ret;
561 	uint64_t iters = 0, salt = 0;
562 	uint8_t *key_material = NULL;
563 	size_t key_material_len = 0;
564 	uint8_t *key_data = NULL;
565 	const char *fsname = (zhp) ? zfs_get_name(zhp) : NULL;
566 
567 	/* get key material from keyformat and keylocation */
568 	ret = get_key_material(hdl, B_TRUE, newkey, keyformat, keylocation,
569 	    fsname, &key_material, &key_material_len, NULL);
570 	if (ret != 0)
571 		goto error;
572 
573 	/* passphrase formats require a salt and pbkdf2 iters property */
574 	if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
575 #ifdef sun
576 		/* always generate a new salt */
577 		ret = pkcs11_get_random(&salt, sizeof (uint64_t));
578 		if (ret != 0) {
579 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
580 			    "Failed to generate salt."));
581 			goto error;
582 		}
583 #else
584 		random_init();
585 
586 		ret = random_get_bytes((uint8_t *)&salt, sizeof (uint64_t));
587 		if (ret != 0) {
588 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
589 			    "Failed to generate salt."));
590 			goto error;
591 		}
592 
593 		random_fini();
594 #endif
595 
596 		ret = nvlist_add_uint64(props,
597 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt);
598 		if (ret != 0) {
599 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
600 			    "Failed to add salt to properties."));
601 			goto error;
602 		}
603 
604 		/*
605 		 * If not otherwise specified, use the default number of
606 		 * pbkdf2 iterations. If specified, we have already checked
607 		 * that the given value is greater than MIN_PBKDF2_ITERATIONS
608 		 * during zfs_valid_proplist().
609 		 */
610 		ret = nvlist_lookup_uint64(props,
611 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
612 		if (ret == ENOENT) {
613 			iters = DEFAULT_PBKDF2_ITERATIONS;
614 			ret = nvlist_add_uint64(props,
615 			    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), iters);
616 			if (ret != 0)
617 				goto error;
618 		} else if (ret != 0) {
619 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
620 			    "Failed to get pbkdf2 iterations."));
621 			goto error;
622 		}
623 	} else {
624 		/* check that pbkdf2iters was not specified by the user */
625 		ret = nvlist_lookup_uint64(props,
626 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
627 		if (ret == 0) {
628 			ret = EINVAL;
629 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
630 			    "Cannot specify pbkdf2iters with a non-passphrase "
631 			    "keyformat."));
632 			goto error;
633 		}
634 	}
635 
636 	/* derive a key from the key material */
637 	ret = derive_key(hdl, (zfs_keyformat_t)keyformat, iters, key_material,
638 	    key_material_len, salt, &key_data);
639 	if (ret != 0)
640 		goto error;
641 
642 	free(key_material);
643 
644 	*wkeydata = key_data;
645 	*wkeylen = WRAPPING_KEY_LEN;
646 	return (0);
647 
648 error:
649 	if (key_material != NULL)
650 		free(key_material);
651 	if (key_data != NULL)
652 		free(key_data);
653 
654 	*wkeydata = NULL;
655 	*wkeylen = 0;
656 	return (ret);
657 }
658 
659 static boolean_t
660 proplist_has_encryption_props(nvlist_t *props)
661 {
662 	int ret;
663 	uint64_t intval;
664 	char *strval;
665 
666 	ret = nvlist_lookup_uint64(props,
667 	    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &intval);
668 	if (ret == 0 && intval != ZIO_CRYPT_OFF)
669 		return (B_TRUE);
670 
671 	ret = nvlist_lookup_string(props,
672 	    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &strval);
673 	if (ret == 0 && strcmp(strval, "none") != 0)
674 		return (B_TRUE);
675 
676 	ret = nvlist_lookup_uint64(props,
677 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &intval);
678 	if (ret == 0)
679 		return (B_TRUE);
680 
681 	ret = nvlist_lookup_uint64(props,
682 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &intval);
683 	if (ret == 0)
684 		return (B_TRUE);
685 
686 	return (B_FALSE);
687 }
688 
689 int
690 zfs_crypto_get_encryption_root(zfs_handle_t *zhp, boolean_t *is_encroot,
691     char *buf)
692 {
693 	int ret;
694 	char prop_encroot[MAXNAMELEN];
695 
696 	/* if the dataset isn't encrypted, just return */
697 	if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) == ZIO_CRYPT_OFF) {
698 		*is_encroot = B_FALSE;
699 		if (buf != NULL)
700 			buf[0] = '\0';
701 		return (0);
702 	}
703 
704 	ret = zfs_prop_get(zhp, ZFS_PROP_ENCRYPTION_ROOT, prop_encroot,
705 	    sizeof (prop_encroot), NULL, NULL, 0, B_TRUE);
706 	if (ret != 0) {
707 		*is_encroot = B_FALSE;
708 		if (buf != NULL)
709 			buf[0] = '\0';
710 		return (ret);
711 	}
712 
713 	*is_encroot = strcmp(prop_encroot, zfs_get_name(zhp)) == 0;
714 	if (buf != NULL)
715 		(void) strcpy(buf, prop_encroot);
716 
717 	return (0);
718 }
719 
720 int
721 zfs_crypto_create(libzfs_handle_t *hdl, char *parent_name, nvlist_t *props,
722     nvlist_t *pool_props, uint8_t **wkeydata_out, uint_t *wkeylen_out)
723 {
724 	int ret;
725 	uint64_t crypt = ZIO_CRYPT_INHERIT, pcrypt = ZIO_CRYPT_INHERIT;
726 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
727 	char *keylocation = NULL;
728 	zfs_handle_t *pzhp = NULL;
729 	uint8_t *wkeydata = NULL;
730 	uint_t wkeylen = 0;
731 	boolean_t local_crypt = B_TRUE;
732 
733 	/* lookup crypt from props */
734 	ret = nvlist_lookup_uint64(props,
735 	    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &crypt);
736 	if (ret != 0)
737 		local_crypt = B_FALSE;
738 
739 	/* lookup key location and format from props */
740 	(void) nvlist_lookup_uint64(props,
741 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
742 	(void) nvlist_lookup_string(props,
743 	    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
744 
745 	if (parent_name != NULL) {
746 		/* get a reference to parent dataset */
747 		pzhp = make_dataset_handle(hdl, parent_name);
748 		if (pzhp == NULL) {
749 			ret = ENOENT;
750 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
751 			    "Failed to lookup parent."));
752 			goto out;
753 		}
754 
755 		/* Lookup parent's crypt */
756 		pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
757 
758 		/* Params require the encryption feature */
759 		if (!encryption_feature_is_enabled(pzhp->zpool_hdl)) {
760 			if (proplist_has_encryption_props(props)) {
761 				ret = EINVAL;
762 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
763 				    "Encryption feature not enabled."));
764 				goto out;
765 			}
766 
767 			ret = 0;
768 			goto out;
769 		}
770 	} else {
771 		/*
772 		 * special case for root dataset where encryption feature
773 		 * feature won't be on disk yet
774 		 */
775 		if (!nvlist_exists(pool_props, "feature@encryption")) {
776 			if (proplist_has_encryption_props(props)) {
777 				ret = EINVAL;
778 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
779 				    "Encryption feature not enabled."));
780 				goto out;
781 			}
782 
783 			ret = 0;
784 			goto out;
785 		}
786 
787 		pcrypt = ZIO_CRYPT_OFF;
788 	}
789 
790 	/* Get the inherited encryption property if we don't have it locally */
791 	if (!local_crypt)
792 		crypt = pcrypt;
793 
794 	/*
795 	 * At this point crypt should be the actual encryption value. If
796 	 * encryption is off just verify that no encryption properties have
797 	 * been specified and return.
798 	 */
799 	if (crypt == ZIO_CRYPT_OFF) {
800 		if (proplist_has_encryption_props(props)) {
801 			ret = EINVAL;
802 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
803 			    "Encryption must be turned on to set encryption "
804 			    "properties."));
805 			goto out;
806 		}
807 
808 		ret = 0;
809 		goto out;
810 	}
811 
812 	/*
813 	 * If we have a parent crypt it is valid to specify encryption alone.
814 	 * This will result in a child that is encrypted with the chosen
815 	 * encryption suite that will also inherit the parent's key. If
816 	 * the parent is not encrypted we need an encryption suite provided.
817 	 */
818 	if (pcrypt == ZIO_CRYPT_OFF && keylocation == NULL &&
819 	    keyformat == ZFS_KEYFORMAT_NONE) {
820 		ret = EINVAL;
821 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
822 		    "Keyformat required for new encryption root."));
823 		goto out;
824 	}
825 
826 	/*
827 	 * Specifying a keylocation implies this will be a new encryption root.
828 	 * Check that a keyformat is also specified.
829 	 */
830 	if (keylocation != NULL && keyformat == ZFS_KEYFORMAT_NONE) {
831 		ret = EINVAL;
832 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
833 		    "Keyformat required for new encryption root."));
834 		goto out;
835 	}
836 
837 	/* default to prompt if no keylocation is specified */
838 	if (keyformat != ZFS_KEYFORMAT_NONE && keylocation == NULL) {
839 		keylocation = "prompt";
840 		ret = nvlist_add_string(props,
841 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), keylocation);
842 		if (ret != 0)
843 			goto out;
844 	}
845 
846 	/*
847 	 * If a local key is provided, this dataset will be a new
848 	 * encryption root. Populate the encryption params.
849 	 */
850 	if (keylocation != NULL) {
851 		ret = populate_create_encryption_params_nvlists(hdl, NULL,
852 		    B_FALSE, keyformat, keylocation, props, &wkeydata,
853 		    &wkeylen);
854 		if (ret != 0)
855 			goto out;
856 	}
857 
858 	if (pzhp != NULL)
859 		zfs_close(pzhp);
860 
861 	*wkeydata_out = wkeydata;
862 	*wkeylen_out = wkeylen;
863 	return (0);
864 
865 out:
866 	if (pzhp != NULL)
867 		zfs_close(pzhp);
868 	if (wkeydata != NULL)
869 		free(wkeydata);
870 
871 	*wkeydata_out = NULL;
872 	*wkeylen_out = 0;
873 	return (ret);
874 }
875 
876 int
877 zfs_crypto_clone_check(libzfs_handle_t *hdl, zfs_handle_t *origin_zhp,
878     char *parent_name, nvlist_t *props)
879 {
880 	/*
881 	 * No encryption properties should be specified. They will all be
882 	 * inherited from the origin dataset.
883 	 */
884 	if (nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYFORMAT)) ||
885 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYLOCATION)) ||
886 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_ENCRYPTION)) ||
887 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS))) {
888 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
889 		    "Encryption properties must inherit from origin dataset."));
890 		return (EINVAL);
891 	}
892 
893 	return (0);
894 }
895 
896 typedef struct loadkeys_cbdata {
897 	uint64_t cb_numfailed;
898 	uint64_t cb_numattempted;
899 } loadkey_cbdata_t;
900 
901 static int
902 load_keys_cb(zfs_handle_t *zhp, void *arg)
903 {
904 	int ret;
905 	boolean_t is_encroot;
906 	loadkey_cbdata_t *cb = arg;
907 	uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
908 
909 	/* only attempt to load keys for encryption roots */
910 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
911 	if (ret != 0 || !is_encroot)
912 		goto out;
913 
914 	/* don't attempt to load already loaded keys */
915 	if (keystatus == ZFS_KEYSTATUS_AVAILABLE)
916 		goto out;
917 
918 	/* Attempt to load the key. Record status in cb. */
919 	cb->cb_numattempted++;
920 
921 	ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
922 	if (ret)
923 		cb->cb_numfailed++;
924 
925 out:
926 	(void) zfs_iter_filesystems(zhp, load_keys_cb, cb);
927 	zfs_close(zhp);
928 
929 	/* always return 0, since this function is best effort */
930 	return (0);
931 }
932 
933 /*
934  * This function is best effort. It attempts to load all the keys for the given
935  * filesystem and all of its children.
936  */
937 int
938 zfs_crypto_attempt_load_keys(libzfs_handle_t *hdl, char *fsname)
939 {
940 	int ret;
941 	zfs_handle_t *zhp = NULL;
942 	loadkey_cbdata_t cb = { 0 };
943 
944 	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
945 	if (zhp == NULL) {
946 		ret = ENOENT;
947 		goto error;
948 	}
949 
950 	ret = load_keys_cb(zfs_handle_dup(zhp), &cb);
951 	if (ret)
952 		goto error;
953 
954 	(void) printf(gettext("%llu / %llu keys successfully loaded\n"),
955 	    (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
956 	    (u_longlong_t)cb.cb_numattempted);
957 
958 	if (cb.cb_numfailed != 0) {
959 		ret = -1;
960 		goto error;
961 	}
962 
963 	zfs_close(zhp);
964 	return (0);
965 
966 error:
967 	if (zhp != NULL)
968 		zfs_close(zhp);
969 	return (ret);
970 }
971 
972 int
973 zfs_crypto_load_key(zfs_handle_t *zhp, boolean_t noop, char *alt_keylocation)
974 {
975 	int ret, attempts = 0;
976 	char errbuf[1024];
977 	uint64_t keystatus, iters = 0, salt = 0;
978 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
979 	char prop_keylocation[MAXNAMELEN];
980 	char prop_encroot[MAXNAMELEN];
981 	char *keylocation = NULL;
982 	uint8_t *key_material = NULL, *key_data = NULL;
983 	size_t key_material_len;
984 	boolean_t is_encroot, can_retry = B_FALSE, correctible = B_FALSE;
985 
986 	(void) snprintf(errbuf, sizeof (errbuf),
987 	    dgettext(TEXT_DOMAIN, "Key load error"));
988 
989 	/* check that encryption is enabled for the pool */
990 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
991 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
992 		    "Encryption feature not enabled."));
993 		ret = EINVAL;
994 		goto error;
995 	}
996 
997 	/* Fetch the keyformat. Check that the dataset is encrypted. */
998 	keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
999 	if (keyformat == ZFS_KEYFORMAT_NONE) {
1000 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1001 		    "'%s' is not encrypted."), zfs_get_name(zhp));
1002 		ret = EINVAL;
1003 		goto error;
1004 	}
1005 
1006 	/*
1007 	 * Fetch the key location. Check that we are working with an
1008 	 * encryption root.
1009 	 */
1010 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1011 	if (ret != 0) {
1012 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1013 		    "Failed to get encryption root for '%s'."),
1014 		    zfs_get_name(zhp));
1015 		goto error;
1016 	} else if (!is_encroot) {
1017 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1018 		    "Keys must be loaded for encryption root of '%s' (%s)."),
1019 		    zfs_get_name(zhp), prop_encroot);
1020 		ret = EINVAL;
1021 		goto error;
1022 	}
1023 
1024 	/*
1025 	 * if the caller has elected to override the keylocation property
1026 	 * use that instead
1027 	 */
1028 	if (alt_keylocation != NULL) {
1029 		keylocation = alt_keylocation;
1030 	} else {
1031 		ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION, prop_keylocation,
1032 		    sizeof (prop_keylocation), NULL, NULL, 0, B_TRUE);
1033 		if (ret != 0) {
1034 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1035 			    "Failed to get keylocation for '%s'."),
1036 			    zfs_get_name(zhp));
1037 			goto error;
1038 		}
1039 
1040 		keylocation = prop_keylocation;
1041 	}
1042 
1043 	/* check that the key is unloaded unless this is a noop */
1044 	if (!noop) {
1045 		keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1046 		if (keystatus == ZFS_KEYSTATUS_AVAILABLE) {
1047 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1048 			    "Key already loaded for '%s'."), zfs_get_name(zhp));
1049 			ret = EEXIST;
1050 			goto error;
1051 		}
1052 	}
1053 
1054 	/* passphrase formats require a salt and pbkdf2_iters property */
1055 	if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
1056 		salt = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_SALT);
1057 		iters = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_ITERS);
1058 	}
1059 
1060 try_again:
1061 	/* fetching and deriving the key are correctible errors. set the flag */
1062 	correctible = B_TRUE;
1063 
1064 	/* get key material from key format and location */
1065 	ret = get_key_material(zhp->zfs_hdl, B_FALSE, B_FALSE, keyformat,
1066 	    keylocation, zfs_get_name(zhp), &key_material, &key_material_len,
1067 	    &can_retry);
1068 	if (ret != 0)
1069 		goto error;
1070 
1071 	/* derive a key from the key material */
1072 	ret = derive_key(zhp->zfs_hdl, keyformat, iters, key_material,
1073 	    key_material_len, salt, &key_data);
1074 	if (ret != 0)
1075 		goto error;
1076 
1077 	correctible = B_FALSE;
1078 
1079 	/* pass the wrapping key and noop flag to the ioctl */
1080 	ret = lzc_load_key(zhp->zfs_name, noop, key_data, WRAPPING_KEY_LEN);
1081 	if (ret != 0) {
1082 		switch (ret) {
1083 		case EINVAL:
1084 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1085 			    "Invalid parameters provided for %s."),
1086 			    zfs_get_name(zhp));
1087 			break;
1088 		case EEXIST:
1089 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1090 			    "Key already loaded for '%s'."), zfs_get_name(zhp));
1091 			break;
1092 		case EBUSY:
1093 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1094 			    "'%s' is busy."), zfs_get_name(zhp));
1095 			break;
1096 		case EACCES:
1097 			correctible = B_TRUE;
1098 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1099 			    "Incorrect key provided for '%s'."),
1100 			    zfs_get_name(zhp));
1101 			break;
1102 		}
1103 		goto error;
1104 	}
1105 
1106 	free(key_material);
1107 	free(key_data);
1108 
1109 	return (0);
1110 
1111 error:
1112 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1113 	if (key_material != NULL) {
1114 		free(key_material);
1115 		key_material = NULL;
1116 	}
1117 	if (key_data != NULL) {
1118 		free(key_data);
1119 		key_data  = NULL;
1120 	}
1121 
1122 	/*
1123 	 * Here we decide if it is ok to allow the user to retry entering their
1124 	 * key. The can_retry flag will be set if the user is entering their
1125 	 * key from an interactive prompt. The correctible flag will only be
1126 	 * set if an error that occured could be corrected by retrying. Both
1127 	 * flags are needed to allow the user to attempt key entry again
1128 	 */
1129 	if (can_retry && correctible && attempts <= MAX_KEY_PROMPT_ATTEMPTS) {
1130 		attempts++;
1131 		goto try_again;
1132 	}
1133 
1134 	return (ret);
1135 }
1136 
1137 int
1138 zfs_crypto_unload_key(zfs_handle_t *zhp)
1139 {
1140 	int ret;
1141 	char errbuf[1024];
1142 	char prop_encroot[MAXNAMELEN];
1143 	uint64_t keystatus, keyformat;
1144 	boolean_t is_encroot;
1145 
1146 	(void) snprintf(errbuf, sizeof (errbuf),
1147 	    dgettext(TEXT_DOMAIN, "Key unload error"));
1148 
1149 	/* check that encryption is enabled for the pool */
1150 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1151 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1152 		    "Encryption feature not enabled."));
1153 		ret = EINVAL;
1154 		goto error;
1155 	}
1156 
1157 	/* Fetch the keyformat. Check that the dataset is encrypted. */
1158 	keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
1159 	if (keyformat == ZFS_KEYFORMAT_NONE) {
1160 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1161 		    "'%s' is not encrypted."), zfs_get_name(zhp));
1162 		ret = EINVAL;
1163 		goto error;
1164 	}
1165 
1166 	/*
1167 	 * Fetch the key location. Check that we are working with an
1168 	 * encryption root.
1169 	 */
1170 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1171 	if (ret != 0) {
1172 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1173 		    "Failed to get encryption root for '%s'."),
1174 		    zfs_get_name(zhp));
1175 		goto error;
1176 	} else if (!is_encroot) {
1177 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1178 		    "Keys must be unloaded for encryption root of '%s' (%s)."),
1179 		    zfs_get_name(zhp), prop_encroot);
1180 		ret = EINVAL;
1181 		goto error;
1182 	}
1183 
1184 	/* check that the key is loaded */
1185 	keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1186 	if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1187 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1188 		    "Key already unloaded for '%s'."), zfs_get_name(zhp));
1189 		ret = EACCES;
1190 		goto error;
1191 	}
1192 
1193 	/* call the ioctl */
1194 	ret = lzc_unload_key(zhp->zfs_name);
1195 
1196 	if (ret != 0) {
1197 		switch (ret) {
1198 		case EACCES:
1199 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1200 			    "Key already unloaded for '%s'."),
1201 			    zfs_get_name(zhp));
1202 			break;
1203 		case EBUSY:
1204 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1205 			    "'%s' is busy."), zfs_get_name(zhp));
1206 			break;
1207 		}
1208 		(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1209 	}
1210 
1211 	return (ret);
1212 
1213 error:
1214 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1215 	return (ret);
1216 }
1217 
1218 static int
1219 zfs_crypto_verify_rewrap_nvlist(zfs_handle_t *zhp, nvlist_t *props,
1220     nvlist_t **props_out, char *errbuf)
1221 {
1222 	int ret;
1223 	nvpair_t *elem = NULL;
1224 	zfs_prop_t prop;
1225 	nvlist_t *new_props = NULL;
1226 
1227 	new_props = fnvlist_alloc();
1228 
1229 	/*
1230 	 * loop through all provided properties, we should only have
1231 	 * keyformat, keylocation and pbkdf2iters. The actual validation of
1232 	 * values is done by zfs_valid_proplist().
1233 	 */
1234 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
1235 		const char *propname = nvpair_name(elem);
1236 		prop = zfs_name_to_prop(propname);
1237 
1238 		switch (prop) {
1239 		case ZFS_PROP_PBKDF2_ITERS:
1240 		case ZFS_PROP_KEYFORMAT:
1241 		case ZFS_PROP_KEYLOCATION:
1242 			break;
1243 		default:
1244 			ret = EINVAL;
1245 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1246 			    "Only keyformat, keylocation and pbkdf2iters may "
1247 			    "be set with this command."));
1248 			goto error;
1249 		}
1250 	}
1251 
1252 	new_props = zfs_valid_proplist(zhp->zfs_hdl, zhp->zfs_type, props,
1253 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED), NULL, zhp->zpool_hdl,
1254 	    B_TRUE, errbuf);
1255 	if (new_props == NULL)
1256 		goto error;
1257 
1258 	*props_out = new_props;
1259 	return (0);
1260 
1261 error:
1262 	nvlist_free(new_props);
1263 	*props_out = NULL;
1264 	return (ret);
1265 }
1266 
1267 int
1268 zfs_crypto_rewrap(zfs_handle_t *zhp, nvlist_t *raw_props, boolean_t inheritkey)
1269 {
1270 	int ret;
1271 	char errbuf[1024];
1272 	boolean_t is_encroot;
1273 	nvlist_t *props = NULL;
1274 	uint8_t *wkeydata = NULL;
1275 	uint_t wkeylen = 0;
1276 	dcp_cmd_t cmd = (inheritkey) ? DCP_CMD_INHERIT : DCP_CMD_NEW_KEY;
1277 	uint64_t crypt, pcrypt, keystatus, pkeystatus;
1278 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
1279 	zfs_handle_t *pzhp = NULL;
1280 	char *keylocation = NULL;
1281 	char origin_name[MAXNAMELEN];
1282 	char prop_keylocation[MAXNAMELEN];
1283 	char parent_name[ZFS_MAX_DATASET_NAME_LEN];
1284 
1285 	(void) snprintf(errbuf, sizeof (errbuf),
1286 	    dgettext(TEXT_DOMAIN, "Key change error"));
1287 
1288 	/* check that encryption is enabled for the pool */
1289 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1290 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1291 		    "Encryption feature not enabled."));
1292 		ret = EINVAL;
1293 		goto error;
1294 	}
1295 
1296 	/* get crypt from dataset */
1297 	crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
1298 	if (crypt == ZIO_CRYPT_OFF) {
1299 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1300 		    "Dataset not encrypted."));
1301 		ret = EINVAL;
1302 		goto error;
1303 	}
1304 
1305 	/* get the encryption root of the dataset */
1306 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
1307 	if (ret != 0) {
1308 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1309 		    "Failed to get encryption root for '%s'."),
1310 		    zfs_get_name(zhp));
1311 		goto error;
1312 	}
1313 
1314 	/* Clones use their origin's key and cannot rewrap it */
1315 	ret = zfs_prop_get(zhp, ZFS_PROP_ORIGIN, origin_name,
1316 	    sizeof (origin_name), NULL, NULL, 0, B_TRUE);
1317 	if (ret == 0 && strcmp(origin_name, "") != 0) {
1318 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1319 		    "Keys cannot be changed on clones."));
1320 		ret = EINVAL;
1321 		goto error;
1322 	}
1323 
1324 	/*
1325 	 * If the user wants to use the inheritkey variant of this function
1326 	 * we don't need to collect any crypto arguments.
1327 	 */
1328 	if (!inheritkey) {
1329 		/* validate the provided properties */
1330 		ret = zfs_crypto_verify_rewrap_nvlist(zhp, raw_props, &props,
1331 		    errbuf);
1332 		if (ret != 0)
1333 			goto error;
1334 
1335 		/*
1336 		 * Load keyformat and keylocation from the nvlist. Fetch from
1337 		 * the dataset properties if not specified.
1338 		 */
1339 		(void) nvlist_lookup_uint64(props,
1340 		    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
1341 		(void) nvlist_lookup_string(props,
1342 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
1343 
1344 		if (is_encroot) {
1345 			/*
1346 			 * If this is already an ecryption root, just keep
1347 			 * any properties not set by the user.
1348 			 */
1349 			if (keyformat == ZFS_KEYFORMAT_NONE) {
1350 				keyformat = zfs_prop_get_int(zhp,
1351 				    ZFS_PROP_KEYFORMAT);
1352 				ret = nvlist_add_uint64(props,
1353 				    zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
1354 				    keyformat);
1355 			}
1356 
1357 			if (keylocation == NULL) {
1358 				ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,
1359 				    prop_keylocation, sizeof (prop_keylocation),
1360 				    NULL, NULL, 0, B_TRUE);
1361 				if (ret != 0) {
1362 					zfs_error_aux(zhp->zfs_hdl,
1363 					    dgettext(TEXT_DOMAIN, "Failed to "
1364 					    "get existing keylocation "
1365 					    "property."));
1366 					goto error;
1367 				}
1368 
1369 				keylocation = prop_keylocation;
1370 			}
1371 		} else {
1372 			/* need a new key for non-encryption roots */
1373 			if (keyformat == ZFS_KEYFORMAT_NONE) {
1374 				ret = EINVAL;
1375 				zfs_error_aux(zhp->zfs_hdl,
1376 				    dgettext(TEXT_DOMAIN, "Keyformat required "
1377 				    "for new encryption root."));
1378 				goto error;
1379 			}
1380 
1381 			/* default to prompt if no keylocation is specified */
1382 			if (keylocation == NULL) {
1383 				keylocation = "prompt";
1384 				ret = nvlist_add_string(props,
1385 				    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1386 				    keylocation);
1387 				if (ret != 0)
1388 					goto error;
1389 			}
1390 		}
1391 
1392 		/* fetch the new wrapping key and associated properties */
1393 		ret = populate_create_encryption_params_nvlists(zhp->zfs_hdl,
1394 		    zhp, B_TRUE, keyformat, keylocation, props, &wkeydata,
1395 		    &wkeylen);
1396 		if (ret != 0)
1397 			goto error;
1398 	} else {
1399 		/* check that zhp is an encryption root */
1400 		if (!is_encroot) {
1401 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1402 			    "Key inheriting can only be performed on "
1403 			    "encryption roots."));
1404 			ret = EINVAL;
1405 			goto error;
1406 		}
1407 
1408 		/* get the parent's name */
1409 		ret = zfs_parent_name(zhp, parent_name, sizeof (parent_name));
1410 		if (ret != 0) {
1411 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1412 			    "Root dataset cannot inherit key."));
1413 			ret = EINVAL;
1414 			goto error;
1415 		}
1416 
1417 		/* get a handle to the parent */
1418 		pzhp = make_dataset_handle(zhp->zfs_hdl, parent_name);
1419 		if (pzhp == NULL) {
1420 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1421 			    "Failed to lookup parent."));
1422 			ret = ENOENT;
1423 			goto error;
1424 		}
1425 
1426 		/* parent must be encrypted */
1427 		pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
1428 		if (pcrypt == ZIO_CRYPT_OFF) {
1429 			zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1430 			    "Parent must be encrypted."));
1431 			ret = EINVAL;
1432 			goto error;
1433 		}
1434 
1435 		/* check that the parent's key is loaded */
1436 		pkeystatus = zfs_prop_get_int(pzhp, ZFS_PROP_KEYSTATUS);
1437 		if (pkeystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1438 			zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1439 			    "Parent key must be loaded."));
1440 			ret = EACCES;
1441 			goto error;
1442 		}
1443 	}
1444 
1445 	/* check that the key is loaded */
1446 	keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1447 	if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1448 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1449 		    "Key must be loaded."));
1450 		ret = EACCES;
1451 		goto error;
1452 	}
1453 
1454 	/* call the ioctl */
1455 	ret = lzc_change_key(zhp->zfs_name, cmd, props, wkeydata, wkeylen);
1456 	if (ret != 0) {
1457 		switch (ret) {
1458 		case EINVAL:
1459 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1460 			    "Invalid properties for key change."));
1461 			break;
1462 		case EACCES:
1463 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1464 			    "Key is not currently loaded."));
1465 			break;
1466 		}
1467 		(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1468 	}
1469 
1470 	if (pzhp != NULL)
1471 		zfs_close(pzhp);
1472 	if (props != NULL)
1473 		nvlist_free(props);
1474 	if (wkeydata != NULL)
1475 		free(wkeydata);
1476 
1477 	return (ret);
1478 
1479 error:
1480 	if (pzhp != NULL)
1481 		zfs_close(pzhp);
1482 	if (props != NULL)
1483 		nvlist_free(props);
1484 	if (wkeydata != NULL)
1485 		free(wkeydata);
1486 
1487 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1488 	return (ret);
1489 }
1490