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