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