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