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