]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/gpt-auto-generator/gpt-auto-generator.c
Merge pull request #10912 from poettering/gpt-root-rw
[thirdparty/systemd.git] / src / gpt-auto-generator / gpt-auto-generator.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <blkid.h>
4 #include <stdlib.h>
5 #include <sys/statfs.h>
6 #include <unistd.h>
7
8 #include "sd-device.h"
9 #include "sd-id128.h"
10
11 #include "alloc-util.h"
12 #include "blkid-util.h"
13 #include "blockdev-util.h"
14 #include "btrfs-util.h"
15 #include "device-util.h"
16 #include "dirent-util.h"
17 #include "dissect-image.h"
18 #include "efivars.h"
19 #include "fd-util.h"
20 #include "fileio.h"
21 #include "fstab-util.h"
22 #include "generator.h"
23 #include "gpt.h"
24 #include "missing.h"
25 #include "mkdir.h"
26 #include "mountpoint-util.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "proc-cmdline.h"
30 #include "special.h"
31 #include "specifier.h"
32 #include "stat-util.h"
33 #include "string-util.h"
34 #include "strv.h"
35 #include "unit-name.h"
36 #include "util.h"
37 #include "virt.h"
38
39 static const char *arg_dest = NULL;
40 static bool arg_enabled = true;
41 static bool arg_root_enabled = true;
42 static int arg_root_rw = -1;
43
44 static int add_cryptsetup(const char *id, const char *what, bool rw, bool require, char **device) {
45 _cleanup_free_ char *e = NULL, *n = NULL, *d = NULL, *id_escaped = NULL, *what_escaped = NULL;
46 _cleanup_fclose_ FILE *f = NULL;
47 const char *p;
48 int r;
49
50 assert(id);
51 assert(what);
52
53 r = unit_name_from_path(what, ".device", &d);
54 if (r < 0)
55 return log_error_errno(r, "Failed to generate unit name: %m");
56
57 e = unit_name_escape(id);
58 if (!e)
59 return log_oom();
60
61 r = unit_name_build("systemd-cryptsetup", e, ".service", &n);
62 if (r < 0)
63 return log_error_errno(r, "Failed to generate unit name: %m");
64
65 id_escaped = specifier_escape(id);
66 if (!id_escaped)
67 return log_oom();
68
69 what_escaped = specifier_escape(what);
70 if (!what_escaped)
71 return log_oom();
72
73 p = strjoina(arg_dest, "/", n);
74 f = fopen(p, "wxe");
75 if (!f)
76 return log_error_errno(errno, "Failed to create unit file %s: %m", p);
77
78 fprintf(f,
79 "# Automatically generated by systemd-gpt-auto-generator\n\n"
80 "[Unit]\n"
81 "Description=Cryptography Setup for %%I\n"
82 "Documentation=man:systemd-gpt-auto-generator(8) man:systemd-cryptsetup@.service(8)\n"
83 "DefaultDependencies=no\n"
84 "Conflicts=umount.target\n"
85 "BindsTo=dev-mapper-%%i.device %s\n"
86 "Before=umount.target cryptsetup.target\n"
87 "After=%s\n"
88 "IgnoreOnIsolate=true\n"
89 "[Service]\n"
90 "Type=oneshot\n"
91 "RemainAfterExit=yes\n"
92 "TimeoutSec=0\n" /* the binary handles timeouts anyway */
93 "KeyringMode=shared\n" /* make sure we can share cached keys among instances */
94 "ExecStart=" SYSTEMD_CRYPTSETUP_PATH " attach '%s' '%s' '' '%s'\n"
95 "ExecStop=" SYSTEMD_CRYPTSETUP_PATH " detach '%s'\n",
96 d, d,
97 id_escaped, what_escaped, rw ? "" : "read-only",
98 id_escaped);
99
100 r = fflush_and_check(f);
101 if (r < 0)
102 return log_error_errno(r, "Failed to write file %s: %m", p);
103
104 r = generator_add_symlink(arg_dest, d, "wants", n);
105 if (r < 0)
106 return r;
107
108 if (require) {
109 const char *dmname;
110
111 r = generator_add_symlink(arg_dest, "cryptsetup.target", "requires", n);
112 if (r < 0)
113 return r;
114
115 dmname = strjoina("dev-mapper-", e, ".device");
116 r = generator_add_symlink(arg_dest, dmname, "requires", n);
117 if (r < 0)
118 return r;
119 }
120
121 p = strjoina(arg_dest, "/dev-mapper-", e, ".device.d/50-job-timeout-sec-0.conf");
122 mkdir_parents_label(p, 0755);
123 r = write_string_file(p,
124 "# Automatically generated by systemd-gpt-auto-generator\n\n"
125 "[Unit]\n"
126 "JobTimeoutSec=0\n",
127 WRITE_STRING_FILE_CREATE); /* the binary handles timeouts anyway */
128 if (r < 0)
129 return log_error_errno(r, "Failed to write device drop-in: %m");
130
131 if (device) {
132 char *ret;
133
134 ret = strappend("/dev/mapper/", id);
135 if (!ret)
136 return log_oom();
137
138 *device = ret;
139 }
140
141 return 0;
142 }
143
144 static int add_mount(
145 const char *id,
146 const char *what,
147 const char *where,
148 const char *fstype,
149 bool rw,
150 const char *options,
151 const char *description,
152 const char *post) {
153
154 _cleanup_free_ char *unit = NULL, *crypto_what = NULL, *p = NULL;
155 _cleanup_fclose_ FILE *f = NULL;
156 int r;
157
158 /* Note that we don't apply specifier escaping on the input strings here, since we know they are not configured
159 * externally, but all originate from our own sources here, and hence we know they contain no % characters that
160 * could potentially be understood as specifiers. */
161
162 assert(id);
163 assert(what);
164 assert(where);
165 assert(description);
166
167 log_debug("Adding %s: %s %s", where, what, strna(fstype));
168
169 if (streq_ptr(fstype, "crypto_LUKS")) {
170
171 r = add_cryptsetup(id, what, rw, true, &crypto_what);
172 if (r < 0)
173 return r;
174
175 what = crypto_what;
176 fstype = NULL;
177 }
178
179 r = unit_name_from_path(where, ".mount", &unit);
180 if (r < 0)
181 return log_error_errno(r, "Failed to generate unit name: %m");
182
183 p = strjoin(arg_dest, "/", unit);
184 if (!p)
185 return log_oom();
186
187 f = fopen(p, "wxe");
188 if (!f)
189 return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
190
191 fprintf(f,
192 "# Automatically generated by systemd-gpt-auto-generator\n\n"
193 "[Unit]\n"
194 "Description=%s\n"
195 "Documentation=man:systemd-gpt-auto-generator(8)\n",
196 description);
197
198 if (post)
199 fprintf(f, "Before=%s\n", post);
200
201 r = generator_write_fsck_deps(f, arg_dest, what, where, fstype);
202 if (r < 0)
203 return r;
204
205 fprintf(f,
206 "\n"
207 "[Mount]\n"
208 "What=%s\n"
209 "Where=%s\n",
210 what, where);
211
212 if (fstype)
213 fprintf(f, "Type=%s\n", fstype);
214
215 if (options)
216 fprintf(f, "Options=%s,%s\n", options, rw ? "rw" : "ro");
217 else
218 fprintf(f, "Options=%s\n", rw ? "rw" : "ro");
219
220 r = fflush_and_check(f);
221 if (r < 0)
222 return log_error_errno(r, "Failed to write unit file %s: %m", p);
223
224 if (post)
225 return generator_add_symlink(arg_dest, post, "requires", unit);
226 return 0;
227 }
228
229 static int path_is_busy(const char *where) {
230 int r;
231
232 /* already a mountpoint; generators run during reload */
233 r = path_is_mount_point(where, NULL, AT_SYMLINK_FOLLOW);
234 if (r > 0)
235 return false;
236
237 /* the directory might not exist on a stateless system */
238 if (r == -ENOENT)
239 return false;
240
241 if (r < 0)
242 return log_warning_errno(r, "Cannot check if \"%s\" is a mount point: %m", where);
243
244 /* not a mountpoint but it contains files */
245 r = dir_is_empty(where);
246 if (r < 0)
247 return log_warning_errno(r, "Cannot check if \"%s\" is empty: %m", where);
248 if (r > 0)
249 return false;
250
251 log_debug("\"%s\" already populated, ignoring.", where);
252 return true;
253 }
254
255 static int add_partition_mount(
256 DissectedPartition *p,
257 const char *id,
258 const char *where,
259 const char *description) {
260
261 int r;
262 assert(p);
263
264 r = path_is_busy(where);
265 if (r != 0)
266 return r < 0 ? r : 0;
267
268 return add_mount(
269 id,
270 p->node,
271 where,
272 p->fstype,
273 p->rw,
274 NULL,
275 description,
276 SPECIAL_LOCAL_FS_TARGET);
277 }
278
279 static int add_swap(const char *path) {
280 _cleanup_free_ char *name = NULL, *unit = NULL;
281 _cleanup_fclose_ FILE *f = NULL;
282 int r;
283
284 assert(path);
285
286 /* Disable the swap auto logic if at least one swap is defined in /etc/fstab, see #6192. */
287 r = fstab_has_fstype("swap");
288 if (r < 0)
289 return log_error_errno(r, "Failed to parse fstab: %m");
290 if (r > 0) {
291 log_debug("swap specified in fstab, ignoring.");
292 return 0;
293 }
294
295 log_debug("Adding swap: %s", path);
296
297 r = unit_name_from_path(path, ".swap", &name);
298 if (r < 0)
299 return log_error_errno(r, "Failed to generate unit name: %m");
300
301 unit = strjoin(arg_dest, "/", name);
302 if (!unit)
303 return log_oom();
304
305 f = fopen(unit, "wxe");
306 if (!f)
307 return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
308
309 fprintf(f,
310 "# Automatically generated by systemd-gpt-auto-generator\n\n"
311 "[Unit]\n"
312 "Description=Swap Partition\n"
313 "Documentation=man:systemd-gpt-auto-generator(8)\n\n"
314 "[Swap]\n"
315 "What=%s\n",
316 path);
317
318 r = fflush_and_check(f);
319 if (r < 0)
320 return log_error_errno(r, "Failed to write unit file %s: %m", unit);
321
322 return generator_add_symlink(arg_dest, SPECIAL_SWAP_TARGET, "wants", name);
323 }
324
325 #if ENABLE_EFI
326 static int add_automount(
327 const char *id,
328 const char *what,
329 const char *where,
330 const char *fstype,
331 bool rw,
332 const char *options,
333 const char *description,
334 usec_t timeout) {
335
336 _cleanup_free_ char *unit = NULL;
337 _cleanup_fclose_ FILE *f = NULL;
338 const char *opt = "noauto", *p;
339 int r;
340
341 assert(id);
342 assert(where);
343 assert(description);
344
345 if (options)
346 opt = strjoina(options, ",", opt);
347
348 r = add_mount(id,
349 what,
350 where,
351 fstype,
352 rw,
353 opt,
354 description,
355 NULL);
356 if (r < 0)
357 return r;
358
359 r = unit_name_from_path(where, ".automount", &unit);
360 if (r < 0)
361 return log_error_errno(r, "Failed to generate unit name: %m");
362
363 p = strjoina(arg_dest, "/", unit);
364 f = fopen(p, "wxe");
365 if (!f)
366 return log_error_errno(errno, "Failed to create unit file %s: %m", unit);
367
368 fprintf(f,
369 "# Automatically generated by systemd-gpt-auto-generator\n\n"
370 "[Unit]\n"
371 "Description=%s\n"
372 "Documentation=man:systemd-gpt-auto-generator(8)\n"
373 "[Automount]\n"
374 "Where=%s\n"
375 "TimeoutIdleSec="USEC_FMT"\n",
376 description,
377 where,
378 timeout / USEC_PER_SEC);
379
380 r = fflush_and_check(f);
381 if (r < 0)
382 return log_error_errno(r, "Failed to write unit file %s: %m", p);
383
384 return generator_add_symlink(arg_dest, SPECIAL_LOCAL_FS_TARGET, "wants", unit);
385 }
386
387 static int add_esp(DissectedPartition *p) {
388 const char *esp;
389 int r;
390
391 assert(p);
392
393 if (in_initrd()) {
394 log_debug("In initrd, ignoring the ESP.");
395 return 0;
396 }
397
398 /* If /efi exists we'll use that. Otherwise we'll use /boot, as that's usually the better choice */
399 esp = access("/efi/", F_OK) >= 0 ? "/efi" : "/boot";
400
401 /* We create an .automount which is not overridden by the .mount from the fstab generator. */
402 r = fstab_is_mount_point(esp);
403 if (r < 0)
404 return log_error_errno(r, "Failed to parse fstab: %m");
405 if (r > 0) {
406 log_debug("%s specified in fstab, ignoring.", esp);
407 return 0;
408 }
409
410 r = path_is_busy(esp);
411 if (r != 0)
412 return r < 0 ? r : 0;
413
414 if (is_efi_boot()) {
415 sd_id128_t loader_uuid;
416
417 /* If this is an EFI boot, be extra careful, and only mount the ESP if it was the ESP used for booting. */
418
419 r = efi_loader_get_device_part_uuid(&loader_uuid);
420 if (r == -ENOENT) {
421 log_debug("EFI loader partition unknown.");
422 return 0;
423 }
424 if (r < 0)
425 return log_error_errno(r, "Failed to read ESP partition UUID: %m");
426
427 if (!sd_id128_equal(p->uuid, loader_uuid)) {
428 log_debug("Partition for %s does not appear to be the partition we are booted from.", esp);
429 return 0;
430 }
431 } else
432 log_debug("Not an EFI boot, skipping ESP check.");
433
434 return add_automount("boot",
435 p->node,
436 esp,
437 p->fstype,
438 true,
439 "umask=0077",
440 "EFI System Partition Automount",
441 120 * USEC_PER_SEC);
442 }
443 #else
444 static int add_esp(DissectedPartition *p) {
445 return 0;
446 }
447 #endif
448
449 static int add_root_rw(DissectedPartition *p) {
450 const char *path;
451 int r;
452
453 assert(p);
454
455 if (in_initrd()) {
456 log_debug("In initrd, not generating drop-in for systemd-remount-fs.service.");
457 return 0;
458 }
459
460 if (arg_root_rw >= 0) {
461 log_debug("Parameter ro/rw specified on kernel command line, not generating drop-in for systemd-remount-fs.service.");
462 return 0;
463 }
464
465 if (!p->rw) {
466 log_debug("Root partition marked read-only in GPT partition table, not generating drop-in for systemd-remount-fs.service.");
467 return 0;
468 }
469
470 path = strjoina(arg_dest, "/systemd-remount-fs.service.d/50-remount-rw.conf");
471 (void) mkdir_parents(path, 0755);
472
473 r = write_string_file(path,
474 "# Automatically generated by systemd-gpt-generator\n\n"
475 "[Unit]\n"
476 "ConditionPathExists=\n\n" /* We need to turn off the ConditionPathExist= in the main unit file */
477 "[Service]\n"
478 "Environment=SYSTEMD_REMOUNT_ROOT_RW=1\n",
479 WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_NOFOLLOW);
480 if (r < 0)
481 return log_error_errno(r, "Failed to write drop-in file %s: %m", path);
482
483 return 0;
484 }
485
486 static int open_parent(dev_t devnum, int *ret) {
487 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
488 const char *name, *devtype, *node;
489 sd_device *parent;
490 dev_t pn;
491 int fd, r;
492
493 assert(ret);
494
495 r = sd_device_new_from_devnum(&d, 'b', devnum);
496 if (r < 0)
497 return log_debug_errno(r, "Failed to open device: %m");
498
499 if (sd_device_get_devname(d, &name) < 0) {
500 r = sd_device_get_syspath(d, &name);
501 if (r < 0) {
502 log_device_debug_errno(d, r, "Device %u:%u does not have a name, ignoring: %m", major(devnum), minor(devnum));
503 return 0;
504 }
505 }
506
507 r = sd_device_get_parent(d, &parent);
508 if (r < 0) {
509 log_device_debug_errno(d, r, "Not a partitioned device, ignoring: %m");
510 return 0;
511 }
512
513 /* Does it have a devtype? */
514 r = sd_device_get_devtype(parent, &devtype);
515 if (r < 0) {
516 log_device_debug_errno(parent, r, "Parent doesn't have a device type, ignoring: %m");
517 return 0;
518 }
519
520 /* Is this a disk or a partition? We only care for disks... */
521 if (!streq(devtype, "disk")) {
522 log_device_debug(parent, "Parent isn't a raw disk, ignoring.");
523 return 0;
524 }
525
526 /* Does it have a device node? */
527 r = sd_device_get_devname(parent, &node);
528 if (r < 0) {
529 log_device_debug_errno(parent, r, "Parent device does not have device node, ignoring: %m");
530 return 0;
531 }
532
533 log_device_debug(d, "Root device %s.", node);
534
535 r = sd_device_get_devnum(parent, &pn);
536 if (r < 0) {
537 log_device_debug_errno(parent, r, "Parent device is not a proper block device, ignoring: %m");
538 return 0;
539 }
540
541 fd = open(node, O_RDONLY|O_CLOEXEC|O_NOCTTY);
542 if (fd < 0)
543 return log_error_errno(errno, "Failed to open %s: %m", node);
544
545 *ret = fd;
546 return 1;
547 }
548
549 static int enumerate_partitions(dev_t devnum) {
550 _cleanup_close_ int fd = -1;
551 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
552 int r, k;
553
554 r = open_parent(devnum, &fd);
555 if (r <= 0)
556 return r;
557
558 r = dissect_image(fd, NULL, 0, DISSECT_IMAGE_GPT_ONLY|DISSECT_IMAGE_NO_UDEV, &m);
559 if (r == -ENOPKG) {
560 log_debug_errno(r, "No suitable partition table found, ignoring.");
561 return 0;
562 }
563 if (r < 0)
564 return log_error_errno(r, "Failed to dissect: %m");
565
566 if (m->partitions[PARTITION_SWAP].found) {
567 k = add_swap(m->partitions[PARTITION_SWAP].node);
568 if (k < 0)
569 r = k;
570 }
571
572 if (m->partitions[PARTITION_ESP].found) {
573 k = add_esp(m->partitions + PARTITION_ESP);
574 if (k < 0)
575 r = k;
576 }
577
578 if (m->partitions[PARTITION_HOME].found) {
579 k = add_partition_mount(m->partitions + PARTITION_HOME, "home", "/home", "Home Partition");
580 if (k < 0)
581 r = k;
582 }
583
584 if (m->partitions[PARTITION_SRV].found) {
585 k = add_partition_mount(m->partitions + PARTITION_SRV, "srv", "/srv", "Server Data Partition");
586 if (k < 0)
587 r = k;
588 }
589
590 if (m->partitions[PARTITION_ROOT].found) {
591 k = add_root_rw(m->partitions + PARTITION_ROOT);
592 if (k < 0)
593 r = k;
594 }
595
596 return r;
597 }
598
599 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
600 int r;
601
602 assert(key);
603
604 if (proc_cmdline_key_streq(key, "systemd.gpt_auto") ||
605 proc_cmdline_key_streq(key, "rd.systemd.gpt_auto")) {
606
607 r = value ? parse_boolean(value) : 1;
608 if (r < 0)
609 log_warning_errno(r, "Failed to parse gpt-auto switch \"%s\", ignoring: %m", value);
610 else
611 arg_enabled = r;
612
613 } else if (proc_cmdline_key_streq(key, "root")) {
614
615 if (proc_cmdline_value_missing(key, value))
616 return 0;
617
618 /* Disable root disk logic if there's a root= value
619 * specified (unless it happens to be "gpt-auto") */
620
621 arg_root_enabled = streq(value, "gpt-auto");
622
623 } else if (proc_cmdline_key_streq(key, "roothash")) {
624
625 if (proc_cmdline_value_missing(key, value))
626 return 0;
627
628 /* Disable root disk logic if there's roothash= defined (i.e. verity enabled) */
629
630 arg_root_enabled = false;
631
632 } else if (proc_cmdline_key_streq(key, "rw") && !value)
633 arg_root_rw = true;
634 else if (proc_cmdline_key_streq(key, "ro") && !value)
635 arg_root_rw = false;
636
637 return 0;
638 }
639
640 #if ENABLE_EFI
641 static int add_root_cryptsetup(void) {
642
643 /* If a device /dev/gpt-auto-root-luks appears, then make it pull in systemd-cryptsetup-root.service, which
644 * sets it up, and causes /dev/gpt-auto-root to appear which is all we are looking for. */
645
646 return add_cryptsetup("root", "/dev/gpt-auto-root-luks", true, false, NULL);
647 }
648 #endif
649
650 static int add_root_mount(void) {
651
652 #if ENABLE_EFI
653 int r;
654
655 if (!is_efi_boot()) {
656 log_debug("Not a EFI boot, not creating root mount.");
657 return 0;
658 }
659
660 r = efi_loader_get_device_part_uuid(NULL);
661 if (r == -ENOENT) {
662 log_debug("EFI loader partition unknown, exiting.");
663 return 0;
664 } else if (r < 0)
665 return log_error_errno(r, "Failed to read ESP partition UUID: %m");
666
667 /* OK, we have an ESP partition, this is fantastic, so let's
668 * wait for a root device to show up. A udev rule will create
669 * the link for us under the right name. */
670
671 if (in_initrd()) {
672 r = generator_write_initrd_root_device_deps(arg_dest, "/dev/gpt-auto-root");
673 if (r < 0)
674 return 0;
675
676 r = add_root_cryptsetup();
677 if (r < 0)
678 return r;
679 }
680
681 return add_mount(
682 "root",
683 "/dev/gpt-auto-root",
684 in_initrd() ? "/sysroot" : "/",
685 NULL,
686 arg_root_rw > 0,
687 NULL,
688 "Root Partition",
689 in_initrd() ? SPECIAL_INITRD_ROOT_FS_TARGET : SPECIAL_LOCAL_FS_TARGET);
690 #else
691 return 0;
692 #endif
693 }
694
695 static int add_mounts(void) {
696 dev_t devno;
697 int r;
698
699 r = get_block_device_harder("/", &devno);
700 if (r < 0)
701 return log_error_errno(r, "Failed to determine block device of root file system: %m");
702 if (r == 0) {
703 r = get_block_device_harder("/usr", &devno);
704 if (r < 0)
705 return log_error_errno(r, "Failed to determine block device of /usr file system: %m");
706 if (r == 0) {
707 log_debug("Neither root nor /usr file system are on a (single) block device.");
708 return 0;
709 }
710 }
711
712 return enumerate_partitions(devno);
713 }
714
715 static int run(const char *dest, const char *dest_early, const char *dest_late) {
716 int r, k;
717
718 assert_se(arg_dest = dest_late);
719
720 if (detect_container() > 0) {
721 log_debug("In a container, exiting.");
722 return 0;
723 }
724
725 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
726 if (r < 0)
727 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
728
729 if (!arg_enabled) {
730 log_debug("Disabled, exiting.");
731 return 0;
732 }
733
734 if (arg_root_enabled)
735 r = add_root_mount();
736
737 if (!in_initrd()) {
738 k = add_mounts();
739 if (r >= 0)
740 r = k;
741 }
742
743 return r;
744 }
745
746 DEFINE_MAIN_GENERATOR_FUNCTION(run);