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