]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cryptsetup/cryptsetup-generator.c
tree-wide: assorted coccinelle fixes
[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 const char *arg_crypttab = NULL;
41 static const char *arg_runtime_directory = NULL;
42 static bool arg_allow_list = false;
43 static Hashmap *arg_disks = NULL;
44 static char *arg_default_options = NULL;
45 static char *arg_default_keyfile = NULL;
46
47 STATIC_DESTRUCTOR_REGISTER(arg_disks, hashmap_freep);
48 STATIC_DESTRUCTOR_REGISTER(arg_default_options, freep);
49 STATIC_DESTRUCTOR_REGISTER(arg_default_keyfile, freep);
50
51 static int split_keyspec(const char *keyspec, char **ret_keyfile, char **ret_keydev) {
52 _cleanup_free_ char *keyfile = NULL, *keydev = NULL;
53 const char *c;
54
55 assert(ret_keyfile);
56 assert(ret_keydev);
57
58 if (!keyspec) {
59 *ret_keyfile = *ret_keydev = NULL;
60 return 0;
61 }
62
63 c = strrchr(keyspec, ':');
64 if (c) {
65 /* The keydev part has to be either an absolute path to device node (/dev/something,
66 * /dev/foo/something, or even possibly /dev/foo/something:part), or a fstab device
67 * specification starting with LABEL= or similar. The keyfile part has the same syntax.
68 *
69 * Let's try to guess if the second part looks like a keydev specification, or just part of a
70 * filename with a colon. fstab_node_to_udev_node() will convert the fstab device syntax to
71 * an absolute path. If we didn't get an absolute path, assume that it is just part of the
72 * first keyfile argument. */
73
74 keydev = fstab_node_to_udev_node(c + 1);
75 if (!keydev)
76 return log_oom();
77
78 if (path_is_absolute(keydev))
79 keyfile = strndup(keyspec, c-keyspec);
80 else {
81 log_debug("Keyspec argument contains a colon, but \"%s\" doesn't look like a device specification.\n"
82 "Assuming that \"%s\" is a single device specification.",
83 c + 1, keyspec);
84 keydev = mfree(keydev);
85 c = NULL;
86 }
87 }
88
89 if (!c)
90 /* No keydev specified */
91 keyfile = strdup(keyspec);
92
93 if (!keyfile)
94 return log_oom();
95
96 *ret_keyfile = TAKE_PTR(keyfile);
97 *ret_keydev = TAKE_PTR(keydev);
98
99 return 0;
100 }
101
102 static int generate_keydev_mount(
103 const char *name,
104 const char *keydev,
105 const char *keydev_timeout,
106 bool canfail,
107 char **unit,
108 char **mount) {
109
110 _cleanup_free_ char *u = NULL, *where = NULL, *name_escaped = NULL, *device_unit = NULL;
111 _cleanup_fclose_ FILE *f = NULL;
112 int r;
113 usec_t timeout_us;
114
115 assert(name);
116 assert(keydev);
117 assert(unit);
118 assert(mount);
119
120 r = mkdir_parents(arg_runtime_directory, 0755);
121 if (r < 0)
122 return r;
123
124 r = mkdir(arg_runtime_directory, 0700);
125 if (r < 0 && errno != EEXIST)
126 return -errno;
127
128 name_escaped = cescape(name);
129 if (!name_escaped)
130 return -ENOMEM;
131
132 where = strjoin(arg_runtime_directory, "/keydev-", name_escaped);
133 if (!where)
134 return -ENOMEM;
135
136 r = mkdir(where, 0700);
137 if (r < 0 && errno != EEXIST)
138 return -errno;
139
140 r = unit_name_from_path(where, ".mount", &u);
141 if (r < 0)
142 return r;
143
144 r = generator_open_unit_file(arg_dest, NULL, u, &f);
145 if (r < 0)
146 return r;
147
148 fprintf(f,
149 "[Unit]\n"
150 "DefaultDependencies=no\n\n"
151 "[Mount]\n"
152 "What=%s\n"
153 "Where=%s\n"
154 "Options=ro%s\n", keydev, where, canfail ? ",nofail" : "");
155
156 if (keydev_timeout) {
157 r = parse_sec_fix_0(keydev_timeout, &timeout_us);
158 if (r >= 0) {
159 r = unit_name_from_path(keydev, ".device", &device_unit);
160 if (r < 0)
161 return log_error_errno(r, "Failed to generate unit name: %m");
162
163 r = write_drop_in_format(arg_dest, device_unit, 90, "device-timeout",
164 "# Automatically generated by systemd-cryptsetup-generator \n\n"
165 "[Unit]\nJobRunningTimeoutSec=%s", keydev_timeout);
166 if (r < 0)
167 return log_error_errno(r, "Failed to write device drop-in: %m");
168
169 } else
170 log_warning_errno(r, "Failed to parse %s, ignoring: %m", keydev_timeout);
171
172 }
173
174 r = fflush_and_check(f);
175 if (r < 0)
176 return r;
177
178 *unit = TAKE_PTR(u);
179 *mount = TAKE_PTR(where);
180
181 return 0;
182 }
183
184 static int generate_keydev_umount(const char *name,
185 const char *keydev_mount,
186 char **ret_umount_unit) {
187 _cleanup_fclose_ FILE *f = NULL;
188 _cleanup_free_ char *u = NULL, *name_escaped = NULL, *mount = NULL;
189 int r;
190
191 assert(name);
192 assert(ret_umount_unit);
193
194 name_escaped = cescape(name);
195 if (!name_escaped)
196 return -ENOMEM;
197
198 u = strjoin("keydev-", name_escaped, "-umount.service");
199 if (!u)
200 return -ENOMEM;
201
202 r = unit_name_from_path(keydev_mount, ".mount", &mount);
203 if (r < 0)
204 return r;
205
206 r = generator_open_unit_file(arg_dest, NULL, u, &f);
207 if (r < 0)
208 return r;
209
210 fprintf(f,
211 "[Unit]\n"
212 "DefaultDependencies=no\n"
213 "After=%s\n\n"
214 "[Service]\n"
215 "ExecStart=-" UMOUNT_PATH " %s\n\n", mount, keydev_mount);
216
217 r = fflush_and_check(f);
218 if (r < 0)
219 return r;
220
221 *ret_umount_unit = TAKE_PTR(u);
222 return 0;
223 }
224
225 static int print_dependencies(FILE *f, const char* device_path) {
226 int r;
227
228 if (STR_IN_SET(device_path, "-", "none"))
229 /* None, nothing to do */
230 return 0;
231
232 if (PATH_IN_SET(device_path,
233 "/dev/urandom",
234 "/dev/random",
235 "/dev/hw_random",
236 "/dev/hwrng")) {
237 /* RNG device, add random dep */
238 fputs("After=systemd-random-seed.service\n", f);
239 return 0;
240 }
241
242 _cleanup_free_ char *udev_node = fstab_node_to_udev_node(device_path);
243 if (!udev_node)
244 return log_oom();
245
246 if (path_equal(udev_node, "/dev/null"))
247 return 0;
248
249 if (path_startswith(udev_node, "/dev/")) {
250 /* We are dealing with a block device, add dependency for corresponding unit */
251 _cleanup_free_ char *unit = NULL;
252
253 r = unit_name_from_path(udev_node, ".device", &unit);
254 if (r < 0)
255 return log_error_errno(r, "Failed to generate unit name: %m");
256
257 fprintf(f,
258 "After=%1$s\n"
259 "Requires=%1$s\n", unit);
260 } else {
261 /* Regular file, add mount dependency */
262 _cleanup_free_ char *escaped_path = specifier_escape(device_path);
263 if (!escaped_path)
264 return log_oom();
265
266 fprintf(f, "RequiresMountsFor=%s\n", escaped_path);
267 }
268
269 return 0;
270 }
271
272 static int create_disk(
273 const char *name,
274 const char *device,
275 const char *password,
276 const char *keydev,
277 const char *options,
278 const char *source) {
279
280 _cleanup_free_ char *n = NULL, *d = NULL, *u = NULL, *e = NULL,
281 *keydev_mount = NULL, *keyfile_timeout_value = NULL,
282 *filtered = NULL, *u_escaped = NULL, *name_escaped = NULL, *header_path = NULL, *password_buffer = NULL,
283 *tmp_fstype = NULL;
284 _cleanup_fclose_ FILE *f = NULL;
285 const char *dmname;
286 bool noauto, nofail, swap, netdev, attach_in_initrd;
287 int r, detached_header, keyfile_can_timeout, tmp;
288
289 assert(name);
290 assert(device);
291
292 noauto = fstab_test_yes_no_option(options, "noauto\0" "auto\0");
293 nofail = fstab_test_yes_no_option(options, "nofail\0" "fail\0");
294 swap = fstab_test_option(options, "swap\0");
295 netdev = fstab_test_option(options, "_netdev\0");
296 attach_in_initrd = fstab_test_option(options, "x-initrd.attach\0");
297
298 keyfile_can_timeout = fstab_filter_options(options, "keyfile-timeout\0", NULL, &keyfile_timeout_value, NULL);
299 if (keyfile_can_timeout < 0)
300 return log_error_errno(keyfile_can_timeout, "Failed to parse keyfile-timeout= option value: %m");
301
302 detached_header = fstab_filter_options(options, "header\0", NULL, &header_path, NULL);
303 if (detached_header < 0)
304 return log_error_errno(detached_header, "Failed to parse header= option value: %m");
305
306 tmp = fstab_filter_options(options, "tmp\0", NULL, &tmp_fstype, NULL);
307 if (tmp < 0)
308 return log_error_errno(tmp, "Failed to parse tmp= option value: %m");
309
310 if (tmp && swap)
311 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
312 "Device '%s' cannot be both 'tmp' and 'swap'. Ignoring.",
313 name);
314
315 name_escaped = specifier_escape(name);
316 if (!name_escaped)
317 return log_oom();
318
319 e = unit_name_escape(name);
320 if (!e)
321 return log_oom();
322
323 u = fstab_node_to_udev_node(device);
324 if (!u)
325 return log_oom();
326
327 r = unit_name_build("systemd-cryptsetup", e, ".service", &n);
328 if (r < 0)
329 return log_error_errno(r, "Failed to generate unit name: %m");
330
331 u_escaped = specifier_escape(u);
332 if (!u_escaped)
333 return log_oom();
334
335 r = unit_name_from_path(u, ".device", &d);
336 if (r < 0)
337 return log_error_errno(r, "Failed to generate unit name: %m");
338
339 if (keydev && !password)
340 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
341 "Key device is specified, but path to the password file is missing.");
342
343 r = generator_open_unit_file(arg_dest, NULL, n, &f);
344 if (r < 0)
345 return r;
346
347 r = generator_write_cryptsetup_unit_section(f, source);
348 if (r < 0)
349 return r;
350
351 if (netdev)
352 fprintf(f, "After=remote-fs-pre.target\n");
353
354 /* If initrd takes care of attaching the disk then it should also detach it during shutdown. */
355 if (!attach_in_initrd)
356 fprintf(f, "Conflicts=umount.target\n");
357
358 if (keydev) {
359 _cleanup_free_ char *unit = NULL, *umount_unit = NULL;
360
361 r = generate_keydev_mount(name, keydev, keyfile_timeout_value, keyfile_can_timeout > 0, &unit, &keydev_mount);
362 if (r < 0)
363 return log_error_errno(r, "Failed to generate keydev mount unit: %m");
364
365 r = generate_keydev_umount(name, keydev_mount, &umount_unit);
366 if (r < 0)
367 return log_error_errno(r, "Failed to generate keydev umount unit: %m");
368
369 password_buffer = path_join(keydev_mount, password);
370 if (!password_buffer)
371 return log_oom();
372
373 password = password_buffer;
374
375 fprintf(f, "After=%s\n", unit);
376 if (keyfile_can_timeout > 0)
377 fprintf(f, "Wants=%s\n", unit);
378 else
379 fprintf(f, "Requires=%s\n", unit);
380
381 if (umount_unit)
382 fprintf(f,
383 "Wants=%s\n"
384 "Before=%s\n",
385 umount_unit,
386 umount_unit
387 );
388 }
389
390 if (!nofail)
391 fprintf(f,
392 "Before=%s\n",
393 netdev ? "remote-cryptsetup.target" : "cryptsetup.target");
394
395 if (password && !keydev) {
396 r = print_dependencies(f, password);
397 if (r < 0)
398 return r;
399 }
400
401 /* Check if a header option was specified */
402 if (detached_header > 0) {
403 r = print_dependencies(f, header_path);
404 if (r < 0)
405 return r;
406 }
407
408 if (path_startswith(u, "/dev/"))
409 fprintf(f,
410 "BindsTo=%s\n"
411 "After=%s\n"
412 "Before=umount.target\n",
413 d, d);
414 else
415 /* For loopback devices, add systemd-tmpfiles-setup-dev.service
416 dependency to ensure that loopback support is available in
417 the kernel (/dev/loop-control needs to exist) */
418 fprintf(f,
419 "RequiresMountsFor=%s\n"
420 "Requires=systemd-tmpfiles-setup-dev.service\n"
421 "After=systemd-tmpfiles-setup-dev.service\n",
422 u_escaped);
423
424 r = generator_write_timeouts(arg_dest, device, name, options, &filtered);
425 if (r < 0)
426 log_warning_errno(r, "Failed to write device timeout drop-in: %m");
427
428 r = generator_write_cryptsetup_service_section(f, name, u, password, filtered);
429 if (r < 0)
430 return r;
431
432 if (tmp) {
433 _cleanup_free_ char *tmp_fstype_escaped = NULL;
434
435 if (tmp_fstype) {
436 tmp_fstype_escaped = specifier_escape(tmp_fstype);
437 if (!tmp_fstype_escaped)
438 return log_oom();
439 }
440
441 fprintf(f,
442 "ExecStartPost=" ROOTLIBEXECDIR "/systemd-makefs '%s' '/dev/mapper/%s'\n",
443 tmp_fstype_escaped ?: "ext4", name_escaped);
444 }
445
446 if (swap)
447 fprintf(f,
448 "ExecStartPost=" ROOTLIBEXECDIR "/systemd-makefs swap '/dev/mapper/%s'\n",
449 name_escaped);
450
451 r = fflush_and_check(f);
452 if (r < 0)
453 return log_error_errno(r, "Failed to write unit file %s: %m", n);
454
455 if (!noauto) {
456 r = generator_add_symlink(arg_dest,
457 netdev ? "remote-cryptsetup.target" : "cryptsetup.target",
458 nofail ? "wants" : "requires", n);
459 if (r < 0)
460 return r;
461 }
462
463 dmname = strjoina("dev-mapper-", e, ".device");
464 r = generator_add_symlink(arg_dest, dmname, "requires", n);
465 if (r < 0)
466 return r;
467
468 if (!noauto && !nofail) {
469 r = write_drop_in(arg_dest, dmname, 40, "device-timeout",
470 "# Automatically generated by systemd-cryptsetup-generator\n\n"
471 "[Unit]\nJobTimeoutSec=0");
472 if (r < 0)
473 log_warning_errno(r, "Failed to write device timeout drop-in: %m");
474 }
475
476 return 0;
477 }
478
479 static crypto_device* crypt_device_free(crypto_device *d) {
480 if (!d)
481 return NULL;
482
483 free(d->uuid);
484 free(d->keyfile);
485 free(d->keydev);
486 free(d->name);
487 free(d->options);
488 return mfree(d);
489 }
490
491 static crypto_device *get_crypto_device(const char *uuid) {
492 int r;
493 crypto_device *d;
494
495 assert(uuid);
496
497 d = hashmap_get(arg_disks, uuid);
498 if (!d) {
499 d = new0(struct crypto_device, 1);
500 if (!d)
501 return NULL;
502
503 d->uuid = strdup(uuid);
504 if (!d->uuid)
505 return mfree(d);
506
507 r = hashmap_put(arg_disks, d->uuid, d);
508 if (r < 0) {
509 free(d->uuid);
510 return mfree(d);
511 }
512 }
513
514 return d;
515 }
516
517 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
518 _cleanup_free_ char *uuid = NULL, *uuid_value = NULL;
519 crypto_device *d;
520 int r;
521
522 if (streq(key, "luks")) {
523
524 r = value ? parse_boolean(value) : 1;
525 if (r < 0)
526 log_warning("Failed to parse luks= kernel command line switch %s. Ignoring.", value);
527 else
528 arg_enabled = r;
529
530 } else if (streq(key, "luks.crypttab")) {
531
532 r = value ? parse_boolean(value) : 1;
533 if (r < 0)
534 log_warning("Failed to parse luks.crypttab= kernel command line switch %s. Ignoring.", value);
535 else
536 arg_read_crypttab = r;
537
538 } else if (streq(key, "luks.uuid")) {
539
540 if (proc_cmdline_value_missing(key, value))
541 return 0;
542
543 d = get_crypto_device(startswith(value, "luks-") ?: value);
544 if (!d)
545 return log_oom();
546
547 d->create = arg_allow_list = true;
548
549 } else if (streq(key, "luks.options")) {
550
551 if (proc_cmdline_value_missing(key, value))
552 return 0;
553
554 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
555 if (r == 2) {
556 d = get_crypto_device(uuid);
557 if (!d)
558 return log_oom();
559
560 free_and_replace(d->options, uuid_value);
561 } else if (free_and_strdup(&arg_default_options, value) < 0)
562 return log_oom();
563
564 } else if (streq(key, "luks.key")) {
565 size_t n;
566 _cleanup_free_ char *keyfile = NULL, *keydev = NULL;
567 const char *keyspec;
568
569 if (proc_cmdline_value_missing(key, value))
570 return 0;
571
572 n = strspn(value, LETTERS DIGITS "-");
573 if (value[n] != '=') {
574 if (free_and_strdup(&arg_default_keyfile, value) < 0)
575 return log_oom();
576 return 0;
577 }
578
579 uuid = strndup(value, n);
580 if (!uuid)
581 return log_oom();
582
583 if (!id128_is_valid(uuid)) {
584 log_warning("Failed to parse luks.key= kernel command line switch. UUID is invalid, ignoring.");
585 return 0;
586 }
587
588 d = get_crypto_device(uuid);
589 if (!d)
590 return log_oom();
591
592 keyspec = value + n + 1;
593 r = split_keyspec(keyspec, &keyfile, &keydev);
594 if (r < 0)
595 return r;
596
597 free_and_replace(d->keyfile, keyfile);
598 free_and_replace(d->keydev, keydev);
599
600 } else if (streq(key, "luks.name")) {
601
602 if (proc_cmdline_value_missing(key, value))
603 return 0;
604
605 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
606 if (r == 2) {
607 d = get_crypto_device(uuid);
608 if (!d)
609 return log_oom();
610
611 d->create = arg_allow_list = true;
612
613 free_and_replace(d->name, uuid_value);
614 } else
615 log_warning("Failed to parse luks name switch %s. Ignoring.", value);
616 }
617
618 return 0;
619 }
620
621 static int add_crypttab_devices(void) {
622 _cleanup_fclose_ FILE *f = NULL;
623 unsigned crypttab_line = 0;
624 int r;
625
626 if (!arg_read_crypttab)
627 return 0;
628
629 r = fopen_unlocked(arg_crypttab, "re", &f);
630 if (r < 0) {
631 if (errno != ENOENT)
632 log_error_errno(errno, "Failed to open %s: %m", arg_crypttab);
633 return 0;
634 }
635
636 for (;;) {
637 _cleanup_free_ char *line = NULL, *name = NULL, *device = NULL, *keyspec = NULL, *options = NULL, *keyfile = NULL, *keydev = NULL;
638 crypto_device *d = NULL;
639 char *l, *uuid;
640 int k;
641
642 r = read_line(f, LONG_LINE_MAX, &line);
643 if (r < 0)
644 return log_error_errno(r, "Failed to read %s: %m", arg_crypttab);
645 if (r == 0)
646 break;
647
648 crypttab_line++;
649
650 l = strstrip(line);
651 if (IN_SET(l[0], 0, '#'))
652 continue;
653
654 k = sscanf(l, "%ms %ms %ms %ms", &name, &device, &keyspec, &options);
655 if (k < 2 || k > 4) {
656 log_error("Failed to parse %s:%u, ignoring.", arg_crypttab, crypttab_line);
657 continue;
658 }
659
660 uuid = startswith(device, "UUID=");
661 if (!uuid)
662 uuid = path_startswith(device, "/dev/disk/by-uuid/");
663 if (!uuid)
664 uuid = startswith(name, "luks-");
665 if (uuid)
666 d = hashmap_get(arg_disks, uuid);
667
668 if (arg_allow_list && !d) {
669 log_info("Not creating device '%s' because it was not specified on the kernel command line.", name);
670 continue;
671 }
672
673 r = split_keyspec(keyspec, &keyfile, &keydev);
674 if (r < 0)
675 return r;
676
677 r = create_disk(name, device, keyfile, keydev, (d && d->options) ? d->options : options, arg_crypttab);
678 if (r < 0)
679 return r;
680
681 if (d)
682 d->create = false;
683 }
684
685 return 0;
686 }
687
688 static int add_proc_cmdline_devices(void) {
689 int r;
690 crypto_device *d;
691
692 HASHMAP_FOREACH(d, arg_disks) {
693 _cleanup_free_ char *device = NULL;
694
695 if (!d->create)
696 continue;
697
698 if (!d->name) {
699 d->name = strjoin("luks-", d->uuid);
700 if (!d->name)
701 return log_oom();
702 }
703
704 device = strjoin("UUID=", d->uuid);
705 if (!device)
706 return log_oom();
707
708 r = create_disk(d->name,
709 device,
710 d->keyfile ?: arg_default_keyfile,
711 d->keydev,
712 d->options ?: arg_default_options,
713 "/proc/cmdline");
714 if (r < 0)
715 return r;
716 }
717
718 return 0;
719 }
720
721 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(crypt_device_hash_ops, char, string_hash_func, string_compare_func,
722 crypto_device, crypt_device_free);
723
724 static int run(const char *dest, const char *dest_early, const char *dest_late) {
725 int r;
726
727 assert_se(arg_dest = dest);
728
729 arg_crypttab = getenv("SYSTEMD_CRYPTTAB") ?: "/etc/crypttab";
730 arg_runtime_directory = getenv("RUNTIME_DIRECTORY") ?: "/run/systemd/cryptsetup";
731
732 arg_disks = hashmap_new(&crypt_device_hash_ops);
733 if (!arg_disks)
734 return log_oom();
735
736 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
737 if (r < 0)
738 return log_warning_errno(r, "Failed to parse kernel command line: %m");
739
740 if (!arg_enabled)
741 return 0;
742
743 r = add_crypttab_devices();
744 if (r < 0)
745 return r;
746
747 r = add_proc_cmdline_devices();
748 if (r < 0)
749 return r;
750
751 return 0;
752 }
753
754 DEFINE_MAIN_GENERATOR_FUNCTION(run);