xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_crypto.c (revision 6ccda740e007c01cb5d1436fe337851ff8c5d422)
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, boolean_t stdin_available, uint8_t **wkeydata_out,
723     uint_t *wkeylen_out)
724 {
725 	int ret;
726 	uint64_t crypt = ZIO_CRYPT_INHERIT, pcrypt = ZIO_CRYPT_INHERIT;
727 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
728 	char *keylocation = NULL;
729 	zfs_handle_t *pzhp = NULL;
730 	uint8_t *wkeydata = NULL;
731 	uint_t wkeylen = 0;
732 	boolean_t local_crypt = B_TRUE;
733 
734 	/* lookup crypt from props */
735 	ret = nvlist_lookup_uint64(props,
736 	    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &crypt);
737 	if (ret != 0)
738 		local_crypt = B_FALSE;
739 
740 	/* lookup key location and format from props */
741 	(void) nvlist_lookup_uint64(props,
742 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
743 	(void) nvlist_lookup_string(props,
744 	    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
745 
746 	if (parent_name != NULL) {
747 		/* get a reference to parent dataset */
748 		pzhp = make_dataset_handle(hdl, parent_name);
749 		if (pzhp == NULL) {
750 			ret = ENOENT;
751 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
752 			    "Failed to lookup parent."));
753 			goto out;
754 		}
755 
756 		/* Lookup parent's crypt */
757 		pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
758 
759 		/* Params require the encryption feature */
760 		if (!encryption_feature_is_enabled(pzhp->zpool_hdl)) {
761 			if (proplist_has_encryption_props(props)) {
762 				ret = EINVAL;
763 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
764 				    "Encryption feature not enabled."));
765 				goto out;
766 			}
767 
768 			ret = 0;
769 			goto out;
770 		}
771 	} else {
772 		/*
773 		 * special case for root dataset where encryption feature
774 		 * feature won't be on disk yet
775 		 */
776 		if (!nvlist_exists(pool_props, "feature@encryption")) {
777 			if (proplist_has_encryption_props(props)) {
778 				ret = EINVAL;
779 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
780 				    "Encryption feature not enabled."));
781 				goto out;
782 			}
783 
784 			ret = 0;
785 			goto out;
786 		}
787 
788 		pcrypt = ZIO_CRYPT_OFF;
789 	}
790 
791 	/* Get the inherited encryption property if we don't have it locally */
792 	if (!local_crypt)
793 		crypt = pcrypt;
794 
795 	/*
796 	 * At this point crypt should be the actual encryption value. If
797 	 * encryption is off just verify that no encryption properties have
798 	 * been specified and return.
799 	 */
800 	if (crypt == ZIO_CRYPT_OFF) {
801 		if (proplist_has_encryption_props(props)) {
802 			ret = EINVAL;
803 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
804 			    "Encryption must be turned on to set encryption "
805 			    "properties."));
806 			goto out;
807 		}
808 
809 		ret = 0;
810 		goto out;
811 	}
812 
813 	/*
814 	 * If we have a parent crypt it is valid to specify encryption alone.
815 	 * This will result in a child that is encrypted with the chosen
816 	 * encryption suite that will also inherit the parent's key. If
817 	 * the parent is not encrypted we need an encryption suite provided.
818 	 */
819 	if (pcrypt == ZIO_CRYPT_OFF && keylocation == NULL &&
820 	    keyformat == ZFS_KEYFORMAT_NONE) {
821 		ret = EINVAL;
822 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
823 		    "Keyformat required for new encryption root."));
824 		goto out;
825 	}
826 
827 	/*
828 	 * Specifying a keylocation implies this will be a new encryption root.
829 	 * Check that a keyformat is also specified.
830 	 */
831 	if (keylocation != NULL && keyformat == ZFS_KEYFORMAT_NONE) {
832 		ret = EINVAL;
833 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
834 		    "Keyformat required for new encryption root."));
835 		goto out;
836 	}
837 
838 	/* default to prompt if no keylocation is specified */
839 	if (keyformat != ZFS_KEYFORMAT_NONE && keylocation == NULL) {
840 		keylocation = "prompt";
841 		ret = nvlist_add_string(props,
842 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), keylocation);
843 		if (ret != 0)
844 			goto out;
845 	}
846 
847 	/*
848 	 * If a local key is provided, this dataset will be a new
849 	 * encryption root. Populate the encryption params.
850 	 */
851 	if (keylocation != NULL) {
852 		/*
853 		 * 'zfs recv -o keylocation=prompt' won't work because stdin
854 		 * is being used by the send stream, so we disallow it.
855 		 */
856 		if (!stdin_available && strcmp(keylocation, "prompt") == 0) {
857 			ret = EINVAL;
858 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Cannot use "
859 			    "'prompt' keylocation because stdin is in use."));
860 			goto out;
861 		}
862 
863 		ret = populate_create_encryption_params_nvlists(hdl, NULL,
864 		    B_FALSE, keyformat, keylocation, props, &wkeydata,
865 		    &wkeylen);
866 		if (ret != 0)
867 			goto out;
868 	}
869 
870 	if (pzhp != NULL)
871 		zfs_close(pzhp);
872 
873 	*wkeydata_out = wkeydata;
874 	*wkeylen_out = wkeylen;
875 	return (0);
876 
877 out:
878 	if (pzhp != NULL)
879 		zfs_close(pzhp);
880 	if (wkeydata != NULL)
881 		free(wkeydata);
882 
883 	*wkeydata_out = NULL;
884 	*wkeylen_out = 0;
885 	return (ret);
886 }
887 
888 int
889 zfs_crypto_clone_check(libzfs_handle_t *hdl, zfs_handle_t *origin_zhp,
890     char *parent_name, nvlist_t *props)
891 {
892 	/*
893 	 * No encryption properties should be specified. They will all be
894 	 * inherited from the origin dataset.
895 	 */
896 	if (nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYFORMAT)) ||
897 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYLOCATION)) ||
898 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_ENCRYPTION)) ||
899 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS))) {
900 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
901 		    "Encryption properties must inherit from origin dataset."));
902 		return (EINVAL);
903 	}
904 
905 	return (0);
906 }
907 
908 typedef struct loadkeys_cbdata {
909 	uint64_t cb_numfailed;
910 	uint64_t cb_numattempted;
911 } loadkey_cbdata_t;
912 
913 static int
914 load_keys_cb(zfs_handle_t *zhp, void *arg)
915 {
916 	int ret;
917 	boolean_t is_encroot;
918 	loadkey_cbdata_t *cb = arg;
919 	uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
920 
921 	/* only attempt to load keys for encryption roots */
922 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
923 	if (ret != 0 || !is_encroot)
924 		goto out;
925 
926 	/* don't attempt to load already loaded keys */
927 	if (keystatus == ZFS_KEYSTATUS_AVAILABLE)
928 		goto out;
929 
930 	/* Attempt to load the key. Record status in cb. */
931 	cb->cb_numattempted++;
932 
933 	ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
934 	if (ret)
935 		cb->cb_numfailed++;
936 
937 out:
938 	(void) zfs_iter_filesystems(zhp, load_keys_cb, cb);
939 	zfs_close(zhp);
940 
941 	/* always return 0, since this function is best effort */
942 	return (0);
943 }
944 
945 /*
946  * This function is best effort. It attempts to load all the keys for the given
947  * filesystem and all of its children.
948  */
949 int
950 zfs_crypto_attempt_load_keys(libzfs_handle_t *hdl, char *fsname)
951 {
952 	int ret;
953 	zfs_handle_t *zhp = NULL;
954 	loadkey_cbdata_t cb = { 0 };
955 
956 	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
957 	if (zhp == NULL) {
958 		ret = ENOENT;
959 		goto error;
960 	}
961 
962 	ret = load_keys_cb(zfs_handle_dup(zhp), &cb);
963 	if (ret)
964 		goto error;
965 
966 	(void) printf(gettext("%llu / %llu keys successfully loaded\n"),
967 	    (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
968 	    (u_longlong_t)cb.cb_numattempted);
969 
970 	if (cb.cb_numfailed != 0) {
971 		ret = -1;
972 		goto error;
973 	}
974 
975 	zfs_close(zhp);
976 	return (0);
977 
978 error:
979 	if (zhp != NULL)
980 		zfs_close(zhp);
981 	return (ret);
982 }
983 
984 int
985 zfs_crypto_load_key(zfs_handle_t *zhp, boolean_t noop, char *alt_keylocation)
986 {
987 	int ret, attempts = 0;
988 	char errbuf[1024];
989 	uint64_t keystatus, iters = 0, salt = 0;
990 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
991 	char prop_keylocation[MAXNAMELEN];
992 	char prop_encroot[MAXNAMELEN];
993 	char *keylocation = NULL;
994 	uint8_t *key_material = NULL, *key_data = NULL;
995 	size_t key_material_len;
996 	boolean_t is_encroot, can_retry = B_FALSE, correctible = B_FALSE;
997 
998 	(void) snprintf(errbuf, sizeof (errbuf),
999 	    dgettext(TEXT_DOMAIN, "Key load error"));
1000 
1001 	/* check that encryption is enabled for the pool */
1002 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1003 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1004 		    "Encryption feature not enabled."));
1005 		ret = EINVAL;
1006 		goto error;
1007 	}
1008 
1009 	/* Fetch the keyformat. Check that the dataset is encrypted. */
1010 	keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
1011 	if (keyformat == ZFS_KEYFORMAT_NONE) {
1012 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1013 		    "'%s' is not encrypted."), zfs_get_name(zhp));
1014 		ret = EINVAL;
1015 		goto error;
1016 	}
1017 
1018 	/*
1019 	 * Fetch the key location. Check that we are working with an
1020 	 * encryption root.
1021 	 */
1022 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1023 	if (ret != 0) {
1024 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1025 		    "Failed to get encryption root for '%s'."),
1026 		    zfs_get_name(zhp));
1027 		goto error;
1028 	} else if (!is_encroot) {
1029 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1030 		    "Keys must be loaded for encryption root of '%s' (%s)."),
1031 		    zfs_get_name(zhp), prop_encroot);
1032 		ret = EINVAL;
1033 		goto error;
1034 	}
1035 
1036 	/*
1037 	 * if the caller has elected to override the keylocation property
1038 	 * use that instead
1039 	 */
1040 	if (alt_keylocation != NULL) {
1041 		keylocation = alt_keylocation;
1042 	} else {
1043 		ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION, prop_keylocation,
1044 		    sizeof (prop_keylocation), NULL, NULL, 0, B_TRUE);
1045 		if (ret != 0) {
1046 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1047 			    "Failed to get keylocation for '%s'."),
1048 			    zfs_get_name(zhp));
1049 			goto error;
1050 		}
1051 
1052 		keylocation = prop_keylocation;
1053 	}
1054 
1055 	/* check that the key is unloaded unless this is a noop */
1056 	if (!noop) {
1057 		keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1058 		if (keystatus == ZFS_KEYSTATUS_AVAILABLE) {
1059 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1060 			    "Key already loaded for '%s'."), zfs_get_name(zhp));
1061 			ret = EEXIST;
1062 			goto error;
1063 		}
1064 	}
1065 
1066 	/* passphrase formats require a salt and pbkdf2_iters property */
1067 	if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
1068 		salt = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_SALT);
1069 		iters = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_ITERS);
1070 	}
1071 
1072 try_again:
1073 	/* fetching and deriving the key are correctible errors. set the flag */
1074 	correctible = B_TRUE;
1075 
1076 	/* get key material from key format and location */
1077 	ret = get_key_material(zhp->zfs_hdl, B_FALSE, B_FALSE, keyformat,
1078 	    keylocation, zfs_get_name(zhp), &key_material, &key_material_len,
1079 	    &can_retry);
1080 	if (ret != 0)
1081 		goto error;
1082 
1083 	/* derive a key from the key material */
1084 	ret = derive_key(zhp->zfs_hdl, keyformat, iters, key_material,
1085 	    key_material_len, salt, &key_data);
1086 	if (ret != 0)
1087 		goto error;
1088 
1089 	correctible = B_FALSE;
1090 
1091 	/* pass the wrapping key and noop flag to the ioctl */
1092 	ret = lzc_load_key(zhp->zfs_name, noop, key_data, WRAPPING_KEY_LEN);
1093 	if (ret != 0) {
1094 		switch (ret) {
1095 		case EINVAL:
1096 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1097 			    "Invalid parameters provided for %s."),
1098 			    zfs_get_name(zhp));
1099 			break;
1100 		case EEXIST:
1101 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1102 			    "Key already loaded for '%s'."), zfs_get_name(zhp));
1103 			break;
1104 		case EBUSY:
1105 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1106 			    "'%s' is busy."), zfs_get_name(zhp));
1107 			break;
1108 		case EACCES:
1109 			correctible = B_TRUE;
1110 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1111 			    "Incorrect key provided for '%s'."),
1112 			    zfs_get_name(zhp));
1113 			break;
1114 		}
1115 		goto error;
1116 	}
1117 
1118 	free(key_material);
1119 	free(key_data);
1120 
1121 	return (0);
1122 
1123 error:
1124 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1125 	if (key_material != NULL) {
1126 		free(key_material);
1127 		key_material = NULL;
1128 	}
1129 	if (key_data != NULL) {
1130 		free(key_data);
1131 		key_data  = NULL;
1132 	}
1133 
1134 	/*
1135 	 * Here we decide if it is ok to allow the user to retry entering their
1136 	 * key. The can_retry flag will be set if the user is entering their
1137 	 * key from an interactive prompt. The correctible flag will only be
1138 	 * set if an error that occured could be corrected by retrying. Both
1139 	 * flags are needed to allow the user to attempt key entry again
1140 	 */
1141 	if (can_retry && correctible && attempts <= MAX_KEY_PROMPT_ATTEMPTS) {
1142 		attempts++;
1143 		goto try_again;
1144 	}
1145 
1146 	return (ret);
1147 }
1148 
1149 int
1150 zfs_crypto_unload_key(zfs_handle_t *zhp)
1151 {
1152 	int ret;
1153 	char errbuf[1024];
1154 	char prop_encroot[MAXNAMELEN];
1155 	uint64_t keystatus, keyformat;
1156 	boolean_t is_encroot;
1157 
1158 	(void) snprintf(errbuf, sizeof (errbuf),
1159 	    dgettext(TEXT_DOMAIN, "Key unload error"));
1160 
1161 	/* check that encryption is enabled for the pool */
1162 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1163 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1164 		    "Encryption feature not enabled."));
1165 		ret = EINVAL;
1166 		goto error;
1167 	}
1168 
1169 	/* Fetch the keyformat. Check that the dataset is encrypted. */
1170 	keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
1171 	if (keyformat == ZFS_KEYFORMAT_NONE) {
1172 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1173 		    "'%s' is not encrypted."), zfs_get_name(zhp));
1174 		ret = EINVAL;
1175 		goto error;
1176 	}
1177 
1178 	/*
1179 	 * Fetch the key location. Check that we are working with an
1180 	 * encryption root.
1181 	 */
1182 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1183 	if (ret != 0) {
1184 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1185 		    "Failed to get encryption root for '%s'."),
1186 		    zfs_get_name(zhp));
1187 		goto error;
1188 	} else if (!is_encroot) {
1189 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1190 		    "Keys must be unloaded for encryption root of '%s' (%s)."),
1191 		    zfs_get_name(zhp), prop_encroot);
1192 		ret = EINVAL;
1193 		goto error;
1194 	}
1195 
1196 	/* check that the key is loaded */
1197 	keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1198 	if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1199 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1200 		    "Key already unloaded for '%s'."), zfs_get_name(zhp));
1201 		ret = EACCES;
1202 		goto error;
1203 	}
1204 
1205 	/* call the ioctl */
1206 	ret = lzc_unload_key(zhp->zfs_name);
1207 
1208 	if (ret != 0) {
1209 		switch (ret) {
1210 		case EACCES:
1211 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1212 			    "Key already unloaded for '%s'."),
1213 			    zfs_get_name(zhp));
1214 			break;
1215 		case EBUSY:
1216 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1217 			    "'%s' is busy."), zfs_get_name(zhp));
1218 			break;
1219 		}
1220 		(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1221 	}
1222 
1223 	return (ret);
1224 
1225 error:
1226 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1227 	return (ret);
1228 }
1229 
1230 static int
1231 zfs_crypto_verify_rewrap_nvlist(zfs_handle_t *zhp, nvlist_t *props,
1232     nvlist_t **props_out, char *errbuf)
1233 {
1234 	int ret;
1235 	nvpair_t *elem = NULL;
1236 	zfs_prop_t prop;
1237 	nvlist_t *new_props = NULL;
1238 
1239 	new_props = fnvlist_alloc();
1240 
1241 	/*
1242 	 * loop through all provided properties, we should only have
1243 	 * keyformat, keylocation and pbkdf2iters. The actual validation of
1244 	 * values is done by zfs_valid_proplist().
1245 	 */
1246 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
1247 		const char *propname = nvpair_name(elem);
1248 		prop = zfs_name_to_prop(propname);
1249 
1250 		switch (prop) {
1251 		case ZFS_PROP_PBKDF2_ITERS:
1252 		case ZFS_PROP_KEYFORMAT:
1253 		case ZFS_PROP_KEYLOCATION:
1254 			break;
1255 		default:
1256 			ret = EINVAL;
1257 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1258 			    "Only keyformat, keylocation and pbkdf2iters may "
1259 			    "be set with this command."));
1260 			goto error;
1261 		}
1262 	}
1263 
1264 	new_props = zfs_valid_proplist(zhp->zfs_hdl, zhp->zfs_type, props,
1265 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED), NULL, zhp->zpool_hdl,
1266 	    B_TRUE, errbuf);
1267 	if (new_props == NULL)
1268 		goto error;
1269 
1270 	*props_out = new_props;
1271 	return (0);
1272 
1273 error:
1274 	nvlist_free(new_props);
1275 	*props_out = NULL;
1276 	return (ret);
1277 }
1278 
1279 int
1280 zfs_crypto_rewrap(zfs_handle_t *zhp, nvlist_t *raw_props, boolean_t inheritkey)
1281 {
1282 	int ret;
1283 	char errbuf[1024];
1284 	boolean_t is_encroot;
1285 	nvlist_t *props = NULL;
1286 	uint8_t *wkeydata = NULL;
1287 	uint_t wkeylen = 0;
1288 	dcp_cmd_t cmd = (inheritkey) ? DCP_CMD_INHERIT : DCP_CMD_NEW_KEY;
1289 	uint64_t crypt, pcrypt, keystatus, pkeystatus;
1290 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
1291 	zfs_handle_t *pzhp = NULL;
1292 	char *keylocation = NULL;
1293 	char origin_name[MAXNAMELEN];
1294 	char prop_keylocation[MAXNAMELEN];
1295 	char parent_name[ZFS_MAX_DATASET_NAME_LEN];
1296 
1297 	(void) snprintf(errbuf, sizeof (errbuf),
1298 	    dgettext(TEXT_DOMAIN, "Key change error"));
1299 
1300 	/* check that encryption is enabled for the pool */
1301 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1302 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1303 		    "Encryption feature not enabled."));
1304 		ret = EINVAL;
1305 		goto error;
1306 	}
1307 
1308 	/* get crypt from dataset */
1309 	crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
1310 	if (crypt == ZIO_CRYPT_OFF) {
1311 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1312 		    "Dataset not encrypted."));
1313 		ret = EINVAL;
1314 		goto error;
1315 	}
1316 
1317 	/* get the encryption root of the dataset */
1318 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
1319 	if (ret != 0) {
1320 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1321 		    "Failed to get encryption root for '%s'."),
1322 		    zfs_get_name(zhp));
1323 		goto error;
1324 	}
1325 
1326 	/* Clones use their origin's key and cannot rewrap it */
1327 	ret = zfs_prop_get(zhp, ZFS_PROP_ORIGIN, origin_name,
1328 	    sizeof (origin_name), NULL, NULL, 0, B_TRUE);
1329 	if (ret == 0 && strcmp(origin_name, "") != 0) {
1330 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1331 		    "Keys cannot be changed on clones."));
1332 		ret = EINVAL;
1333 		goto error;
1334 	}
1335 
1336 	/*
1337 	 * If the user wants to use the inheritkey variant of this function
1338 	 * we don't need to collect any crypto arguments.
1339 	 */
1340 	if (!inheritkey) {
1341 		/* validate the provided properties */
1342 		ret = zfs_crypto_verify_rewrap_nvlist(zhp, raw_props, &props,
1343 		    errbuf);
1344 		if (ret != 0)
1345 			goto error;
1346 
1347 		/*
1348 		 * Load keyformat and keylocation from the nvlist. Fetch from
1349 		 * the dataset properties if not specified.
1350 		 */
1351 		(void) nvlist_lookup_uint64(props,
1352 		    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
1353 		(void) nvlist_lookup_string(props,
1354 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
1355 
1356 		if (is_encroot) {
1357 			/*
1358 			 * If this is already an ecryption root, just keep
1359 			 * any properties not set by the user.
1360 			 */
1361 			if (keyformat == ZFS_KEYFORMAT_NONE) {
1362 				keyformat = zfs_prop_get_int(zhp,
1363 				    ZFS_PROP_KEYFORMAT);
1364 				ret = nvlist_add_uint64(props,
1365 				    zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
1366 				    keyformat);
1367 			}
1368 
1369 			if (keylocation == NULL) {
1370 				ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,
1371 				    prop_keylocation, sizeof (prop_keylocation),
1372 				    NULL, NULL, 0, B_TRUE);
1373 				if (ret != 0) {
1374 					zfs_error_aux(zhp->zfs_hdl,
1375 					    dgettext(TEXT_DOMAIN, "Failed to "
1376 					    "get existing keylocation "
1377 					    "property."));
1378 					goto error;
1379 				}
1380 
1381 				keylocation = prop_keylocation;
1382 			}
1383 		} else {
1384 			/* need a new key for non-encryption roots */
1385 			if (keyformat == ZFS_KEYFORMAT_NONE) {
1386 				ret = EINVAL;
1387 				zfs_error_aux(zhp->zfs_hdl,
1388 				    dgettext(TEXT_DOMAIN, "Keyformat required "
1389 				    "for new encryption root."));
1390 				goto error;
1391 			}
1392 
1393 			/* default to prompt if no keylocation is specified */
1394 			if (keylocation == NULL) {
1395 				keylocation = "prompt";
1396 				ret = nvlist_add_string(props,
1397 				    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1398 				    keylocation);
1399 				if (ret != 0)
1400 					goto error;
1401 			}
1402 		}
1403 
1404 		/* fetch the new wrapping key and associated properties */
1405 		ret = populate_create_encryption_params_nvlists(zhp->zfs_hdl,
1406 		    zhp, B_TRUE, keyformat, keylocation, props, &wkeydata,
1407 		    &wkeylen);
1408 		if (ret != 0)
1409 			goto error;
1410 	} else {
1411 		/* check that zhp is an encryption root */
1412 		if (!is_encroot) {
1413 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1414 			    "Key inheriting can only be performed on "
1415 			    "encryption roots."));
1416 			ret = EINVAL;
1417 			goto error;
1418 		}
1419 
1420 		/* get the parent's name */
1421 		ret = zfs_parent_name(zhp, parent_name, sizeof (parent_name));
1422 		if (ret != 0) {
1423 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1424 			    "Root dataset cannot inherit key."));
1425 			ret = EINVAL;
1426 			goto error;
1427 		}
1428 
1429 		/* get a handle to the parent */
1430 		pzhp = make_dataset_handle(zhp->zfs_hdl, parent_name);
1431 		if (pzhp == NULL) {
1432 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1433 			    "Failed to lookup parent."));
1434 			ret = ENOENT;
1435 			goto error;
1436 		}
1437 
1438 		/* parent must be encrypted */
1439 		pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
1440 		if (pcrypt == ZIO_CRYPT_OFF) {
1441 			zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1442 			    "Parent must be encrypted."));
1443 			ret = EINVAL;
1444 			goto error;
1445 		}
1446 
1447 		/* check that the parent's key is loaded */
1448 		pkeystatus = zfs_prop_get_int(pzhp, ZFS_PROP_KEYSTATUS);
1449 		if (pkeystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1450 			zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1451 			    "Parent key must be loaded."));
1452 			ret = EACCES;
1453 			goto error;
1454 		}
1455 	}
1456 
1457 	/* check that the key is loaded */
1458 	keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1459 	if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1460 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1461 		    "Key must be loaded."));
1462 		ret = EACCES;
1463 		goto error;
1464 	}
1465 
1466 	/* call the ioctl */
1467 	ret = lzc_change_key(zhp->zfs_name, cmd, props, wkeydata, wkeylen);
1468 	if (ret != 0) {
1469 		switch (ret) {
1470 		case EINVAL:
1471 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1472 			    "Invalid properties for key change."));
1473 			break;
1474 		case EACCES:
1475 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1476 			    "Key is not currently loaded."));
1477 			break;
1478 		}
1479 		(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1480 	}
1481 
1482 	if (pzhp != NULL)
1483 		zfs_close(pzhp);
1484 	if (props != NULL)
1485 		nvlist_free(props);
1486 	if (wkeydata != NULL)
1487 		free(wkeydata);
1488 
1489 	return (ret);
1490 
1491 error:
1492 	if (pzhp != NULL)
1493 		zfs_close(pzhp);
1494 	if (props != NULL)
1495 		nvlist_free(props);
1496 	if (wkeydata != NULL)
1497 		free(wkeydata);
1498 
1499 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1500 	return (ret);
1501 }
1502