]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cryptsetup/cryptsetup-generator.c
7da13dc2076c28ab8d788209a0436ad3f8a5fadc
[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 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
128 "Device '%s' cannot be both 'tmp' and 'swap'. Ignoring.",
129 name);
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 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
163 "Key device is specified, but path to the password file is missing.");
164
165 r = generator_open_unit_file(arg_dest, NULL, n, &f);
166 if (r < 0)
167 return r;
168
169 fprintf(f,
170 "[Unit]\n"
171 "Description=Cryptography Setup for %%I\n"
172 "Documentation=man:crypttab(5) man:systemd-cryptsetup-generator(8) man:systemd-cryptsetup@.service(8)\n"
173 "SourcePath=/etc/crypttab\n"
174 "DefaultDependencies=no\n"
175 "Conflicts=umount.target\n"
176 "IgnoreOnIsolate=true\n"
177 "After=%s\n",
178 netdev ? "remote-fs-pre.target" : "cryptsetup-pre.target");
179
180 if (keydev) {
181 _cleanup_free_ char *unit = NULL, *p = NULL;
182
183 r = generate_keydev_mount(name, keydev, &unit, &keydev_mount);
184 if (r < 0)
185 return log_error_errno(r, "Failed to generate keydev mount unit: %m");
186
187 p = prefix_root(keydev_mount, password_escaped);
188 if (!p)
189 return log_oom();
190
191 free_and_replace(password_escaped, p);
192 }
193
194 if (!nofail)
195 fprintf(f,
196 "Before=%s\n",
197 netdev ? "remote-cryptsetup.target" : "cryptsetup.target");
198
199 if (password) {
200 if (PATH_IN_SET(password, "/dev/urandom", "/dev/random", "/dev/hw_random"))
201 fputs("After=systemd-random-seed.service\n", f);
202 else if (!STR_IN_SET(password, "-", "none")) {
203 _cleanup_free_ char *uu;
204
205 uu = fstab_node_to_udev_node(password);
206 if (!uu)
207 return log_oom();
208
209 if (!path_equal(uu, "/dev/null")) {
210
211 if (path_startswith(uu, "/dev/")) {
212 _cleanup_free_ char *dd = NULL;
213
214 r = unit_name_from_path(uu, ".device", &dd);
215 if (r < 0)
216 return log_error_errno(r, "Failed to generate unit name: %m");
217
218 fprintf(f, "After=%1$s\nRequires=%1$s\n", dd);
219 } else
220 fprintf(f, "RequiresMountsFor=%s\n", password_escaped);
221 }
222 }
223 }
224
225 if (path_startswith(u, "/dev/")) {
226 fprintf(f,
227 "BindsTo=%s\n"
228 "After=%s\n"
229 "Before=umount.target\n",
230 d, d);
231
232 if (swap)
233 fputs("Before=dev-mapper-%i.swap\n",
234 f);
235 } else
236 /* For loopback devices, add systemd-tmpfiles-setup-dev.service
237 dependency to ensure that loopback support is available in
238 the kernel (/dev/loop-control needs to exist) */
239 fprintf(f,
240 "RequiresMountsFor=%s\n"
241 "Requires=systemd-tmpfiles-setup-dev.service\n"
242 "After=systemd-tmpfiles-setup-dev.service\n",
243 u_escaped);
244
245 r = generator_write_timeouts(arg_dest, device, name, options, &filtered);
246 if (r < 0)
247 return r;
248
249 if (filtered) {
250 filtered_escaped = specifier_escape(filtered);
251 if (!filtered_escaped)
252 return log_oom();
253 }
254
255 fprintf(f,
256 "\n[Service]\n"
257 "Type=oneshot\n"
258 "RemainAfterExit=yes\n"
259 "TimeoutSec=0\n" /* the binary handles timeouts anyway */
260 "KeyringMode=shared\n" /* make sure we can share cached keys among instances */
261 "ExecStart=" SYSTEMD_CRYPTSETUP_PATH " attach '%s' '%s' '%s' '%s'\n"
262 "ExecStop=" SYSTEMD_CRYPTSETUP_PATH " detach '%s'\n",
263 name_escaped, u_escaped, strempty(password_escaped), strempty(filtered_escaped),
264 name_escaped);
265
266 if (tmp)
267 fprintf(f,
268 "ExecStartPost=/sbin/mke2fs '/dev/mapper/%s'\n",
269 name_escaped);
270
271 if (swap)
272 fprintf(f,
273 "ExecStartPost=/sbin/mkswap '/dev/mapper/%s'\n",
274 name_escaped);
275
276 if (keydev)
277 fprintf(f,
278 "ExecStartPost=" UMOUNT_PATH " %s\n\n",
279 keydev_mount);
280
281 r = fflush_and_check(f);
282 if (r < 0)
283 return log_error_errno(r, "Failed to write unit file %s: %m", n);
284
285 if (!noauto) {
286 r = generator_add_symlink(arg_dest, d, "wants", n);
287 if (r < 0)
288 return r;
289
290 r = generator_add_symlink(arg_dest,
291 netdev ? "remote-cryptsetup.target" : "cryptsetup.target",
292 nofail ? "wants" : "requires", n);
293 if (r < 0)
294 return r;
295 }
296
297 dmname = strjoina("dev-mapper-", e, ".device");
298 r = generator_add_symlink(arg_dest, dmname, "requires", n);
299 if (r < 0)
300 return r;
301
302 if (!noauto && !nofail) {
303 r = write_drop_in(arg_dest, dmname, 90, "device-timeout",
304 "# Automatically generated by systemd-cryptsetup-generator \n\n"
305 "[Unit]\nJobTimeoutSec=0");
306 if (r < 0)
307 return log_error_errno(r, "Failed to write device drop-in: %m");
308 }
309
310 return 0;
311 }
312
313 static void crypt_device_free(crypto_device *d) {
314 free(d->uuid);
315 free(d->keyfile);
316 free(d->keydev);
317 free(d->name);
318 free(d->options);
319 free(d);
320 }
321
322 static crypto_device *get_crypto_device(const char *uuid) {
323 int r;
324 crypto_device *d;
325
326 assert(uuid);
327
328 d = hashmap_get(arg_disks, uuid);
329 if (!d) {
330 d = new0(struct crypto_device, 1);
331 if (!d)
332 return NULL;
333
334 d->create = false;
335 d->keyfile = d->options = d->name = NULL;
336
337 d->uuid = strdup(uuid);
338 if (!d->uuid)
339 return mfree(d);
340
341 r = hashmap_put(arg_disks, d->uuid, d);
342 if (r < 0) {
343 free(d->uuid);
344 return mfree(d);
345 }
346 }
347
348 return d;
349 }
350
351 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
352 _cleanup_free_ char *uuid = NULL, *uuid_value = NULL;
353 crypto_device *d;
354 int r;
355
356 if (streq(key, "luks")) {
357
358 r = value ? parse_boolean(value) : 1;
359 if (r < 0)
360 log_warning("Failed to parse luks= kernel command line switch %s. Ignoring.", value);
361 else
362 arg_enabled = r;
363
364 } else if (streq(key, "luks.crypttab")) {
365
366 r = value ? parse_boolean(value) : 1;
367 if (r < 0)
368 log_warning("Failed to parse luks.crypttab= kernel command line switch %s. Ignoring.", value);
369 else
370 arg_read_crypttab = r;
371
372 } else if (streq(key, "luks.uuid")) {
373
374 if (proc_cmdline_value_missing(key, value))
375 return 0;
376
377 d = get_crypto_device(startswith(value, "luks-") ? value+5 : value);
378 if (!d)
379 return log_oom();
380
381 d->create = arg_whitelist = true;
382
383 } else if (streq(key, "luks.options")) {
384
385 if (proc_cmdline_value_missing(key, value))
386 return 0;
387
388 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
389 if (r == 2) {
390 d = get_crypto_device(uuid);
391 if (!d)
392 return log_oom();
393
394 free_and_replace(d->options, uuid_value);
395 } else if (free_and_strdup(&arg_default_options, value) < 0)
396 return log_oom();
397
398 } else if (streq(key, "luks.key")) {
399 size_t n;
400 _cleanup_free_ char *keyfile = NULL, *keydev = NULL;
401 char *c;
402 const char *keyspec;
403
404 if (proc_cmdline_value_missing(key, value))
405 return 0;
406
407 n = strspn(value, LETTERS DIGITS "-");
408 if (value[n] != '=') {
409 if (free_and_strdup(&arg_default_keyfile, value) < 0)
410 return log_oom();
411 return 0;
412 }
413
414 uuid = strndup(value, n);
415 if (!uuid)
416 return log_oom();
417
418 if (!id128_is_valid(uuid)) {
419 log_warning("Failed to parse luks.key= kernel command line switch. UUID is invalid, ignoring.");
420 return 0;
421 }
422
423 d = get_crypto_device(uuid);
424 if (!d)
425 return log_oom();
426
427 keyspec = value + n + 1;
428 c = strrchr(keyspec, ':');
429 if (c) {
430 *c = '\0';
431 keyfile = strdup(keyspec);
432 keydev = strdup(c + 1);
433
434 if (!keyfile || !keydev)
435 return log_oom();
436 } else {
437 /* No keydev specified */
438 keyfile = strdup(keyspec);
439 if (!keyfile)
440 return log_oom();
441 }
442
443 free_and_replace(d->keyfile, keyfile);
444 free_and_replace(d->keydev, keydev);
445 } else if (streq(key, "luks.name")) {
446
447 if (proc_cmdline_value_missing(key, value))
448 return 0;
449
450 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
451 if (r == 2) {
452 d = get_crypto_device(uuid);
453 if (!d)
454 return log_oom();
455
456 d->create = arg_whitelist = true;
457
458 free_and_replace(d->name, uuid_value);
459 } else
460 log_warning("Failed to parse luks name switch %s. Ignoring.", value);
461 }
462
463 return 0;
464 }
465
466 static int add_crypttab_devices(void) {
467 _cleanup_fclose_ FILE *f = NULL;
468 unsigned crypttab_line = 0;
469 struct stat st;
470 int r;
471
472 if (!arg_read_crypttab)
473 return 0;
474
475 f = fopen("/etc/crypttab", "re");
476 if (!f) {
477 if (errno != ENOENT)
478 log_error_errno(errno, "Failed to open /etc/crypttab: %m");
479 return 0;
480 }
481
482 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
483
484 if (fstat(fileno(f), &st) < 0) {
485 log_error_errno(errno, "Failed to stat /etc/crypttab: %m");
486 return 0;
487 }
488
489 for (;;) {
490 _cleanup_free_ char *line = NULL, *name = NULL, *device = NULL, *keyfile = NULL, *options = NULL;
491 crypto_device *d = NULL;
492 char *l, *uuid;
493 int k;
494
495 r = read_line(f, LONG_LINE_MAX, &line);
496 if (r < 0)
497 return log_error_errno(r, "Failed to read /etc/crypttab: %m");
498 if (r == 0)
499 break;
500
501 crypttab_line++;
502
503 l = strstrip(line);
504 if (IN_SET(l[0], 0, '#'))
505 continue;
506
507 k = sscanf(l, "%ms %ms %ms %ms", &name, &device, &keyfile, &options);
508 if (k < 2 || k > 4) {
509 log_error("Failed to parse /etc/crypttab:%u, ignoring.", crypttab_line);
510 continue;
511 }
512
513 uuid = startswith(device, "UUID=");
514 if (!uuid)
515 uuid = path_startswith(device, "/dev/disk/by-uuid/");
516 if (!uuid)
517 uuid = startswith(name, "luks-");
518 if (uuid)
519 d = hashmap_get(arg_disks, uuid);
520
521 if (arg_whitelist && !d) {
522 log_info("Not creating device '%s' because it was not specified on the kernel command line.", name);
523 continue;
524 }
525
526 r = create_disk(name, device, NULL, keyfile, (d && d->options) ? d->options : options);
527 if (r < 0)
528 return r;
529
530 if (d)
531 d->create = false;
532 }
533
534 return 0;
535 }
536
537 static int add_proc_cmdline_devices(void) {
538 int r;
539 Iterator i;
540 crypto_device *d;
541
542 HASHMAP_FOREACH(d, arg_disks, i) {
543 const char *options;
544 _cleanup_free_ char *device = NULL;
545
546 if (!d->create)
547 continue;
548
549 if (!d->name) {
550 d->name = strappend("luks-", d->uuid);
551 if (!d->name)
552 return log_oom();
553 }
554
555 device = strappend("UUID=", d->uuid);
556 if (!device)
557 return log_oom();
558
559 if (d->options)
560 options = d->options;
561 else if (arg_default_options)
562 options = arg_default_options;
563 else
564 options = "timeout=0";
565
566 r = create_disk(d->name, device, d->keydev, d->keyfile ?: arg_default_keyfile, options);
567 if (r < 0)
568 return r;
569 }
570
571 return 0;
572 }
573
574 int main(int argc, char *argv[]) {
575 int r;
576
577 if (argc > 1 && argc != 4) {
578 log_error("This program takes three or no arguments.");
579 return EXIT_FAILURE;
580 }
581
582 if (argc > 1)
583 arg_dest = argv[1];
584
585 log_setup_generator();
586
587 arg_disks = hashmap_new(&string_hash_ops);
588 if (!arg_disks) {
589 r = log_oom();
590 goto finish;
591 }
592
593 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
594 if (r < 0) {
595 log_warning_errno(r, "Failed to parse kernel command line: %m");
596 goto finish;
597 }
598
599 if (!arg_enabled) {
600 r = 0;
601 goto finish;
602 }
603
604 r = add_crypttab_devices();
605 if (r < 0)
606 goto finish;
607
608 r = add_proc_cmdline_devices();
609 if (r < 0)
610 goto finish;
611
612 r = 0;
613
614 finish:
615 hashmap_free_with_destructor(arg_disks, crypt_device_free);
616 free(arg_default_options);
617 free(arg_default_keyfile);
618
619 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
620 }