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