]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cryptsetup/cryptsetup.c
Merge pull request #9274 from poettering/comment-header-cleanup
[thirdparty/systemd.git] / src / cryptsetup / cryptsetup.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <mntent.h>
5 #include <string.h>
6 #include <sys/mman.h>
7
8 #include "sd-device.h"
9
10 #include "alloc-util.h"
11 #include "ask-password-api.h"
12 #include "crypt-util.h"
13 #include "device-util.h"
14 #include "escape.h"
15 #include "fileio.h"
16 #include "log.h"
17 #include "mount-util.h"
18 #include "parse-util.h"
19 #include "path-util.h"
20 #include "string-util.h"
21 #include "strv.h"
22 #include "util.h"
23
24 /* internal helper */
25 #define ANY_LUKS "LUKS"
26
27 static const char *arg_type = NULL; /* ANY_LUKS, CRYPT_LUKS1, CRYPT_LUKS2, CRYPT_TCRYPT or CRYPT_PLAIN */
28 static char *arg_cipher = NULL;
29 static unsigned arg_key_size = 0;
30 static int arg_key_slot = CRYPT_ANY_SLOT;
31 static unsigned arg_keyfile_size = 0;
32 static uint64_t arg_keyfile_offset = 0;
33 static char *arg_hash = NULL;
34 static char *arg_header = NULL;
35 static unsigned arg_tries = 3;
36 static bool arg_readonly = false;
37 static bool arg_verify = false;
38 static bool arg_discards = false;
39 static bool arg_tcrypt_hidden = false;
40 static bool arg_tcrypt_system = false;
41 #ifdef CRYPT_TCRYPT_VERA_MODES
42 static bool arg_tcrypt_veracrypt = false;
43 #endif
44 static char **arg_tcrypt_keyfiles = NULL;
45 static uint64_t arg_offset = 0;
46 static uint64_t arg_skip = 0;
47 static usec_t arg_timeout = USEC_INFINITY;
48
49 /* Options Debian's crypttab knows we don't:
50
51 precheck=
52 check=
53 checkargs=
54 noearly=
55 loud=
56 keyscript=
57 */
58
59 static int parse_one_option(const char *option) {
60 const char *val;
61 int r;
62
63 assert(option);
64
65 /* Handled outside of this tool */
66 if (STR_IN_SET(option, "noauto", "auto", "nofail", "fail", "_netdev"))
67 return 0;
68
69 if ((val = startswith(option, "cipher="))) {
70 r = free_and_strdup(&arg_cipher, val);
71 if (r < 0)
72 return log_oom();
73
74 } else if ((val = startswith(option, "size="))) {
75
76 r = safe_atou(val, &arg_key_size);
77 if (r < 0) {
78 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
79 return 0;
80 }
81
82 if (arg_key_size % 8) {
83 log_error("size= not a multiple of 8, ignoring.");
84 return 0;
85 }
86
87 arg_key_size /= 8;
88
89 } else if ((val = startswith(option, "key-slot="))) {
90
91 arg_type = ANY_LUKS;
92 r = safe_atoi(val, &arg_key_slot);
93 if (r < 0) {
94 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
95 return 0;
96 }
97
98 } else if ((val = startswith(option, "tcrypt-keyfile="))) {
99
100 arg_type = CRYPT_TCRYPT;
101 if (path_is_absolute(val)) {
102 if (strv_extend(&arg_tcrypt_keyfiles, val) < 0)
103 return log_oom();
104 } else
105 log_error("Key file path \"%s\" is not absolute. Ignoring.", val);
106
107 } else if ((val = startswith(option, "keyfile-size="))) {
108
109 r = safe_atou(val, &arg_keyfile_size);
110 if (r < 0) {
111 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
112 return 0;
113 }
114
115 } else if ((val = startswith(option, "keyfile-offset="))) {
116 uint64_t off;
117
118 r = safe_atou64(val, &off);
119 if (r < 0) {
120 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
121 return 0;
122 }
123
124 if ((size_t) off != off) {
125 /* https://gitlab.com/cryptsetup/cryptsetup/issues/359 */
126 log_error("keyfile-offset= value would truncated to %zu, ignoring.", (size_t) off);
127 return 0;
128 }
129
130 arg_keyfile_offset = off;
131
132 } else if ((val = startswith(option, "hash="))) {
133 r = free_and_strdup(&arg_hash, val);
134 if (r < 0)
135 return log_oom();
136
137 } else if ((val = startswith(option, "header="))) {
138 arg_type = ANY_LUKS;
139
140 if (!path_is_absolute(val)) {
141 log_error("Header path \"%s\" is not absolute, refusing.", val);
142 return -EINVAL;
143 }
144
145 if (arg_header) {
146 log_error("Duplicate header= option, refusing.");
147 return -EINVAL;
148 }
149
150 arg_header = strdup(val);
151 if (!arg_header)
152 return log_oom();
153
154 } else if ((val = startswith(option, "tries="))) {
155
156 r = safe_atou(val, &arg_tries);
157 if (r < 0) {
158 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
159 return 0;
160 }
161
162 } else if (STR_IN_SET(option, "readonly", "read-only"))
163 arg_readonly = true;
164 else if (streq(option, "verify"))
165 arg_verify = true;
166 else if (STR_IN_SET(option, "allow-discards", "discard"))
167 arg_discards = true;
168 else if (streq(option, "luks"))
169 arg_type = ANY_LUKS;
170 else if (streq(option, "tcrypt"))
171 arg_type = CRYPT_TCRYPT;
172 else if (streq(option, "tcrypt-hidden")) {
173 arg_type = CRYPT_TCRYPT;
174 arg_tcrypt_hidden = true;
175 } else if (streq(option, "tcrypt-system")) {
176 arg_type = CRYPT_TCRYPT;
177 arg_tcrypt_system = true;
178 } else if (streq(option, "tcrypt-veracrypt")) {
179 #ifdef CRYPT_TCRYPT_VERA_MODES
180 arg_type = CRYPT_TCRYPT;
181 arg_tcrypt_veracrypt = true;
182 #else
183 log_error("This version of cryptsetup does not support tcrypt-veracrypt; refusing.");
184 return -EINVAL;
185 #endif
186 } else if (STR_IN_SET(option, "plain", "swap", "tmp"))
187 arg_type = CRYPT_PLAIN;
188 else if ((val = startswith(option, "timeout="))) {
189
190 r = parse_sec_fix_0(val, &arg_timeout);
191 if (r < 0) {
192 log_error_errno(r, "Failed to parse %s, ignoring: %m", option);
193 return 0;
194 }
195
196 } else if ((val = startswith(option, "offset="))) {
197
198 r = safe_atou64(val, &arg_offset);
199 if (r < 0)
200 return log_error_errno(r, "Failed to parse %s: %m", option);
201
202 } else if ((val = startswith(option, "skip="))) {
203
204 r = safe_atou64(val, &arg_skip);
205 if (r < 0)
206 return log_error_errno(r, "Failed to parse %s: %m", option);
207
208 } else if (!streq(option, "none"))
209 log_warning("Encountered unknown /etc/crypttab option '%s', ignoring.", option);
210
211 return 0;
212 }
213
214 static int parse_options(const char *options) {
215 const char *word, *state;
216 size_t l;
217 int r;
218
219 assert(options);
220
221 FOREACH_WORD_SEPARATOR(word, l, options, ",", state) {
222 _cleanup_free_ char *o;
223
224 o = strndup(word, l);
225 if (!o)
226 return -ENOMEM;
227 r = parse_one_option(o);
228 if (r < 0)
229 return r;
230 }
231
232 /* sanity-check options */
233 if (arg_type != NULL && !streq(arg_type, CRYPT_PLAIN)) {
234 if (arg_offset)
235 log_warning("offset= ignored with type %s", arg_type);
236 if (arg_skip)
237 log_warning("skip= ignored with type %s", arg_type);
238 }
239
240 return 0;
241 }
242
243 static char* disk_description(const char *path) {
244
245 static const char name_fields[] =
246 "ID_PART_ENTRY_NAME\0"
247 "DM_NAME\0"
248 "ID_MODEL_FROM_DATABASE\0"
249 "ID_MODEL\0";
250
251 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
252 struct stat st;
253 const char *i;
254 int r;
255
256 assert(path);
257
258 if (stat(path, &st) < 0)
259 return NULL;
260
261 if (!S_ISBLK(st.st_mode))
262 return NULL;
263
264 r = sd_device_new_from_devnum(&device, 'b', st.st_rdev);
265 if (r < 0)
266 return NULL;
267
268 NULSTR_FOREACH(i, name_fields) {
269 const char *name;
270
271 r = sd_device_get_property_value(device, i, &name);
272 if (r >= 0 && !isempty(name))
273 return strdup(name);
274 }
275
276 return NULL;
277 }
278
279 static char *disk_mount_point(const char *label) {
280 _cleanup_free_ char *device = NULL;
281 _cleanup_endmntent_ FILE *f = NULL;
282 struct mntent *m;
283
284 /* Yeah, we don't support native systemd unit files here for now */
285
286 if (asprintf(&device, "/dev/mapper/%s", label) < 0)
287 return NULL;
288
289 f = setmntent("/etc/fstab", "re");
290 if (!f)
291 return NULL;
292
293 while ((m = getmntent(f)))
294 if (path_equal(m->mnt_fsname, device))
295 return strdup(m->mnt_dir);
296
297 return NULL;
298 }
299
300 static int get_password(const char *vol, const char *src, usec_t until, bool accept_cached, char ***ret) {
301 _cleanup_free_ char *description = NULL, *name_buffer = NULL, *mount_point = NULL, *text = NULL, *disk_path = NULL;
302 _cleanup_strv_free_erase_ char **passwords = NULL;
303 const char *name = NULL;
304 char **p, *id;
305 int r = 0;
306
307 assert(vol);
308 assert(src);
309 assert(ret);
310
311 description = disk_description(src);
312 mount_point = disk_mount_point(vol);
313
314 disk_path = cescape(src);
315 if (!disk_path)
316 return log_oom();
317
318 if (description && streq(vol, description))
319 /* If the description string is simply the
320 * volume name, then let's not show this
321 * twice */
322 description = mfree(description);
323
324 if (mount_point && description)
325 r = asprintf(&name_buffer, "%s (%s) on %s", description, vol, mount_point);
326 else if (mount_point)
327 r = asprintf(&name_buffer, "%s on %s", vol, mount_point);
328 else if (description)
329 r = asprintf(&name_buffer, "%s (%s)", description, vol);
330
331 if (r < 0)
332 return log_oom();
333
334 name = name_buffer ? name_buffer : vol;
335
336 if (asprintf(&text, "Please enter passphrase for disk %s!", name) < 0)
337 return log_oom();
338
339 id = strjoina("cryptsetup:", disk_path);
340
341 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", until,
342 ASK_PASSWORD_PUSH_CACHE | (accept_cached*ASK_PASSWORD_ACCEPT_CACHED),
343 &passwords);
344 if (r < 0)
345 return log_error_errno(r, "Failed to query password: %m");
346
347 if (arg_verify) {
348 _cleanup_strv_free_erase_ char **passwords2 = NULL;
349
350 assert(strv_length(passwords) == 1);
351
352 if (asprintf(&text, "Please enter passphrase for disk %s! (verification)", name) < 0)
353 return log_oom();
354
355 id = strjoina("cryptsetup-verification:", disk_path);
356
357 r = ask_password_auto(text, "drive-harddisk", id, "cryptsetup", until, ASK_PASSWORD_PUSH_CACHE, &passwords2);
358 if (r < 0)
359 return log_error_errno(r, "Failed to query verification password: %m");
360
361 assert(strv_length(passwords2) == 1);
362
363 if (!streq(passwords[0], passwords2[0])) {
364 log_warning("Passwords did not match, retrying.");
365 return -EAGAIN;
366 }
367 }
368
369 strv_uniq(passwords);
370
371 STRV_FOREACH(p, passwords) {
372 char *c;
373
374 if (strlen(*p)+1 >= arg_key_size)
375 continue;
376
377 /* Pad password if necessary */
378 c = new(char, arg_key_size);
379 if (!c)
380 return log_oom();
381
382 strncpy(c, *p, arg_key_size);
383 free(*p);
384 *p = c;
385 }
386
387 *ret = TAKE_PTR(passwords);
388
389 return 0;
390 }
391
392 static int attach_tcrypt(
393 struct crypt_device *cd,
394 const char *name,
395 const char *key_file,
396 char **passwords,
397 uint32_t flags) {
398
399 int r = 0;
400 _cleanup_free_ char *passphrase = NULL;
401 struct crypt_params_tcrypt params = {
402 .flags = CRYPT_TCRYPT_LEGACY_MODES,
403 .keyfiles = (const char **)arg_tcrypt_keyfiles,
404 .keyfiles_count = strv_length(arg_tcrypt_keyfiles)
405 };
406
407 assert(cd);
408 assert(name);
409 assert(key_file || (passwords && passwords[0]));
410
411 if (arg_tcrypt_hidden)
412 params.flags |= CRYPT_TCRYPT_HIDDEN_HEADER;
413
414 if (arg_tcrypt_system)
415 params.flags |= CRYPT_TCRYPT_SYSTEM_HEADER;
416
417 #ifdef CRYPT_TCRYPT_VERA_MODES
418 if (arg_tcrypt_veracrypt)
419 params.flags |= CRYPT_TCRYPT_VERA_MODES;
420 #endif
421
422 if (key_file) {
423 r = read_one_line_file(key_file, &passphrase);
424 if (r < 0) {
425 log_error_errno(r, "Failed to read password file '%s': %m", key_file);
426 return -EAGAIN;
427 }
428
429 params.passphrase = passphrase;
430 } else
431 params.passphrase = passwords[0];
432 params.passphrase_size = strlen(params.passphrase);
433
434 r = crypt_load(cd, CRYPT_TCRYPT, &params);
435 if (r < 0) {
436 if (key_file && r == -EPERM) {
437 log_error("Failed to activate using password file '%s'.", key_file);
438 return -EAGAIN;
439 }
440 return r;
441 }
442
443 return crypt_activate_by_volume_key(cd, name, NULL, 0, flags);
444 }
445
446 static int attach_luks_or_plain(struct crypt_device *cd,
447 const char *name,
448 const char *key_file,
449 const char *data_device,
450 char **passwords,
451 uint32_t flags) {
452 int r = 0;
453 bool pass_volume_key = false;
454
455 assert(cd);
456 assert(name);
457 assert(key_file || passwords);
458
459 if (!arg_type || STR_IN_SET(arg_type, ANY_LUKS, CRYPT_LUKS1)) {
460 r = crypt_load(cd, CRYPT_LUKS, NULL);
461 if (r < 0) {
462 log_error("crypt_load() failed on device %s.\n", crypt_get_device_name(cd));
463 return r;
464 }
465
466 if (data_device)
467 r = crypt_set_data_device(cd, data_device);
468 }
469
470 if ((!arg_type && r < 0) || streq_ptr(arg_type, CRYPT_PLAIN)) {
471 struct crypt_params_plain params = {
472 .offset = arg_offset,
473 .skip = arg_skip,
474 };
475 const char *cipher, *cipher_mode;
476 _cleanup_free_ char *truncated_cipher = NULL;
477
478 if (arg_hash) {
479 /* plain isn't a real hash type. it just means "use no hash" */
480 if (!streq(arg_hash, "plain"))
481 params.hash = arg_hash;
482 } else if (!key_file)
483 /* for CRYPT_PLAIN, the behaviour of cryptsetup
484 * package is to not hash when a key file is provided */
485 params.hash = "ripemd160";
486
487 if (arg_cipher) {
488 size_t l;
489
490 l = strcspn(arg_cipher, "-");
491 truncated_cipher = strndup(arg_cipher, l);
492 if (!truncated_cipher)
493 return log_oom();
494
495 cipher = truncated_cipher;
496 cipher_mode = arg_cipher[l] ? arg_cipher+l+1 : "plain";
497 } else {
498 cipher = "aes";
499 cipher_mode = "cbc-essiv:sha256";
500 }
501
502 /* for CRYPT_PLAIN limit reads
503 * from keyfile to key length, and
504 * ignore keyfile-size */
505 arg_keyfile_size = arg_key_size;
506
507 /* In contrast to what the name
508 * crypt_setup() might suggest this
509 * doesn't actually format anything,
510 * it just configures encryption
511 * parameters when used for plain
512 * mode. */
513 r = crypt_format(cd, CRYPT_PLAIN, cipher, cipher_mode, NULL, NULL, arg_keyfile_size, &params);
514
515 /* hash == NULL implies the user passed "plain" */
516 pass_volume_key = (params.hash == NULL);
517 }
518
519 if (r < 0)
520 return log_error_errno(r, "Loading of cryptographic parameters failed: %m");
521
522 log_info("Set cipher %s, mode %s, key size %i bits for device %s.",
523 crypt_get_cipher(cd),
524 crypt_get_cipher_mode(cd),
525 crypt_get_volume_key_size(cd)*8,
526 crypt_get_device_name(cd));
527
528 if (key_file) {
529 r = crypt_activate_by_keyfile_offset(cd, name, arg_key_slot, key_file, arg_keyfile_size, arg_keyfile_offset, flags);
530 if (r < 0) {
531 log_error_errno(r, "Failed to activate with key file '%s': %m", key_file);
532 return -EAGAIN;
533 }
534 } else {
535 char **p;
536
537 STRV_FOREACH(p, passwords) {
538 if (pass_volume_key)
539 r = crypt_activate_by_volume_key(cd, name, *p, arg_key_size, flags);
540 else
541 r = crypt_activate_by_passphrase(cd, name, arg_key_slot, *p, strlen(*p), flags);
542
543 if (r >= 0)
544 break;
545 }
546 }
547
548 return r;
549 }
550
551 static int help(void) {
552
553 printf("%s attach VOLUME SOURCEDEVICE [PASSWORD] [OPTIONS]\n"
554 "%s detach VOLUME\n\n"
555 "Attaches or detaches an encrypted block device.\n",
556 program_invocation_short_name,
557 program_invocation_short_name);
558
559 return 0;
560 }
561
562 int main(int argc, char *argv[]) {
563 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
564 int r = -EINVAL;
565
566 if (argc <= 1) {
567 r = help();
568 goto finish;
569 }
570
571 if (argc < 3) {
572 log_error("This program requires at least two arguments.");
573 goto finish;
574 }
575
576 log_set_target(LOG_TARGET_AUTO);
577 log_parse_environment();
578 log_open();
579
580 umask(0022);
581
582 if (streq(argv[1], "attach")) {
583 uint32_t flags = 0;
584 unsigned tries;
585 usec_t until;
586 crypt_status_info status;
587 const char *key_file = NULL;
588
589 /* Arguments: systemd-cryptsetup attach VOLUME SOURCE-DEVICE [PASSWORD] [OPTIONS] */
590
591 if (argc < 4) {
592 log_error("attach requires at least two arguments.");
593 goto finish;
594 }
595
596 if (argc >= 5 &&
597 argv[4][0] &&
598 !streq(argv[4], "-") &&
599 !streq(argv[4], "none")) {
600
601 if (!path_is_absolute(argv[4]))
602 log_error("Password file path '%s' is not absolute. Ignoring.", argv[4]);
603 else
604 key_file = argv[4];
605 }
606
607 if (argc >= 6 && argv[5][0] && !streq(argv[5], "-")) {
608 if (parse_options(argv[5]) < 0)
609 goto finish;
610 }
611
612 /* A delicious drop of snake oil */
613 mlockall(MCL_FUTURE);
614
615 if (arg_header) {
616 log_debug("LUKS header: %s", arg_header);
617 r = crypt_init(&cd, arg_header);
618 } else
619 r = crypt_init(&cd, argv[3]);
620 if (r < 0) {
621 log_error_errno(r, "crypt_init() failed: %m");
622 goto finish;
623 }
624
625 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
626
627 status = crypt_status(cd, argv[2]);
628 if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) {
629 log_info("Volume %s already active.", argv[2]);
630 r = 0;
631 goto finish;
632 }
633
634 if (arg_readonly)
635 flags |= CRYPT_ACTIVATE_READONLY;
636
637 if (arg_discards)
638 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
639
640 if (arg_timeout == USEC_INFINITY)
641 until = 0;
642 else
643 until = now(CLOCK_MONOTONIC) + arg_timeout;
644
645 arg_key_size = (arg_key_size > 0 ? arg_key_size : (256 / 8));
646
647 if (key_file) {
648 struct stat st;
649
650 /* Ideally we'd do this on the open fd, but since this is just a
651 * warning it's OK to do this in two steps. */
652 if (stat(key_file, &st) >= 0 && S_ISREG(st.st_mode) && (st.st_mode & 0005))
653 log_warning("Key file %s is world-readable. This is not a good idea!", key_file);
654 }
655
656 for (tries = 0; arg_tries == 0 || tries < arg_tries; tries++) {
657 _cleanup_strv_free_erase_ char **passwords = NULL;
658
659 if (!key_file) {
660 r = get_password(argv[2], argv[3], until, tries == 0 && !arg_verify, &passwords);
661 if (r == -EAGAIN)
662 continue;
663 if (r < 0)
664 goto finish;
665 }
666
667 if (streq_ptr(arg_type, CRYPT_TCRYPT))
668 r = attach_tcrypt(cd, argv[2], key_file, passwords, flags);
669 else
670 r = attach_luks_or_plain(cd,
671 argv[2],
672 key_file,
673 arg_header ? argv[3] : NULL,
674 passwords,
675 flags);
676 if (r >= 0)
677 break;
678 if (r == -EAGAIN) {
679 key_file = NULL;
680 continue;
681 }
682 if (r != -EPERM) {
683 log_error_errno(r, "Failed to activate: %m");
684 goto finish;
685 }
686
687 log_warning("Invalid passphrase.");
688 }
689
690 if (arg_tries != 0 && tries >= arg_tries) {
691 log_error("Too many attempts; giving up.");
692 r = -EPERM;
693 goto finish;
694 }
695
696 } else if (streq(argv[1], "detach")) {
697
698 r = crypt_init_by_name(&cd, argv[2]);
699 if (r == -ENODEV) {
700 log_info("Volume %s already inactive.", argv[2]);
701 r = 0;
702 goto finish;
703 }
704 if (r < 0) {
705 log_error_errno(r, "crypt_init_by_name() failed: %m");
706 goto finish;
707 }
708
709 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
710
711 r = crypt_deactivate(cd, argv[2]);
712 if (r < 0) {
713 log_error_errno(r, "Failed to deactivate: %m");
714 goto finish;
715 }
716
717 } else {
718 log_error("Unknown verb %s.", argv[1]);
719 goto finish;
720 }
721
722 r = 0;
723
724 finish:
725 free(arg_cipher);
726 free(arg_hash);
727 free(arg_header);
728 strv_free(arg_tcrypt_keyfiles);
729
730 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
731 }