]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cryptsetup/cryptsetup-generator.c
Merge pull request #13217 from poettering/TODO-updates
[thirdparty/systemd.git] / src / cryptsetup / cryptsetup-generator.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <sys/stat.h>
6 #include <sys/types.h>
7
8 #include "alloc-util.h"
9 #include "dropin.h"
10 #include "escape.h"
11 #include "fd-util.h"
12 #include "fileio.h"
13 #include "fstab-util.h"
14 #include "generator.h"
15 #include "hashmap.h"
16 #include "id128-util.h"
17 #include "log.h"
18 #include "mkdir.h"
19 #include "parse-util.h"
20 #include "path-util.h"
21 #include "proc-cmdline.h"
22 #include "specifier.h"
23 #include "string-util.h"
24 #include "strv.h"
25 #include "unit-name.h"
26 #include "util.h"
27
28 typedef struct crypto_device {
29 char *uuid;
30 char *keyfile;
31 char *keydev;
32 char *name;
33 char *options;
34 bool create;
35 } crypto_device;
36
37 static const char *arg_dest = NULL;
38 static bool arg_enabled = true;
39 static bool arg_read_crypttab = true;
40 static bool arg_whitelist = false;
41 static Hashmap *arg_disks = NULL;
42 static char *arg_default_options = NULL;
43 static char *arg_default_keyfile = NULL;
44
45 STATIC_DESTRUCTOR_REGISTER(arg_disks, hashmap_freep);
46 STATIC_DESTRUCTOR_REGISTER(arg_default_options, freep);
47 STATIC_DESTRUCTOR_REGISTER(arg_default_keyfile, freep);
48
49 static int split_keyspec(const char *keyspec, char **keyfile, char **keydev) {
50 _cleanup_free_ char *kfile = NULL, *kdev = NULL;
51 char *c;
52
53 assert(keyspec);
54 assert(keyfile);
55 assert(keydev);
56
57 c = strrchr(keyspec, ':');
58 if (c) {
59 kfile = strndup(keyspec, c-keyspec);
60 kdev = strdup(c + 1);
61 if (!*kfile || !*kdev)
62 return log_oom();
63 } else {
64 /* No keydev specified */
65 kfile = strdup(keyspec);
66 kdev = NULL;
67 if (!*kfile)
68 return log_oom();
69 }
70
71 *keyfile = TAKE_PTR(kfile);
72 *keydev = TAKE_PTR(kdev);
73
74 return 0;
75 }
76
77 static int generate_keydev_mount(const char *name, const char *keydev, const char *keydev_timeout, bool canfail, char **unit, char **mount) {
78 _cleanup_free_ char *u = NULL, *what = NULL, *where = NULL, *name_escaped = NULL, *device_unit = NULL;
79 _cleanup_fclose_ FILE *f = NULL;
80 int r;
81 usec_t timeout_us;
82
83 assert(name);
84 assert(keydev);
85 assert(unit);
86 assert(mount);
87
88 r = mkdir_parents("/run/systemd/cryptsetup", 0755);
89 if (r < 0)
90 return r;
91
92 r = mkdir("/run/systemd/cryptsetup", 0700);
93 if (r < 0 && errno != EEXIST)
94 return -errno;
95
96 name_escaped = cescape(name);
97 if (!name_escaped)
98 return -ENOMEM;
99
100 where = strjoin("/run/systemd/cryptsetup/keydev-", name_escaped);
101 if (!where)
102 return -ENOMEM;
103
104 r = mkdir(where, 0700);
105 if (r < 0 && errno != EEXIST)
106 return -errno;
107
108 r = unit_name_from_path(where, ".mount", &u);
109 if (r < 0)
110 return r;
111
112 r = generator_open_unit_file(arg_dest, NULL, u, &f);
113 if (r < 0)
114 return r;
115
116 what = fstab_node_to_udev_node(keydev);
117 if (!what)
118 return -ENOMEM;
119
120 fprintf(f,
121 "[Unit]\n"
122 "DefaultDependencies=no\n\n"
123 "[Mount]\n"
124 "What=%s\n"
125 "Where=%s\n"
126 "Options=ro%s\n", what, where, canfail ? ",nofail" : "");
127
128 if (keydev_timeout) {
129 r = parse_sec_fix_0(keydev_timeout, &timeout_us);
130 if (r >= 0) {
131 r = unit_name_from_path(what, ".device", &device_unit);
132 if (r < 0)
133 return log_error_errno(r, "Failed to generate unit name: %m");
134
135 r = write_drop_in_format(arg_dest, device_unit, 90, "device-timeout",
136 "# Automatically generated by systemd-cryptsetup-generator \n\n"
137 "[Unit]\nJobRunningTimeoutSec=%s", keydev_timeout);
138 if (r < 0)
139 return log_error_errno(r, "Failed to write device drop-in: %m");
140
141 } else
142 log_warning_errno(r, "Failed to parse %s, ignoring: %m", keydev_timeout);
143
144 }
145
146 r = fflush_and_check(f);
147 if (r < 0)
148 return r;
149
150 *unit = TAKE_PTR(u);
151 *mount = TAKE_PTR(where);
152
153 return 0;
154 }
155
156 static int print_dependencies(FILE *f, const char* device_path) {
157 int r;
158
159 if (STR_IN_SET(device_path, "-", "none"))
160 /* None, nothing to do */
161 return 0;
162
163 if (PATH_IN_SET(device_path, "/dev/urandom", "/dev/random", "/dev/hw_random")) {
164 /* RNG device, add random dep */
165 fputs("After=systemd-random-seed.service\n", f);
166 return 0;
167 }
168
169 _cleanup_free_ char *udev_node = fstab_node_to_udev_node(device_path);
170 if (!udev_node)
171 return log_oom();
172
173 if (path_equal(udev_node, "/dev/null"))
174 return 0;
175
176 if (path_startswith(udev_node, "/dev/")) {
177 /* We are dealing with a block device, add dependency for correspoding unit */
178 _cleanup_free_ char *unit = NULL;
179
180 r = unit_name_from_path(udev_node, ".device", &unit);
181 if (r < 0)
182 return log_error_errno(r, "Failed to generate unit name: %m");
183
184 fprintf(f, "After=%1$s\nRequires=%1$s\n", unit);
185 } else {
186 /* Regular file, add mount dependency */
187 _cleanup_free_ char *escaped_path = specifier_escape(device_path);
188 if (!escaped_path)
189 return log_oom();
190
191 fprintf(f, "RequiresMountsFor=%s\n", escaped_path);
192 }
193
194 return 0;
195 }
196
197 static int create_disk(
198 const char *name,
199 const char *device,
200 const char *password,
201 const char *keydev,
202 const char *options) {
203
204 _cleanup_free_ char *n = NULL, *d = NULL, *u = NULL, *e = NULL,
205 *keydev_mount = NULL, *keyfile_timeout_value = NULL, *password_escaped = NULL,
206 *filtered = NULL, *u_escaped = NULL, *filtered_escaped = NULL, *name_escaped = NULL, *header_path = NULL;
207 _cleanup_fclose_ FILE *f = NULL;
208 const char *dmname;
209 bool noauto, nofail, tmp, swap, netdev;
210 int r, detached_header, keyfile_can_timeout;
211
212 assert(name);
213 assert(device);
214
215 noauto = fstab_test_yes_no_option(options, "noauto\0" "auto\0");
216 nofail = fstab_test_yes_no_option(options, "nofail\0" "fail\0");
217 tmp = fstab_test_option(options, "tmp\0");
218 swap = fstab_test_option(options, "swap\0");
219 netdev = fstab_test_option(options, "_netdev\0");
220
221 keyfile_can_timeout = fstab_filter_options(options, "keyfile-timeout\0", NULL, &keyfile_timeout_value, NULL);
222 if (keyfile_can_timeout < 0)
223 return log_error_errno(keyfile_can_timeout, "Failed to parse keyfile-timeout= option value: %m");
224
225 detached_header = fstab_filter_options(options, "header\0", NULL, &header_path, NULL);
226 if (detached_header < 0)
227 return log_error_errno(detached_header, "Failed to parse header= option value: %m");
228
229 if (tmp && swap)
230 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
231 "Device '%s' cannot be both 'tmp' and 'swap'. Ignoring.",
232 name);
233
234 name_escaped = specifier_escape(name);
235 if (!name_escaped)
236 return log_oom();
237
238 e = unit_name_escape(name);
239 if (!e)
240 return log_oom();
241
242 u = fstab_node_to_udev_node(device);
243 if (!u)
244 return log_oom();
245
246 r = unit_name_build("systemd-cryptsetup", e, ".service", &n);
247 if (r < 0)
248 return log_error_errno(r, "Failed to generate unit name: %m");
249
250 u_escaped = specifier_escape(u);
251 if (!u_escaped)
252 return log_oom();
253
254 r = unit_name_from_path(u, ".device", &d);
255 if (r < 0)
256 return log_error_errno(r, "Failed to generate unit name: %m");
257
258 if (keydev && !password)
259 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
260 "Key device is specified, but path to the password file is missing.");
261
262 r = generator_open_unit_file(arg_dest, NULL, n, &f);
263 if (r < 0)
264 return r;
265
266 fprintf(f,
267 "[Unit]\n"
268 "Description=Cryptography Setup for %%I\n"
269 "Documentation=man:crypttab(5) man:systemd-cryptsetup-generator(8) man:systemd-cryptsetup@.service(8)\n"
270 "SourcePath=/etc/crypttab\n"
271 "DefaultDependencies=no\n"
272 "Conflicts=umount.target\n"
273 "IgnoreOnIsolate=true\n"
274 "After=%s\n",
275 netdev ? "remote-fs-pre.target" : "cryptsetup-pre.target");
276
277 if (password) {
278 password_escaped = specifier_escape(password);
279 if (!password_escaped)
280 return log_oom();
281 }
282
283 if (keydev) {
284 _cleanup_free_ char *unit = NULL, *p = NULL;
285
286 r = generate_keydev_mount(name, keydev, keyfile_timeout_value, keyfile_can_timeout > 0, &unit, &keydev_mount);
287 if (r < 0)
288 return log_error_errno(r, "Failed to generate keydev mount unit: %m");
289
290 p = path_join(keydev_mount, password_escaped);
291 if (!p)
292 return log_oom();
293
294 free_and_replace(password_escaped, p);
295
296 fprintf(f, "After=%s\n", unit);
297 if (keyfile_can_timeout > 0)
298 fprintf(f, "Wants=%s\n", unit);
299 else
300 fprintf(f, "Requires=%s\n", unit);
301 }
302
303 if (!nofail)
304 fprintf(f,
305 "Before=%s\n",
306 netdev ? "remote-cryptsetup.target" : "cryptsetup.target");
307
308 if (password && !keydev) {
309 r = print_dependencies(f, password);
310 if (r < 0)
311 return r;
312 }
313
314 /* Check if a header option was specified */
315 if (detached_header > 0) {
316 r = print_dependencies(f, header_path);
317 if (r < 0)
318 return r;
319 }
320
321 if (path_startswith(u, "/dev/")) {
322 fprintf(f,
323 "BindsTo=%s\n"
324 "After=%s\n"
325 "Before=umount.target\n",
326 d, d);
327
328 if (swap)
329 fputs("Before=dev-mapper-%i.swap\n",
330 f);
331 } else
332 /* For loopback devices, add systemd-tmpfiles-setup-dev.service
333 dependency to ensure that loopback support is available in
334 the kernel (/dev/loop-control needs to exist) */
335 fprintf(f,
336 "RequiresMountsFor=%s\n"
337 "Requires=systemd-tmpfiles-setup-dev.service\n"
338 "After=systemd-tmpfiles-setup-dev.service\n",
339 u_escaped);
340
341 r = generator_write_timeouts(arg_dest, device, name, options, &filtered);
342 if (r < 0)
343 return r;
344
345 if (filtered) {
346 filtered_escaped = specifier_escape(filtered);
347 if (!filtered_escaped)
348 return log_oom();
349 }
350
351 fprintf(f,
352 "\n[Service]\n"
353 "Type=oneshot\n"
354 "RemainAfterExit=yes\n"
355 "TimeoutSec=0\n" /* the binary handles timeouts anyway */
356 "KeyringMode=shared\n" /* make sure we can share cached keys among instances */
357 "OOMScoreAdjust=500\n" /* unlocking can allocate a lot of memory if Argon2 is used */
358 "ExecStart=" SYSTEMD_CRYPTSETUP_PATH " attach '%s' '%s' '%s' '%s'\n"
359 "ExecStop=" SYSTEMD_CRYPTSETUP_PATH " detach '%s'\n",
360 name_escaped, u_escaped, strempty(password_escaped), strempty(filtered_escaped),
361 name_escaped);
362
363 if (tmp)
364 fprintf(f,
365 "ExecStartPost=/sbin/mke2fs '/dev/mapper/%s'\n",
366 name_escaped);
367
368 if (swap)
369 fprintf(f,
370 "ExecStartPost=/sbin/mkswap '/dev/mapper/%s'\n",
371 name_escaped);
372
373 if (keydev)
374 fprintf(f,
375 "ExecStartPost=-" UMOUNT_PATH " %s\n\n",
376 keydev_mount);
377
378 r = fflush_and_check(f);
379 if (r < 0)
380 return log_error_errno(r, "Failed to write unit file %s: %m", n);
381
382 if (!noauto) {
383 r = generator_add_symlink(arg_dest,
384 netdev ? "remote-cryptsetup.target" : "cryptsetup.target",
385 nofail ? "wants" : "requires", n);
386 if (r < 0)
387 return r;
388 }
389
390 dmname = strjoina("dev-mapper-", e, ".device");
391 r = generator_add_symlink(arg_dest, dmname, "requires", n);
392 if (r < 0)
393 return r;
394
395 if (!noauto && !nofail) {
396 r = write_drop_in(arg_dest, dmname, 90, "device-timeout",
397 "# Automatically generated by systemd-cryptsetup-generator \n\n"
398 "[Unit]\nJobTimeoutSec=0");
399 if (r < 0)
400 return log_error_errno(r, "Failed to write device drop-in: %m");
401 }
402
403 return 0;
404 }
405
406 static crypto_device* crypt_device_free(crypto_device *d) {
407 if (!d)
408 return NULL;
409
410 free(d->uuid);
411 free(d->keyfile);
412 free(d->keydev);
413 free(d->name);
414 free(d->options);
415 return mfree(d);
416 }
417
418 static crypto_device *get_crypto_device(const char *uuid) {
419 int r;
420 crypto_device *d;
421
422 assert(uuid);
423
424 d = hashmap_get(arg_disks, uuid);
425 if (!d) {
426 d = new0(struct crypto_device, 1);
427 if (!d)
428 return NULL;
429
430 d->uuid = strdup(uuid);
431 if (!d->uuid)
432 return mfree(d);
433
434 r = hashmap_put(arg_disks, d->uuid, d);
435 if (r < 0) {
436 free(d->uuid);
437 return mfree(d);
438 }
439 }
440
441 return d;
442 }
443
444 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
445 _cleanup_free_ char *uuid = NULL, *uuid_value = NULL;
446 crypto_device *d;
447 int r;
448
449 if (streq(key, "luks")) {
450
451 r = value ? parse_boolean(value) : 1;
452 if (r < 0)
453 log_warning("Failed to parse luks= kernel command line switch %s. Ignoring.", value);
454 else
455 arg_enabled = r;
456
457 } else if (streq(key, "luks.crypttab")) {
458
459 r = value ? parse_boolean(value) : 1;
460 if (r < 0)
461 log_warning("Failed to parse luks.crypttab= kernel command line switch %s. Ignoring.", value);
462 else
463 arg_read_crypttab = r;
464
465 } else if (streq(key, "luks.uuid")) {
466
467 if (proc_cmdline_value_missing(key, value))
468 return 0;
469
470 d = get_crypto_device(startswith(value, "luks-") ? value+5 : value);
471 if (!d)
472 return log_oom();
473
474 d->create = arg_whitelist = true;
475
476 } else if (streq(key, "luks.options")) {
477
478 if (proc_cmdline_value_missing(key, value))
479 return 0;
480
481 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
482 if (r == 2) {
483 d = get_crypto_device(uuid);
484 if (!d)
485 return log_oom();
486
487 free_and_replace(d->options, uuid_value);
488 } else if (free_and_strdup(&arg_default_options, value) < 0)
489 return log_oom();
490
491 } else if (streq(key, "luks.key")) {
492 size_t n;
493 _cleanup_free_ char *keyfile = NULL, *keydev = NULL;
494 const char *keyspec;
495
496 if (proc_cmdline_value_missing(key, value))
497 return 0;
498
499 n = strspn(value, LETTERS DIGITS "-");
500 if (value[n] != '=') {
501 if (free_and_strdup(&arg_default_keyfile, value) < 0)
502 return log_oom();
503 return 0;
504 }
505
506 uuid = strndup(value, n);
507 if (!uuid)
508 return log_oom();
509
510 if (!id128_is_valid(uuid)) {
511 log_warning("Failed to parse luks.key= kernel command line switch. UUID is invalid, ignoring.");
512 return 0;
513 }
514
515 d = get_crypto_device(uuid);
516 if (!d)
517 return log_oom();
518
519 keyspec = value + n + 1;
520 r = split_keyspec(keyspec, &keyfile, &keydev);
521 if (r < 0)
522 return r;
523
524 free_and_replace(d->keyfile, keyfile);
525 free_and_replace(d->keydev, keydev);
526
527 } else if (streq(key, "luks.name")) {
528
529 if (proc_cmdline_value_missing(key, value))
530 return 0;
531
532 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
533 if (r == 2) {
534 d = get_crypto_device(uuid);
535 if (!d)
536 return log_oom();
537
538 d->create = arg_whitelist = true;
539
540 free_and_replace(d->name, uuid_value);
541 } else
542 log_warning("Failed to parse luks name switch %s. Ignoring.", value);
543 }
544
545 return 0;
546 }
547
548 static int add_crypttab_devices(void) {
549 _cleanup_fclose_ FILE *f = NULL;
550 unsigned crypttab_line = 0;
551 struct stat st;
552 int r;
553
554 if (!arg_read_crypttab)
555 return 0;
556
557 r = fopen_unlocked("/etc/crypttab", "re", &f);
558 if (r < 0) {
559 if (errno != ENOENT)
560 log_error_errno(errno, "Failed to open /etc/crypttab: %m");
561 return 0;
562 }
563
564 if (fstat(fileno(f), &st) < 0) {
565 log_error_errno(errno, "Failed to stat /etc/crypttab: %m");
566 return 0;
567 }
568
569 for (;;) {
570 _cleanup_free_ char *line = NULL, *name = NULL, *device = NULL, *keydev = NULL, *keyfile = NULL, *keyspec = NULL, *options = NULL;
571 crypto_device *d = NULL;
572 char *l, *uuid;
573 int k;
574
575 r = read_line(f, LONG_LINE_MAX, &line);
576 if (r < 0)
577 return log_error_errno(r, "Failed to read /etc/crypttab: %m");
578 if (r == 0)
579 break;
580
581 crypttab_line++;
582
583 l = strstrip(line);
584 if (IN_SET(l[0], 0, '#'))
585 continue;
586
587 k = sscanf(l, "%ms %ms %ms %ms", &name, &device, &keyspec, &options);
588 if (k < 2 || k > 4) {
589 log_error("Failed to parse /etc/crypttab:%u, ignoring.", crypttab_line);
590 continue;
591 }
592
593 uuid = startswith(device, "UUID=");
594 if (!uuid)
595 uuid = path_startswith(device, "/dev/disk/by-uuid/");
596 if (!uuid)
597 uuid = startswith(name, "luks-");
598 if (uuid)
599 d = hashmap_get(arg_disks, uuid);
600
601 if (arg_whitelist && !d) {
602 log_info("Not creating device '%s' because it was not specified on the kernel command line.", name);
603 continue;
604 }
605
606 r = split_keyspec(keyspec, &keyfile, &keydev);
607 if (r < 0)
608 return r;
609
610 r = create_disk(name, device, keyfile, keydev, (d && d->options) ? d->options : options);
611 if (r < 0)
612 return r;
613
614 if (d)
615 d->create = false;
616 }
617
618 return 0;
619 }
620
621 static int add_proc_cmdline_devices(void) {
622 int r;
623 Iterator i;
624 crypto_device *d;
625
626 HASHMAP_FOREACH(d, arg_disks, i) {
627 const char *options;
628 _cleanup_free_ char *device = NULL;
629
630 if (!d->create)
631 continue;
632
633 if (!d->name) {
634 d->name = strjoin("luks-", d->uuid);
635 if (!d->name)
636 return log_oom();
637 }
638
639 device = strjoin("UUID=", d->uuid);
640 if (!device)
641 return log_oom();
642
643 if (d->options)
644 options = d->options;
645 else if (arg_default_options)
646 options = arg_default_options;
647 else
648 options = "timeout=0";
649
650 r = create_disk(d->name, device, d->keyfile ?: arg_default_keyfile, d->keydev, options);
651 if (r < 0)
652 return r;
653 }
654
655 return 0;
656 }
657
658 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(crypt_device_hash_ops, char, string_hash_func, string_compare_func,
659 crypto_device, crypt_device_free);
660
661 static int run(const char *dest, const char *dest_early, const char *dest_late) {
662 int r;
663
664 assert_se(arg_dest = dest);
665
666 arg_disks = hashmap_new(&crypt_device_hash_ops);
667 if (!arg_disks)
668 return log_oom();
669
670 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
671 if (r < 0)
672 return log_warning_errno(r, "Failed to parse kernel command line: %m");
673
674 if (!arg_enabled)
675 return 0;
676
677 r = add_crypttab_devices();
678 if (r < 0)
679 return r;
680
681 r = add_proc_cmdline_devices();
682 if (r < 0)
683 return r;
684
685 return 0;
686 }
687
688 DEFINE_MAIN_GENERATOR_FUNCTION(run);