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