]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cryptsetup/cryptsetup-generator.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[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 = NULL;
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_DESTRUCTOR_REGISTER(arg_disks, hashmap_freep);
44 STATIC_DESTRUCTOR_REGISTER(arg_default_options, freep);
45 STATIC_DESTRUCTOR_REGISTER(arg_default_keyfile, freep);
46
47 static int generate_keydev_mount(const char *name, const char *keydev, char **unit, char **mount) {
48 _cleanup_free_ char *u = NULL, *what = NULL, *where = NULL, *name_escaped = NULL;
49 _cleanup_fclose_ FILE *f = NULL;
50 int r;
51
52 assert(name);
53 assert(keydev);
54 assert(unit);
55 assert(mount);
56
57 r = mkdir_parents("/run/systemd/cryptsetup", 0755);
58 if (r < 0)
59 return r;
60
61 r = mkdir("/run/systemd/cryptsetup", 0700);
62 if (r < 0 && errno != EEXIST)
63 return -errno;
64
65 name_escaped = cescape(name);
66 if (!name_escaped)
67 return -ENOMEM;
68
69 where = strjoin("/run/systemd/cryptsetup/keydev-", name_escaped);
70 if (!where)
71 return -ENOMEM;
72
73 r = mkdir(where, 0700);
74 if (r < 0 && errno != EEXIST)
75 return -errno;
76
77 r = unit_name_from_path(where, ".mount", &u);
78 if (r < 0)
79 return r;
80
81 r = generator_open_unit_file(arg_dest, NULL, u, &f);
82 if (r < 0)
83 return r;
84
85 what = fstab_node_to_udev_node(keydev);
86 if (!what)
87 return -ENOMEM;
88
89 fprintf(f,
90 "[Unit]\n"
91 "DefaultDependencies=no\n\n"
92 "[Mount]\n"
93 "What=%s\n"
94 "Where=%s\n"
95 "Options=ro\n", what, where);
96
97 r = fflush_and_check(f);
98 if (r < 0)
99 return r;
100
101 *unit = TAKE_PTR(u);
102 *mount = TAKE_PTR(where);
103
104 return 0;
105 }
106
107 static int create_disk(
108 const char *name,
109 const char *device,
110 const char *keydev,
111 const char *password,
112 const char *options) {
113
114 _cleanup_free_ char *n = NULL, *d = NULL, *u = NULL, *e = NULL,
115 *filtered = NULL, *u_escaped = NULL, *password_escaped = NULL, *filtered_escaped = NULL, *name_escaped = NULL, *keydev_mount = NULL;
116 _cleanup_fclose_ FILE *f = NULL;
117 const char *dmname;
118 bool noauto, nofail, tmp, swap, netdev;
119 int r;
120
121 assert(name);
122 assert(device);
123
124 noauto = fstab_test_yes_no_option(options, "noauto\0" "auto\0");
125 nofail = fstab_test_yes_no_option(options, "nofail\0" "fail\0");
126 tmp = fstab_test_option(options, "tmp\0");
127 swap = fstab_test_option(options, "swap\0");
128 netdev = fstab_test_option(options, "_netdev\0");
129
130 if (tmp && swap)
131 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
132 "Device '%s' cannot be both 'tmp' and 'swap'. Ignoring.",
133 name);
134
135 name_escaped = specifier_escape(name);
136 if (!name_escaped)
137 return log_oom();
138
139 e = unit_name_escape(name);
140 if (!e)
141 return log_oom();
142
143 u = fstab_node_to_udev_node(device);
144 if (!u)
145 return log_oom();
146
147 r = unit_name_build("systemd-cryptsetup", e, ".service", &n);
148 if (r < 0)
149 return log_error_errno(r, "Failed to generate unit name: %m");
150
151 u_escaped = specifier_escape(u);
152 if (!u_escaped)
153 return log_oom();
154
155 r = unit_name_from_path(u, ".device", &d);
156 if (r < 0)
157 return log_error_errno(r, "Failed to generate unit name: %m");
158
159 if (password) {
160 password_escaped = specifier_escape(password);
161 if (!password_escaped)
162 return log_oom();
163 }
164
165 if (keydev && !password)
166 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
167 "Key device is specified, but path to the password file is missing.");
168
169 r = generator_open_unit_file(arg_dest, NULL, n, &f);
170 if (r < 0)
171 return r;
172
173 fprintf(f,
174 "[Unit]\n"
175 "Description=Cryptography Setup for %%I\n"
176 "Documentation=man:crypttab(5) man:systemd-cryptsetup-generator(8) man:systemd-cryptsetup@.service(8)\n"
177 "SourcePath=/etc/crypttab\n"
178 "DefaultDependencies=no\n"
179 "Conflicts=umount.target\n"
180 "IgnoreOnIsolate=true\n"
181 "After=%s\n",
182 netdev ? "remote-fs-pre.target" : "cryptsetup-pre.target");
183
184 if (keydev) {
185 _cleanup_free_ char *unit = NULL, *p = NULL;
186
187 r = generate_keydev_mount(name, keydev, &unit, &keydev_mount);
188 if (r < 0)
189 return log_error_errno(r, "Failed to generate keydev mount unit: %m");
190
191 p = prefix_root(keydev_mount, password_escaped);
192 if (!p)
193 return log_oom();
194
195 free_and_replace(password_escaped, p);
196 }
197
198 if (!nofail)
199 fprintf(f,
200 "Before=%s\n",
201 netdev ? "remote-cryptsetup.target" : "cryptsetup.target");
202
203 if (password) {
204 if (PATH_IN_SET(password, "/dev/urandom", "/dev/random", "/dev/hw_random"))
205 fputs("After=systemd-random-seed.service\n", f);
206 else if (!STR_IN_SET(password, "-", "none")) {
207 _cleanup_free_ char *uu;
208
209 uu = fstab_node_to_udev_node(password);
210 if (!uu)
211 return log_oom();
212
213 if (!path_equal(uu, "/dev/null")) {
214
215 if (path_startswith(uu, "/dev/")) {
216 _cleanup_free_ char *dd = NULL;
217
218 r = unit_name_from_path(uu, ".device", &dd);
219 if (r < 0)
220 return log_error_errno(r, "Failed to generate unit name: %m");
221
222 fprintf(f, "After=%1$s\nRequires=%1$s\n", dd);
223 } else
224 fprintf(f, "RequiresMountsFor=%s\n", password_escaped);
225 }
226 }
227 }
228
229 if (path_startswith(u, "/dev/")) {
230 fprintf(f,
231 "BindsTo=%s\n"
232 "After=%s\n"
233 "Before=umount.target\n",
234 d, d);
235
236 if (swap)
237 fputs("Before=dev-mapper-%i.swap\n",
238 f);
239 } else
240 /* For loopback devices, add systemd-tmpfiles-setup-dev.service
241 dependency to ensure that loopback support is available in
242 the kernel (/dev/loop-control needs to exist) */
243 fprintf(f,
244 "RequiresMountsFor=%s\n"
245 "Requires=systemd-tmpfiles-setup-dev.service\n"
246 "After=systemd-tmpfiles-setup-dev.service\n",
247 u_escaped);
248
249 r = generator_write_timeouts(arg_dest, device, name, options, &filtered);
250 if (r < 0)
251 return r;
252
253 if (filtered) {
254 filtered_escaped = specifier_escape(filtered);
255 if (!filtered_escaped)
256 return log_oom();
257 }
258
259 fprintf(f,
260 "\n[Service]\n"
261 "Type=oneshot\n"
262 "RemainAfterExit=yes\n"
263 "TimeoutSec=0\n" /* the binary handles timeouts anyway */
264 "KeyringMode=shared\n" /* make sure we can share cached keys among instances */
265 "ExecStart=" SYSTEMD_CRYPTSETUP_PATH " attach '%s' '%s' '%s' '%s'\n"
266 "ExecStop=" SYSTEMD_CRYPTSETUP_PATH " detach '%s'\n",
267 name_escaped, u_escaped, strempty(password_escaped), strempty(filtered_escaped),
268 name_escaped);
269
270 if (tmp)
271 fprintf(f,
272 "ExecStartPost=/sbin/mke2fs '/dev/mapper/%s'\n",
273 name_escaped);
274
275 if (swap)
276 fprintf(f,
277 "ExecStartPost=/sbin/mkswap '/dev/mapper/%s'\n",
278 name_escaped);
279
280 if (keydev)
281 fprintf(f,
282 "ExecStartPost=" UMOUNT_PATH " %s\n\n",
283 keydev_mount);
284
285 r = fflush_and_check(f);
286 if (r < 0)
287 return log_error_errno(r, "Failed to write unit file %s: %m", n);
288
289 if (!noauto) {
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 crypto_device* crypt_device_free(crypto_device *d) {
314 if (!d)
315 return NULL;
316
317 free(d->uuid);
318 free(d->keyfile);
319 free(d->keydev);
320 free(d->name);
321 free(d->options);
322 return mfree(d);
323 }
324
325 static crypto_device *get_crypto_device(const char *uuid) {
326 int r;
327 crypto_device *d;
328
329 assert(uuid);
330
331 d = hashmap_get(arg_disks, uuid);
332 if (!d) {
333 d = new0(struct crypto_device, 1);
334 if (!d)
335 return NULL;
336
337 d->create = false;
338 d->keyfile = d->options = d->name = NULL;
339
340 d->uuid = strdup(uuid);
341 if (!d->uuid)
342 return mfree(d);
343
344 r = hashmap_put(arg_disks, d->uuid, d);
345 if (r < 0) {
346 free(d->uuid);
347 return mfree(d);
348 }
349 }
350
351 return d;
352 }
353
354 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
355 _cleanup_free_ char *uuid = NULL, *uuid_value = NULL;
356 crypto_device *d;
357 int r;
358
359 if (streq(key, "luks")) {
360
361 r = value ? parse_boolean(value) : 1;
362 if (r < 0)
363 log_warning("Failed to parse luks= kernel command line switch %s. Ignoring.", value);
364 else
365 arg_enabled = r;
366
367 } else if (streq(key, "luks.crypttab")) {
368
369 r = value ? parse_boolean(value) : 1;
370 if (r < 0)
371 log_warning("Failed to parse luks.crypttab= kernel command line switch %s. Ignoring.", value);
372 else
373 arg_read_crypttab = r;
374
375 } else if (streq(key, "luks.uuid")) {
376
377 if (proc_cmdline_value_missing(key, value))
378 return 0;
379
380 d = get_crypto_device(startswith(value, "luks-") ? value+5 : value);
381 if (!d)
382 return log_oom();
383
384 d->create = arg_whitelist = true;
385
386 } else if (streq(key, "luks.options")) {
387
388 if (proc_cmdline_value_missing(key, value))
389 return 0;
390
391 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
392 if (r == 2) {
393 d = get_crypto_device(uuid);
394 if (!d)
395 return log_oom();
396
397 free_and_replace(d->options, uuid_value);
398 } else if (free_and_strdup(&arg_default_options, value) < 0)
399 return log_oom();
400
401 } else if (streq(key, "luks.key")) {
402 size_t n;
403 _cleanup_free_ char *keyfile = NULL, *keydev = NULL;
404 char *c;
405 const char *keyspec;
406
407 if (proc_cmdline_value_missing(key, value))
408 return 0;
409
410 n = strspn(value, LETTERS DIGITS "-");
411 if (value[n] != '=') {
412 if (free_and_strdup(&arg_default_keyfile, value) < 0)
413 return log_oom();
414 return 0;
415 }
416
417 uuid = strndup(value, n);
418 if (!uuid)
419 return log_oom();
420
421 if (!id128_is_valid(uuid)) {
422 log_warning("Failed to parse luks.key= kernel command line switch. UUID is invalid, ignoring.");
423 return 0;
424 }
425
426 d = get_crypto_device(uuid);
427 if (!d)
428 return log_oom();
429
430 keyspec = value + n + 1;
431 c = strrchr(keyspec, ':');
432 if (c) {
433 *c = '\0';
434 keyfile = strdup(keyspec);
435 keydev = strdup(c + 1);
436
437 if (!keyfile || !keydev)
438 return log_oom();
439 } else {
440 /* No keydev specified */
441 keyfile = strdup(keyspec);
442 if (!keyfile)
443 return log_oom();
444 }
445
446 free_and_replace(d->keyfile, keyfile);
447 free_and_replace(d->keydev, keydev);
448 } else if (streq(key, "luks.name")) {
449
450 if (proc_cmdline_value_missing(key, value))
451 return 0;
452
453 r = sscanf(value, "%m[0-9a-fA-F-]=%ms", &uuid, &uuid_value);
454 if (r == 2) {
455 d = get_crypto_device(uuid);
456 if (!d)
457 return log_oom();
458
459 d->create = arg_whitelist = true;
460
461 free_and_replace(d->name, uuid_value);
462 } else
463 log_warning("Failed to parse luks name switch %s. Ignoring.", value);
464 }
465
466 return 0;
467 }
468
469 static int add_crypttab_devices(void) {
470 _cleanup_fclose_ FILE *f = NULL;
471 unsigned crypttab_line = 0;
472 struct stat st;
473 int r;
474
475 if (!arg_read_crypttab)
476 return 0;
477
478 f = fopen("/etc/crypttab", "re");
479 if (!f) {
480 if (errno != ENOENT)
481 log_error_errno(errno, "Failed to open /etc/crypttab: %m");
482 return 0;
483 }
484
485 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
486
487 if (fstat(fileno(f), &st) < 0) {
488 log_error_errno(errno, "Failed to stat /etc/crypttab: %m");
489 return 0;
490 }
491
492 for (;;) {
493 _cleanup_free_ char *line = NULL, *name = NULL, *device = NULL, *keyfile = NULL, *options = NULL;
494 crypto_device *d = NULL;
495 char *l, *uuid;
496 int k;
497
498 r = read_line(f, LONG_LINE_MAX, &line);
499 if (r < 0)
500 return log_error_errno(r, "Failed to read /etc/crypttab: %m");
501 if (r == 0)
502 break;
503
504 crypttab_line++;
505
506 l = strstrip(line);
507 if (IN_SET(l[0], 0, '#'))
508 continue;
509
510 k = sscanf(l, "%ms %ms %ms %ms", &name, &device, &keyfile, &options);
511 if (k < 2 || k > 4) {
512 log_error("Failed to parse /etc/crypttab:%u, ignoring.", crypttab_line);
513 continue;
514 }
515
516 uuid = STARTSWITH_SET(device, "UUID=", "luks-");
517 if (!uuid)
518 uuid = path_startswith(device, "/dev/disk/by-uuid/");
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 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(crypt_device_hash_ops, char, string_hash_func, string_compare_func,
576 crypto_device, crypt_device_free);
577
578 static int run(const char *dest, const char *dest_early, const char *dest_late) {
579 int r;
580
581 assert_se(arg_dest = dest);
582
583 arg_disks = hashmap_new(&crypt_device_hash_ops);
584 if (!arg_disks)
585 return log_oom();
586
587 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, PROC_CMDLINE_STRIP_RD_PREFIX);
588 if (r < 0)
589 return log_warning_errno(r, "Failed to parse kernel command line: %m");
590
591 if (!arg_enabled)
592 return 0;
593
594 r = add_crypttab_devices();
595 if (r < 0)
596 return r;
597
598 r = add_proc_cmdline_devices();
599 if (r < 0)
600 return r;
601
602 return 0;
603 }
604
605 DEFINE_MAIN_GENERATOR_FUNCTION(run);