xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_crypto.c (revision aecc710ab066150d47e5e9e7269e2e0d69107b4e)
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 		for (handler = uri_handlers; handler->zuh_scheme != NULL;
535 		    handler++) {
536 			if (strcmp(handler->zuh_scheme, scheme) != 0)
537 				continue;
538 			if ((ret = handler->zuh_handler(hdl, keylocation,
539 			    fsname, keyformat, newkey, &km, &kmlen)) != 0)
540 				goto error;
541 		}
542 		ret = ENOTSUP;
543 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
544 		    "URI scheme is not supported"));
545 		break;
546 	default:
547 		ret = EINVAL;
548 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
549 		    "Invalid keylocation."));
550 		goto error;
551 	}
552 
553 	if ((ret = validate_key(hdl, keyformat, (const char *)km, kmlen)) != 0)
554 		goto error;
555 
556 	*km_out = km;
557 	*kmlen_out = kmlen;
558 	if (can_retry_out != NULL)
559 		*can_retry_out = can_retry;
560 
561 	free(scheme);
562 	return (0);
563 
564 error:
565 	freezero(km, kmlen);
566 	free(scheme);
567 
568 	*km_out = NULL;
569 	*kmlen_out = 0;
570 
571 	return (ret);
572 }
573 
574 /* This needs to be fixed to be compatible with other platforms */
575 
576 static int
pbkdf2(uint8_t * passphrase,size_t passphraselen,uint8_t * salt,size_t saltlen,uint64_t iterations,uint8_t * output,size_t outputlen)577 pbkdf2(uint8_t *passphrase, size_t passphraselen, uint8_t *salt,
578     size_t saltlen, uint64_t iterations, uint8_t *output,
579     size_t outputlen)
580 {
581 	int ret = 0;
582 	CK_SESSION_HANDLE session;
583 	char *tmpkeydata = NULL;
584 	size_t tmpkeydatalen = 0;
585 	CK_OBJECT_HANDLE obj;
586 
587 	/* initialize output */
588 	(void) memset(output, 0, outputlen);
589 
590 	ret = SUNW_C_GetMechSession(CKM_PKCS5_PBKD2, &session);
591 	if (ret) {
592 		(void) fprintf(stderr, "failed to connect to pkcs5: %s\n",
593 		    pkcs11_strerror(ret));
594 		return (ret);
595 	}
596 
597 	ret = pkcs11_PasswdToPBKD2Object(session, (char *)passphrase,
598 	    passphraselen, salt, saltlen, iterations, CKK_AES, outputlen, 0,
599 	    &obj);
600 
601 	if (ret == CKR_OK)
602 		ret = pkcs11_ObjectToKey(session, obj, (void **)&tmpkeydata,
603 		    &tmpkeydatalen, B_TRUE);
604 
605 	(void) C_CloseSession(session);
606 	if (ret) {
607 		(void) fprintf(stderr, "unable to generate key: %s\n",
608 		    pkcs11_strerror(ret));
609 		return (ret);
610 	}
611 
612 	/*
613 	 * Because it allocates an area for the passphrase, we copy it out
614 	 * then zero the original
615 	 */
616 	(void) memcpy(output, tmpkeydata, tmpkeydatalen);
617 	(void) memset(tmpkeydata, 0, tmpkeydatalen);
618 	free(tmpkeydata);
619 
620 	return (ret);
621 }
622 
623 /* ARGSUSED */
624 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)625 derive_key(libzfs_handle_t *hdl, zfs_keyformat_t format, uint64_t iters,
626     uint8_t *key_material, size_t key_material_len, uint64_t salt,
627     uint8_t **key_out)
628 {
629 	int ret;
630 	uint8_t *key;
631 
632 	*key_out = NULL;
633 
634 	key = zfs_alloc(hdl, WRAPPING_KEY_LEN);
635 	if (!key)
636 		return (ENOMEM);
637 
638 	switch (format) {
639 	case ZFS_KEYFORMAT_RAW:
640 		bcopy(key_material, key, WRAPPING_KEY_LEN);
641 		break;
642 	case ZFS_KEYFORMAT_HEX:
643 		ret = hex_key_to_raw((char *)key_material,
644 		    WRAPPING_KEY_LEN * 2, key);
645 		if (ret != 0) {
646 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
647 			    "Invalid hex key provided."));
648 			goto error;
649 		}
650 		break;
651 	case ZFS_KEYFORMAT_PASSPHRASE:
652 		salt = LE_64(salt);
653 		ret = pbkdf2(key_material, strlen((char *)key_material),
654 		    ((uint8_t *)&salt), sizeof (uint64_t), iters,
655 		    key, WRAPPING_KEY_LEN);
656 		if (ret != 0) {
657 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
658 			    "Failed to generate key from passphrase."));
659 			goto error;
660 		}
661 		break;
662 	default:
663 		ret = EINVAL;
664 		goto error;
665 	}
666 
667 	*key_out = key;
668 	return (0);
669 
670 error:
671 	free(key);
672 
673 	*key_out = NULL;
674 	return (ret);
675 }
676 
677 static boolean_t
encryption_feature_is_enabled(zpool_handle_t * zph)678 encryption_feature_is_enabled(zpool_handle_t *zph)
679 {
680 	nvlist_t *features;
681 	uint64_t feat_refcount;
682 
683 	/* check that features can be enabled */
684 	if (zpool_get_prop_int(zph, ZPOOL_PROP_VERSION, NULL)
685 	    < SPA_VERSION_FEATURES)
686 		return (B_FALSE);
687 
688 	/* check for crypto feature */
689 	features = zpool_get_features(zph);
690 	if (!features || nvlist_lookup_uint64(features,
691 	    spa_feature_table[SPA_FEATURE_ENCRYPTION].fi_guid,
692 	    &feat_refcount) != 0)
693 		return (B_FALSE);
694 
695 	return (B_TRUE);
696 }
697 
698 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)699 populate_create_encryption_params_nvlists(libzfs_handle_t *hdl,
700     zfs_handle_t *zhp, boolean_t newkey, zfs_keyformat_t keyformat,
701     char *keylocation, nvlist_t *props, uint8_t **wkeydata, uint_t *wkeylen)
702 {
703 	int ret;
704 	uint64_t iters = 0, salt = 0;
705 	uint8_t *key_material = NULL;
706 	size_t key_material_len = 0;
707 	uint8_t *key_data = NULL;
708 	const char *fsname = (zhp) ? zfs_get_name(zhp) : NULL;
709 
710 	/* get key material from keyformat and keylocation */
711 	ret = get_key_material(hdl, B_TRUE, newkey, keyformat, keylocation,
712 	    fsname, &key_material, &key_material_len, NULL);
713 	if (ret != 0)
714 		goto error;
715 
716 	/* passphrase formats require a salt and pbkdf2 iters property */
717 	if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
718 #ifdef sun
719 		arc4random_buf(&salt, sizeof (salt));
720 #else
721 		random_init();
722 
723 		ret = random_get_bytes((uint8_t *)&salt, sizeof (uint64_t));
724 		if (ret != 0) {
725 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
726 			    "Failed to generate salt."));
727 			goto error;
728 		}
729 
730 		random_fini();
731 #endif
732 
733 		ret = nvlist_add_uint64(props,
734 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), salt);
735 		if (ret != 0) {
736 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
737 			    "Failed to add salt to properties."));
738 			goto error;
739 		}
740 
741 		/*
742 		 * If not otherwise specified, use the default number of
743 		 * pbkdf2 iterations. If specified, we have already checked
744 		 * that the given value is greater than MIN_PBKDF2_ITERATIONS
745 		 * during zfs_valid_proplist().
746 		 */
747 		ret = nvlist_lookup_uint64(props,
748 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
749 		if (ret == ENOENT) {
750 			iters = DEFAULT_PBKDF2_ITERATIONS;
751 			ret = nvlist_add_uint64(props,
752 			    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), iters);
753 			if (ret != 0)
754 				goto error;
755 		} else if (ret != 0) {
756 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
757 			    "Failed to get pbkdf2 iterations."));
758 			goto error;
759 		}
760 	} else {
761 		/* check that pbkdf2iters was not specified by the user */
762 		ret = nvlist_lookup_uint64(props,
763 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &iters);
764 		if (ret == 0) {
765 			ret = EINVAL;
766 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
767 			    "Cannot specify pbkdf2iters with a non-passphrase "
768 			    "keyformat."));
769 			goto error;
770 		}
771 	}
772 
773 	/* derive a key from the key material */
774 	ret = derive_key(hdl, (zfs_keyformat_t)keyformat, iters, key_material,
775 	    key_material_len, salt, &key_data);
776 	if (ret != 0)
777 		goto error;
778 
779 	free(key_material);
780 
781 	*wkeydata = key_data;
782 	*wkeylen = WRAPPING_KEY_LEN;
783 	return (0);
784 
785 error:
786 	if (key_material != NULL)
787 		free(key_material);
788 	if (key_data != NULL)
789 		free(key_data);
790 
791 	*wkeydata = NULL;
792 	*wkeylen = 0;
793 	return (ret);
794 }
795 
796 static boolean_t
proplist_has_encryption_props(nvlist_t * props)797 proplist_has_encryption_props(nvlist_t *props)
798 {
799 	int ret;
800 	uint64_t intval;
801 	char *strval;
802 
803 	ret = nvlist_lookup_uint64(props,
804 	    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &intval);
805 	if (ret == 0 && intval != ZIO_CRYPT_OFF)
806 		return (B_TRUE);
807 
808 	ret = nvlist_lookup_string(props,
809 	    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &strval);
810 	if (ret == 0 && strcmp(strval, "none") != 0)
811 		return (B_TRUE);
812 
813 	ret = nvlist_lookup_uint64(props,
814 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &intval);
815 	if (ret == 0)
816 		return (B_TRUE);
817 
818 	ret = nvlist_lookup_uint64(props,
819 	    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), &intval);
820 	if (ret == 0)
821 		return (B_TRUE);
822 
823 	return (B_FALSE);
824 }
825 
826 int
zfs_crypto_get_encryption_root(zfs_handle_t * zhp,boolean_t * is_encroot,char * buf)827 zfs_crypto_get_encryption_root(zfs_handle_t *zhp, boolean_t *is_encroot,
828     char *buf)
829 {
830 	int ret;
831 	char prop_encroot[MAXNAMELEN];
832 
833 	/* if the dataset isn't encrypted, just return */
834 	if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) == ZIO_CRYPT_OFF) {
835 		*is_encroot = B_FALSE;
836 		if (buf != NULL)
837 			buf[0] = '\0';
838 		return (0);
839 	}
840 
841 	ret = zfs_prop_get(zhp, ZFS_PROP_ENCRYPTION_ROOT, prop_encroot,
842 	    sizeof (prop_encroot), NULL, NULL, 0, B_TRUE);
843 	if (ret != 0) {
844 		*is_encroot = B_FALSE;
845 		if (buf != NULL)
846 			buf[0] = '\0';
847 		return (ret);
848 	}
849 
850 	*is_encroot = strcmp(prop_encroot, zfs_get_name(zhp)) == 0;
851 	if (buf != NULL)
852 		(void) strcpy(buf, prop_encroot);
853 
854 	return (0);
855 }
856 
857 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)858 zfs_crypto_create(libzfs_handle_t *hdl, char *parent_name, nvlist_t *props,
859     nvlist_t *pool_props, boolean_t stdin_available, uint8_t **wkeydata_out,
860     uint_t *wkeylen_out)
861 {
862 	int ret;
863 	uint64_t crypt = ZIO_CRYPT_INHERIT, pcrypt = ZIO_CRYPT_INHERIT;
864 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
865 	char *keylocation = NULL;
866 	zfs_handle_t *pzhp = NULL;
867 	uint8_t *wkeydata = NULL;
868 	uint_t wkeylen = 0;
869 	boolean_t local_crypt = B_TRUE;
870 
871 	/* lookup crypt from props */
872 	ret = nvlist_lookup_uint64(props,
873 	    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), &crypt);
874 	if (ret != 0)
875 		local_crypt = B_FALSE;
876 
877 	/* lookup key location and format from props */
878 	(void) nvlist_lookup_uint64(props,
879 	    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
880 	(void) nvlist_lookup_string(props,
881 	    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
882 
883 	if (parent_name != NULL) {
884 		/* get a reference to parent dataset */
885 		pzhp = make_dataset_handle(hdl, parent_name);
886 		if (pzhp == NULL) {
887 			ret = ENOENT;
888 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
889 			    "Failed to lookup parent."));
890 			goto out;
891 		}
892 
893 		/* Lookup parent's crypt */
894 		pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
895 
896 		/* Params require the encryption feature */
897 		if (!encryption_feature_is_enabled(pzhp->zpool_hdl)) {
898 			if (proplist_has_encryption_props(props)) {
899 				ret = EINVAL;
900 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
901 				    "Encryption feature not enabled."));
902 				goto out;
903 			}
904 
905 			ret = 0;
906 			goto out;
907 		}
908 	} else {
909 		/*
910 		 * special case for root dataset where encryption feature
911 		 * feature won't be on disk yet
912 		 */
913 		if (!nvlist_exists(pool_props, "feature@encryption")) {
914 			if (proplist_has_encryption_props(props)) {
915 				ret = EINVAL;
916 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
917 				    "Encryption feature not enabled."));
918 				goto out;
919 			}
920 
921 			ret = 0;
922 			goto out;
923 		}
924 
925 		pcrypt = ZIO_CRYPT_OFF;
926 	}
927 
928 	/* Get the inherited encryption property if we don't have it locally */
929 	if (!local_crypt)
930 		crypt = pcrypt;
931 
932 	/*
933 	 * At this point crypt should be the actual encryption value. If
934 	 * encryption is off just verify that no encryption properties have
935 	 * been specified and return.
936 	 */
937 	if (crypt == ZIO_CRYPT_OFF) {
938 		if (proplist_has_encryption_props(props)) {
939 			ret = EINVAL;
940 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
941 			    "Encryption must be turned on to set encryption "
942 			    "properties."));
943 			goto out;
944 		}
945 
946 		ret = 0;
947 		goto out;
948 	}
949 
950 	/*
951 	 * If we have a parent crypt it is valid to specify encryption alone.
952 	 * This will result in a child that is encrypted with the chosen
953 	 * encryption suite that will also inherit the parent's key. If
954 	 * the parent is not encrypted we need an encryption suite provided.
955 	 */
956 	if (pcrypt == ZIO_CRYPT_OFF && keylocation == NULL &&
957 	    keyformat == ZFS_KEYFORMAT_NONE) {
958 		ret = EINVAL;
959 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
960 		    "Keyformat required for new encryption root."));
961 		goto out;
962 	}
963 
964 	/*
965 	 * Specifying a keylocation implies this will be a new encryption root.
966 	 * Check that a keyformat is also specified.
967 	 */
968 	if (keylocation != NULL && keyformat == ZFS_KEYFORMAT_NONE) {
969 		ret = EINVAL;
970 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
971 		    "Keyformat required for new encryption root."));
972 		goto out;
973 	}
974 
975 	/* default to prompt if no keylocation is specified */
976 	if (keyformat != ZFS_KEYFORMAT_NONE && keylocation == NULL) {
977 		keylocation = "prompt";
978 		ret = nvlist_add_string(props,
979 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), keylocation);
980 		if (ret != 0)
981 			goto out;
982 	}
983 
984 	/*
985 	 * If a local key is provided, this dataset will be a new
986 	 * encryption root. Populate the encryption params.
987 	 */
988 	if (keylocation != NULL) {
989 		/*
990 		 * 'zfs recv -o keylocation=prompt' won't work because stdin
991 		 * is being used by the send stream, so we disallow it.
992 		 */
993 		if (!stdin_available && strcmp(keylocation, "prompt") == 0) {
994 			ret = EINVAL;
995 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Cannot use "
996 			    "'prompt' keylocation because stdin is in use."));
997 			goto out;
998 		}
999 
1000 		ret = populate_create_encryption_params_nvlists(hdl, NULL,
1001 		    B_FALSE, keyformat, keylocation, props, &wkeydata,
1002 		    &wkeylen);
1003 		if (ret != 0)
1004 			goto out;
1005 	}
1006 
1007 	if (pzhp != NULL)
1008 		zfs_close(pzhp);
1009 
1010 	*wkeydata_out = wkeydata;
1011 	*wkeylen_out = wkeylen;
1012 	return (0);
1013 
1014 out:
1015 	if (pzhp != NULL)
1016 		zfs_close(pzhp);
1017 	if (wkeydata != NULL)
1018 		free(wkeydata);
1019 
1020 	*wkeydata_out = NULL;
1021 	*wkeylen_out = 0;
1022 	return (ret);
1023 }
1024 
1025 int
zfs_crypto_clone_check(libzfs_handle_t * hdl,zfs_handle_t * origin_zhp,char * parent_name,nvlist_t * props)1026 zfs_crypto_clone_check(libzfs_handle_t *hdl, zfs_handle_t *origin_zhp,
1027     char *parent_name, nvlist_t *props)
1028 {
1029 	/*
1030 	 * No encryption properties should be specified. They will all be
1031 	 * inherited from the origin dataset.
1032 	 */
1033 	if (nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYFORMAT)) ||
1034 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_KEYLOCATION)) ||
1035 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_ENCRYPTION)) ||
1036 	    nvlist_exists(props, zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS))) {
1037 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1038 		    "Encryption properties must inherit from origin dataset."));
1039 		return (EINVAL);
1040 	}
1041 
1042 	return (0);
1043 }
1044 
1045 typedef struct loadkeys_cbdata {
1046 	uint64_t cb_numfailed;
1047 	uint64_t cb_numattempted;
1048 } loadkey_cbdata_t;
1049 
1050 static int
load_keys_cb(zfs_handle_t * zhp,void * arg)1051 load_keys_cb(zfs_handle_t *zhp, void *arg)
1052 {
1053 	int ret;
1054 	boolean_t is_encroot;
1055 	loadkey_cbdata_t *cb = arg;
1056 	uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1057 
1058 	/* only attempt to load keys for encryption roots */
1059 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
1060 	if (ret != 0 || !is_encroot)
1061 		goto out;
1062 
1063 	/* don't attempt to load already loaded keys */
1064 	if (keystatus == ZFS_KEYSTATUS_AVAILABLE)
1065 		goto out;
1066 
1067 	/* Attempt to load the key. Record status in cb. */
1068 	cb->cb_numattempted++;
1069 
1070 	ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
1071 	if (ret)
1072 		cb->cb_numfailed++;
1073 
1074 out:
1075 	(void) zfs_iter_filesystems(zhp, load_keys_cb, cb);
1076 	zfs_close(zhp);
1077 
1078 	/* always return 0, since this function is best effort */
1079 	return (0);
1080 }
1081 
1082 /*
1083  * This function is best effort. It attempts to load all the keys for the given
1084  * filesystem and all of its children.
1085  */
1086 int
zfs_crypto_attempt_load_keys(libzfs_handle_t * hdl,char * fsname)1087 zfs_crypto_attempt_load_keys(libzfs_handle_t *hdl, char *fsname)
1088 {
1089 	int ret;
1090 	zfs_handle_t *zhp = NULL;
1091 	loadkey_cbdata_t cb = { 0 };
1092 
1093 	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1094 	if (zhp == NULL) {
1095 		ret = ENOENT;
1096 		goto error;
1097 	}
1098 
1099 	ret = load_keys_cb(zfs_handle_dup(zhp), &cb);
1100 	if (ret)
1101 		goto error;
1102 
1103 	(void) printf(gettext("%llu / %llu keys successfully loaded\n"),
1104 	    (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
1105 	    (u_longlong_t)cb.cb_numattempted);
1106 
1107 	if (cb.cb_numfailed != 0) {
1108 		ret = -1;
1109 		goto error;
1110 	}
1111 
1112 	zfs_close(zhp);
1113 	return (0);
1114 
1115 error:
1116 	if (zhp != NULL)
1117 		zfs_close(zhp);
1118 	return (ret);
1119 }
1120 
1121 int
zfs_crypto_load_key(zfs_handle_t * zhp,boolean_t noop,char * alt_keylocation)1122 zfs_crypto_load_key(zfs_handle_t *zhp, boolean_t noop, char *alt_keylocation)
1123 {
1124 	int ret, attempts = 0;
1125 	char errbuf[1024];
1126 	uint64_t keystatus, iters = 0, salt = 0;
1127 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
1128 	char prop_keylocation[MAXNAMELEN];
1129 	char prop_encroot[MAXNAMELEN];
1130 	char *keylocation = NULL;
1131 	uint8_t *key_material = NULL, *key_data = NULL;
1132 	size_t key_material_len;
1133 	boolean_t is_encroot, can_retry = B_FALSE, correctible = B_FALSE;
1134 
1135 	(void) snprintf(errbuf, sizeof (errbuf),
1136 	    dgettext(TEXT_DOMAIN, "Key load error"));
1137 
1138 	/* check that encryption is enabled for the pool */
1139 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1140 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1141 		    "Encryption feature not enabled."));
1142 		ret = EINVAL;
1143 		goto error;
1144 	}
1145 
1146 	/* Fetch the keyformat. Check that the dataset is encrypted. */
1147 	keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
1148 	if (keyformat == ZFS_KEYFORMAT_NONE) {
1149 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1150 		    "'%s' is not encrypted."), zfs_get_name(zhp));
1151 		ret = EINVAL;
1152 		goto error;
1153 	}
1154 
1155 	/*
1156 	 * Fetch the key location. Check that we are working with an
1157 	 * encryption root.
1158 	 */
1159 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1160 	if (ret != 0) {
1161 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1162 		    "Failed to get encryption root for '%s'."),
1163 		    zfs_get_name(zhp));
1164 		goto error;
1165 	} else if (!is_encroot) {
1166 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1167 		    "Keys must be loaded for encryption root of '%s' (%s)."),
1168 		    zfs_get_name(zhp), prop_encroot);
1169 		ret = EINVAL;
1170 		goto error;
1171 	}
1172 
1173 	/*
1174 	 * if the caller has elected to override the keylocation property
1175 	 * use that instead
1176 	 */
1177 	if (alt_keylocation != NULL) {
1178 		keylocation = alt_keylocation;
1179 	} else {
1180 		ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION, prop_keylocation,
1181 		    sizeof (prop_keylocation), NULL, NULL, 0, B_TRUE);
1182 		if (ret != 0) {
1183 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1184 			    "Failed to get keylocation for '%s'."),
1185 			    zfs_get_name(zhp));
1186 			goto error;
1187 		}
1188 
1189 		keylocation = prop_keylocation;
1190 	}
1191 
1192 	/* check that the key is unloaded unless this is a noop */
1193 	if (!noop) {
1194 		keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1195 		if (keystatus == ZFS_KEYSTATUS_AVAILABLE) {
1196 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1197 			    "Key already loaded for '%s'."), zfs_get_name(zhp));
1198 			ret = EEXIST;
1199 			goto error;
1200 		}
1201 	}
1202 
1203 	/* passphrase formats require a salt and pbkdf2_iters property */
1204 	if (keyformat == ZFS_KEYFORMAT_PASSPHRASE) {
1205 		salt = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_SALT);
1206 		iters = zfs_prop_get_int(zhp, ZFS_PROP_PBKDF2_ITERS);
1207 	}
1208 
1209 try_again:
1210 	/* fetching and deriving the key are correctible errors. set the flag */
1211 	correctible = B_TRUE;
1212 
1213 	/* get key material from key format and location */
1214 	ret = get_key_material(zhp->zfs_hdl, B_FALSE, B_FALSE, keyformat,
1215 	    keylocation, zfs_get_name(zhp), &key_material, &key_material_len,
1216 	    &can_retry);
1217 	if (ret != 0)
1218 		goto error;
1219 
1220 	/* derive a key from the key material */
1221 	ret = derive_key(zhp->zfs_hdl, keyformat, iters, key_material,
1222 	    key_material_len, salt, &key_data);
1223 	if (ret != 0)
1224 		goto error;
1225 
1226 	correctible = B_FALSE;
1227 
1228 	/* pass the wrapping key and noop flag to the ioctl */
1229 	ret = lzc_load_key(zhp->zfs_name, noop, key_data, WRAPPING_KEY_LEN);
1230 	if (ret != 0) {
1231 		switch (ret) {
1232 		case EINVAL:
1233 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1234 			    "Invalid parameters provided for %s."),
1235 			    zfs_get_name(zhp));
1236 			break;
1237 		case EEXIST:
1238 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1239 			    "Key already loaded for '%s'."), zfs_get_name(zhp));
1240 			break;
1241 		case EBUSY:
1242 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1243 			    "'%s' is busy."), zfs_get_name(zhp));
1244 			break;
1245 		case EACCES:
1246 			correctible = B_TRUE;
1247 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1248 			    "Incorrect key provided for '%s'."),
1249 			    zfs_get_name(zhp));
1250 			break;
1251 		}
1252 		goto error;
1253 	}
1254 
1255 	free(key_material);
1256 	free(key_data);
1257 
1258 	return (0);
1259 
1260 error:
1261 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1262 	if (key_material != NULL) {
1263 		free(key_material);
1264 		key_material = NULL;
1265 	}
1266 	if (key_data != NULL) {
1267 		free(key_data);
1268 		key_data  = NULL;
1269 	}
1270 
1271 	/*
1272 	 * Here we decide if it is ok to allow the user to retry entering their
1273 	 * key. The can_retry flag will be set if the user is entering their
1274 	 * key from an interactive prompt. The correctible flag will only be
1275 	 * set if an error that occured could be corrected by retrying. Both
1276 	 * flags are needed to allow the user to attempt key entry again
1277 	 */
1278 	if (can_retry && correctible && attempts <= MAX_KEY_PROMPT_ATTEMPTS) {
1279 		attempts++;
1280 		goto try_again;
1281 	}
1282 
1283 	return (ret);
1284 }
1285 
1286 int
zfs_crypto_unload_key(zfs_handle_t * zhp)1287 zfs_crypto_unload_key(zfs_handle_t *zhp)
1288 {
1289 	int ret;
1290 	char errbuf[1024];
1291 	char prop_encroot[MAXNAMELEN];
1292 	uint64_t keystatus, keyformat;
1293 	boolean_t is_encroot;
1294 
1295 	(void) snprintf(errbuf, sizeof (errbuf),
1296 	    dgettext(TEXT_DOMAIN, "Key unload error"));
1297 
1298 	/* check that encryption is enabled for the pool */
1299 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1300 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1301 		    "Encryption feature not enabled."));
1302 		ret = EINVAL;
1303 		goto error;
1304 	}
1305 
1306 	/* Fetch the keyformat. Check that the dataset is encrypted. */
1307 	keyformat = zfs_prop_get_int(zhp, ZFS_PROP_KEYFORMAT);
1308 	if (keyformat == ZFS_KEYFORMAT_NONE) {
1309 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1310 		    "'%s' is not encrypted."), zfs_get_name(zhp));
1311 		ret = EINVAL;
1312 		goto error;
1313 	}
1314 
1315 	/*
1316 	 * Fetch the key location. Check that we are working with an
1317 	 * encryption root.
1318 	 */
1319 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, prop_encroot);
1320 	if (ret != 0) {
1321 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1322 		    "Failed to get encryption root for '%s'."),
1323 		    zfs_get_name(zhp));
1324 		goto error;
1325 	} else if (!is_encroot) {
1326 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1327 		    "Keys must be unloaded for encryption root of '%s' (%s)."),
1328 		    zfs_get_name(zhp), prop_encroot);
1329 		ret = EINVAL;
1330 		goto error;
1331 	}
1332 
1333 	/* check that the key is loaded */
1334 	keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1335 	if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1336 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1337 		    "Key already unloaded for '%s'."), zfs_get_name(zhp));
1338 		ret = EACCES;
1339 		goto error;
1340 	}
1341 
1342 	/* call the ioctl */
1343 	ret = lzc_unload_key(zhp->zfs_name);
1344 
1345 	if (ret != 0) {
1346 		switch (ret) {
1347 		case EACCES:
1348 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1349 			    "Key already unloaded for '%s'."),
1350 			    zfs_get_name(zhp));
1351 			break;
1352 		case EBUSY:
1353 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1354 			    "'%s' is busy."), zfs_get_name(zhp));
1355 			break;
1356 		}
1357 		(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1358 	}
1359 
1360 	return (ret);
1361 
1362 error:
1363 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1364 	return (ret);
1365 }
1366 
1367 static int
zfs_crypto_verify_rewrap_nvlist(zfs_handle_t * zhp,nvlist_t * props,boolean_t inheritkey,nvlist_t ** props_out,char * errbuf)1368 zfs_crypto_verify_rewrap_nvlist(zfs_handle_t *zhp, nvlist_t *props,
1369     boolean_t inheritkey, nvlist_t **props_out, char *errbuf)
1370 {
1371 	int ret;
1372 	nvpair_t *elem = NULL;
1373 	nvlist_t *new_props = NULL;
1374 
1375 	/*
1376 	 * loop through all provided properties, we should only have
1377 	 * keyformat, keylocation and pbkdf2iters, and user properties.
1378 	 * The actual validation of values is done by zfs_valid_proplist().
1379 	 */
1380 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
1381 		const char *propname = nvpair_name(elem);
1382 
1383 		switch (zfs_name_to_prop(propname)) {
1384 		case ZFS_PROP_PBKDF2_ITERS:
1385 		case ZFS_PROP_KEYFORMAT:
1386 		case ZFS_PROP_KEYLOCATION:
1387 			if (inheritkey) {
1388 				ret = EINVAL;
1389 				zfs_error_aux(zhp->zfs_hdl,
1390 				    dgettext(TEXT_DOMAIN,
1391 				    "Only user properties may be set with "
1392 				    "'zfs change-key -i'"));
1393 				goto error;
1394 			}
1395 			break;
1396 		case ZPROP_INVAL:
1397 			if (zfs_prop_user(propname))
1398 				break;
1399 			/* FALLTHROUGH */
1400 		default:
1401 			ret = EINVAL;
1402 			if (inheritkey) {
1403 				zfs_error_aux(zhp->zfs_hdl,
1404 				    dgettext(TEXT_DOMAIN,
1405 				    "Only user properties may be set with "
1406 				    "'zfs change-key -i'"));
1407 			} else {
1408 				zfs_error_aux(zhp->zfs_hdl,
1409 				    dgettext(TEXT_DOMAIN,
1410 				    "Only keyformat, keylocation, pbkdf2iters, "
1411 				    "and user properties may be set with this "
1412 				    "command."));
1413 			}
1414 			goto error;
1415 		}
1416 	}
1417 
1418 	new_props = zfs_valid_proplist(zhp->zfs_hdl, zhp->zfs_type, props,
1419 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED), NULL, zhp->zpool_hdl,
1420 	    B_TRUE, errbuf);
1421 	if (new_props == NULL)
1422 		goto error;
1423 
1424 	*props_out = new_props;
1425 	return (0);
1426 
1427 error:
1428 	nvlist_free(new_props);
1429 	*props_out = NULL;
1430 	return (ret);
1431 }
1432 
1433 int
zfs_crypto_rewrap(zfs_handle_t * zhp,nvlist_t * raw_props,boolean_t inheritkey)1434 zfs_crypto_rewrap(zfs_handle_t *zhp, nvlist_t *raw_props, boolean_t inheritkey)
1435 {
1436 	int ret;
1437 	char errbuf[1024];
1438 	boolean_t is_encroot;
1439 	nvlist_t *props = NULL;
1440 	uint8_t *wkeydata = NULL;
1441 	uint_t wkeylen = 0;
1442 	dcp_cmd_t cmd = (inheritkey) ? DCP_CMD_INHERIT : DCP_CMD_NEW_KEY;
1443 	uint64_t crypt, pcrypt, keystatus, pkeystatus;
1444 	uint64_t keyformat = ZFS_KEYFORMAT_NONE;
1445 	zfs_handle_t *pzhp = NULL;
1446 	char *keylocation = NULL;
1447 	char origin_name[MAXNAMELEN];
1448 	char prop_keylocation[MAXNAMELEN];
1449 	char parent_name[ZFS_MAX_DATASET_NAME_LEN];
1450 
1451 	(void) snprintf(errbuf, sizeof (errbuf),
1452 	    dgettext(TEXT_DOMAIN, "Key change error"));
1453 
1454 	/* check that encryption is enabled for the pool */
1455 	if (!encryption_feature_is_enabled(zhp->zpool_hdl)) {
1456 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1457 		    "Encryption feature not enabled."));
1458 		ret = EINVAL;
1459 		goto error;
1460 	}
1461 
1462 	/* get crypt from dataset */
1463 	crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
1464 	if (crypt == ZIO_CRYPT_OFF) {
1465 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1466 		    "Dataset not encrypted."));
1467 		ret = EINVAL;
1468 		goto error;
1469 	}
1470 
1471 	/* get the encryption root of the dataset */
1472 	ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
1473 	if (ret != 0) {
1474 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1475 		    "Failed to get encryption root for '%s'."),
1476 		    zfs_get_name(zhp));
1477 		goto error;
1478 	}
1479 
1480 	/* Clones use their origin's key and cannot rewrap it */
1481 	ret = zfs_prop_get(zhp, ZFS_PROP_ORIGIN, origin_name,
1482 	    sizeof (origin_name), NULL, NULL, 0, B_TRUE);
1483 	if (ret == 0 && strcmp(origin_name, "") != 0) {
1484 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1485 		    "Keys cannot be changed on clones."));
1486 		ret = EINVAL;
1487 		goto error;
1488 	}
1489 
1490 	/* validate the provided properties */
1491 	ret = zfs_crypto_verify_rewrap_nvlist(zhp, raw_props, inheritkey,
1492 	    &props, errbuf);
1493 	if (ret != 0)
1494 		goto error;
1495 
1496 	/*
1497 	 * If the user wants to use the inheritkey variant of this function
1498 	 * we don't need to collect any crypto arguments.
1499 	 */
1500 	if (!inheritkey) {
1501 		/*
1502 		 * Load keyformat and keylocation from the nvlist. Fetch from
1503 		 * the dataset properties if not specified.
1504 		 */
1505 		(void) nvlist_lookup_uint64(props,
1506 		    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), &keyformat);
1507 		(void) nvlist_lookup_string(props,
1508 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
1509 
1510 		if (is_encroot) {
1511 			/*
1512 			 * If this is already an ecryption root, just keep
1513 			 * any properties not set by the user.
1514 			 */
1515 			if (keyformat == ZFS_KEYFORMAT_NONE) {
1516 				keyformat = zfs_prop_get_int(zhp,
1517 				    ZFS_PROP_KEYFORMAT);
1518 				ret = nvlist_add_uint64(props,
1519 				    zfs_prop_to_name(ZFS_PROP_KEYFORMAT),
1520 				    keyformat);
1521 			}
1522 
1523 			if (keylocation == NULL) {
1524 				ret = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,
1525 				    prop_keylocation, sizeof (prop_keylocation),
1526 				    NULL, NULL, 0, B_TRUE);
1527 				if (ret != 0) {
1528 					zfs_error_aux(zhp->zfs_hdl,
1529 					    dgettext(TEXT_DOMAIN, "Failed to "
1530 					    "get existing keylocation "
1531 					    "property."));
1532 					goto error;
1533 				}
1534 
1535 				keylocation = prop_keylocation;
1536 			}
1537 		} else {
1538 			/* need a new key for non-encryption roots */
1539 			if (keyformat == ZFS_KEYFORMAT_NONE) {
1540 				ret = EINVAL;
1541 				zfs_error_aux(zhp->zfs_hdl,
1542 				    dgettext(TEXT_DOMAIN, "Keyformat required "
1543 				    "for new encryption root."));
1544 				goto error;
1545 			}
1546 
1547 			/* default to prompt if no keylocation is specified */
1548 			if (keylocation == NULL) {
1549 				keylocation = "prompt";
1550 				ret = nvlist_add_string(props,
1551 				    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
1552 				    keylocation);
1553 				if (ret != 0)
1554 					goto error;
1555 			}
1556 		}
1557 
1558 		/* fetch the new wrapping key and associated properties */
1559 		ret = populate_create_encryption_params_nvlists(zhp->zfs_hdl,
1560 		    zhp, B_TRUE, keyformat, keylocation, props, &wkeydata,
1561 		    &wkeylen);
1562 		if (ret != 0)
1563 			goto error;
1564 	} else {
1565 		/* check that zhp is an encryption root */
1566 		if (!is_encroot) {
1567 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1568 			    "Key inheriting can only be performed on "
1569 			    "encryption roots."));
1570 			ret = EINVAL;
1571 			goto error;
1572 		}
1573 
1574 		/* get the parent's name */
1575 		ret = zfs_parent_name(zhp, parent_name, sizeof (parent_name));
1576 		if (ret != 0) {
1577 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1578 			    "Root dataset cannot inherit key."));
1579 			ret = EINVAL;
1580 			goto error;
1581 		}
1582 
1583 		/* get a handle to the parent */
1584 		pzhp = make_dataset_handle(zhp->zfs_hdl, parent_name);
1585 		if (pzhp == NULL) {
1586 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1587 			    "Failed to lookup parent."));
1588 			ret = ENOENT;
1589 			goto error;
1590 		}
1591 
1592 		/* parent must be encrypted */
1593 		pcrypt = zfs_prop_get_int(pzhp, ZFS_PROP_ENCRYPTION);
1594 		if (pcrypt == ZIO_CRYPT_OFF) {
1595 			zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1596 			    "Parent must be encrypted."));
1597 			ret = EINVAL;
1598 			goto error;
1599 		}
1600 
1601 		/* check that the parent's key is loaded */
1602 		pkeystatus = zfs_prop_get_int(pzhp, ZFS_PROP_KEYSTATUS);
1603 		if (pkeystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1604 			zfs_error_aux(pzhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1605 			    "Parent key must be loaded."));
1606 			ret = EACCES;
1607 			goto error;
1608 		}
1609 	}
1610 
1611 	/* check that the key is loaded */
1612 	keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
1613 	if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
1614 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1615 		    "Key must be loaded."));
1616 		ret = EACCES;
1617 		goto error;
1618 	}
1619 
1620 	/* call the ioctl */
1621 	ret = lzc_change_key(zhp->zfs_name, cmd, props, wkeydata, wkeylen);
1622 	if (ret != 0) {
1623 		switch (ret) {
1624 		case EINVAL:
1625 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1626 			    "Invalid properties for key change."));
1627 			break;
1628 		case EACCES:
1629 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1630 			    "Key is not currently loaded."));
1631 			break;
1632 		}
1633 		(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1634 	}
1635 
1636 	if (pzhp != NULL)
1637 		zfs_close(pzhp);
1638 	if (props != NULL)
1639 		nvlist_free(props);
1640 	if (wkeydata != NULL)
1641 		free(wkeydata);
1642 
1643 	return (ret);
1644 
1645 error:
1646 	if (pzhp != NULL)
1647 		zfs_close(pzhp);
1648 	if (props != NULL)
1649 		nvlist_free(props);
1650 	if (wkeydata != NULL)
1651 		free(wkeydata);
1652 
1653 	(void) zfs_error(zhp->zfs_hdl, EZFS_CRYPTOFAILED, errbuf);
1654 	return (ret);
1655 }
1656