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