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