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