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