]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
Merge pull request #17549 from yuwata/tiny-fixes
[thirdparty/systemd.git] / src / shared / dissect-image.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
5 #endif
6
7 #include <linux/dm-ioctl.h>
8 #include <linux/loop.h>
9 #include <sys/mount.h>
10 #include <sys/prctl.h>
11 #include <sys/wait.h>
12 #include <sysexits.h>
13
14 #include "sd-device.h"
15 #include "sd-id128.h"
16
17 #include "architecture.h"
18 #include "ask-password-api.h"
19 #include "blkid-util.h"
20 #include "blockdev-util.h"
21 #include "copy.h"
22 #include "cryptsetup-util.h"
23 #include "def.h"
24 #include "device-nodes.h"
25 #include "device-util.h"
26 #include "dissect-image.h"
27 #include "dm-util.h"
28 #include "env-file.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "fsck-util.h"
33 #include "gpt.h"
34 #include "hexdecoct.h"
35 #include "hostname-util.h"
36 #include "id128-util.h"
37 #include "mkdir.h"
38 #include "mount-util.h"
39 #include "mountpoint-util.h"
40 #include "namespace-util.h"
41 #include "nulstr-util.h"
42 #include "os-util.h"
43 #include "path-util.h"
44 #include "process-util.h"
45 #include "raw-clone.h"
46 #include "signal-util.h"
47 #include "stat-util.h"
48 #include "stdio-util.h"
49 #include "string-table.h"
50 #include "string-util.h"
51 #include "strv.h"
52 #include "tmpfile-util.h"
53 #include "udev-util.h"
54 #include "user-util.h"
55 #include "xattr-util.h"
56
57 /* how many times to wait for the device nodes to appear */
58 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
59
60 int probe_filesystem(const char *node, char **ret_fstype) {
61 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
62 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
63 * different error otherwise. */
64
65 #if HAVE_BLKID
66 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
67 const char *fstype;
68 int r;
69
70 errno = 0;
71 b = blkid_new_probe_from_filename(node);
72 if (!b)
73 return errno_or_else(ENOMEM);
74
75 blkid_probe_enable_superblocks(b, 1);
76 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
77
78 errno = 0;
79 r = blkid_do_safeprobe(b);
80 if (r == 1) {
81 log_debug("No type detected on partition %s", node);
82 goto not_found;
83 }
84 if (r == -2)
85 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
86 "Results ambiguous for partition %s", node);
87 if (r != 0)
88 return errno_or_else(EIO);
89
90 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
91
92 if (fstype) {
93 char *t;
94
95 t = strdup(fstype);
96 if (!t)
97 return -ENOMEM;
98
99 *ret_fstype = t;
100 return 1;
101 }
102
103 not_found:
104 *ret_fstype = NULL;
105 return 0;
106 #else
107 return -EOPNOTSUPP;
108 #endif
109 }
110
111 #if HAVE_BLKID
112 static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
113 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
114 int r;
115
116 assert(d);
117 assert(ret);
118
119 r = sd_device_enumerator_new(&e);
120 if (r < 0)
121 return r;
122
123 r = sd_device_enumerator_allow_uninitialized(e);
124 if (r < 0)
125 return r;
126
127 r = sd_device_enumerator_add_match_parent(e, d);
128 if (r < 0)
129 return r;
130
131 *ret = TAKE_PTR(e);
132 return 0;
133 }
134
135 static int device_is_partition(sd_device *d, blkid_partition pp) {
136 blkid_loff_t bsize, bstart;
137 uint64_t size, start;
138 int partno, bpartno, r;
139 const char *ss, *v;
140
141 assert(d);
142 assert(pp);
143
144 r = sd_device_get_subsystem(d, &ss);
145 if (r < 0)
146 return r;
147 if (!streq(ss, "block"))
148 return false;
149
150 r = sd_device_get_sysattr_value(d, "partition", &v);
151 if (r == -ENOENT) /* Not a partition device */
152 return false;
153 if (r < 0)
154 return r;
155 r = safe_atoi(v, &partno);
156 if (r < 0)
157 return r;
158
159 errno = 0;
160 bpartno = blkid_partition_get_partno(pp);
161 if (bpartno < 0)
162 return errno_or_else(EIO);
163
164 if (partno != bpartno)
165 return false;
166
167 r = sd_device_get_sysattr_value(d, "start", &v);
168 if (r < 0)
169 return r;
170 r = safe_atou64(v, &start);
171 if (r < 0)
172 return r;
173
174 errno = 0;
175 bstart = blkid_partition_get_start(pp);
176 if (bstart < 0)
177 return errno_or_else(EIO);
178
179 if (start != (uint64_t) bstart)
180 return false;
181
182 r = sd_device_get_sysattr_value(d, "size", &v);
183 if (r < 0)
184 return r;
185 r = safe_atou64(v, &size);
186 if (r < 0)
187 return r;
188
189 errno = 0;
190 bsize = blkid_partition_get_size(pp);
191 if (bsize < 0)
192 return errno_or_else(EIO);
193
194 if (size != (uint64_t) bsize)
195 return false;
196
197 return true;
198 }
199
200 static int find_partition(
201 sd_device *parent,
202 blkid_partition pp,
203 sd_device **ret) {
204
205 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
206 sd_device *q;
207 int r;
208
209 assert(parent);
210 assert(pp);
211 assert(ret);
212
213 r = enumerator_for_parent(parent, &e);
214 if (r < 0)
215 return r;
216
217 FOREACH_DEVICE(e, q) {
218 r = device_is_partition(q, pp);
219 if (r < 0)
220 return r;
221 if (r > 0) {
222 *ret = sd_device_ref(q);
223 return 0;
224 }
225 }
226
227 return -ENXIO;
228 }
229
230 struct wait_data {
231 sd_device *parent_device;
232 blkid_partition blkidp;
233 sd_device *found;
234 };
235
236 static inline void wait_data_done(struct wait_data *d) {
237 sd_device_unref(d->found);
238 }
239
240 static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) {
241 const char *parent1_path, *parent2_path;
242 struct wait_data *w = userdata;
243 sd_device *pp;
244 int r;
245
246 assert(w);
247
248 if (device_for_action(device, DEVICE_ACTION_REMOVE))
249 return 0;
250
251 r = sd_device_get_parent(device, &pp);
252 if (r < 0)
253 return 0; /* Doesn't have a parent? No relevant to us */
254
255 r = sd_device_get_syspath(pp, &parent1_path); /* Check parent of device of this action */
256 if (r < 0)
257 goto finish;
258
259 r = sd_device_get_syspath(w->parent_device, &parent2_path); /* Check parent of device we are looking for */
260 if (r < 0)
261 goto finish;
262
263 if (!path_equal(parent1_path, parent2_path))
264 return 0; /* Has a different parent than what we need, not interesting to us */
265
266 r = device_is_partition(device, w->blkidp);
267 if (r < 0)
268 goto finish;
269 if (r == 0) /* Not the one we need */
270 return 0;
271
272 /* It's the one we need! Yay! */
273 assert(!w->found);
274 w->found = sd_device_ref(device);
275 r = 0;
276
277 finish:
278 return sd_event_exit(sd_device_monitor_get_event(monitor), r);
279 }
280
281 static int wait_for_partition_device(
282 sd_device *parent,
283 blkid_partition pp,
284 usec_t deadline,
285 sd_device **ret) {
286
287 _cleanup_(sd_event_source_unrefp) sd_event_source *timeout_source = NULL;
288 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
289 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
290 int r;
291
292 assert(parent);
293 assert(pp);
294 assert(ret);
295
296 r = find_partition(parent, pp, ret);
297 if (r != -ENXIO)
298 return r;
299
300 r = sd_event_new(&event);
301 if (r < 0)
302 return r;
303
304 r = sd_device_monitor_new(&monitor);
305 if (r < 0)
306 return r;
307
308 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "block", "partition");
309 if (r < 0)
310 return r;
311
312 r = sd_device_monitor_attach_event(monitor, event);
313 if (r < 0)
314 return r;
315
316 _cleanup_(wait_data_done) struct wait_data w = {
317 .parent_device = parent,
318 .blkidp = pp,
319 };
320
321 r = sd_device_monitor_start(monitor, device_monitor_handler, &w);
322 if (r < 0)
323 return r;
324
325 /* Check again, the partition might have appeared in the meantime */
326 r = find_partition(parent, pp, ret);
327 if (r != -ENXIO)
328 return r;
329
330 if (deadline != USEC_INFINITY) {
331 r = sd_event_add_time(
332 event, &timeout_source,
333 CLOCK_MONOTONIC, deadline, 0,
334 NULL, INT_TO_PTR(-ETIMEDOUT));
335 if (r < 0)
336 return r;
337 }
338
339 r = sd_event_loop(event);
340 if (r < 0)
341 return r;
342
343 assert(w.found);
344 *ret = TAKE_PTR(w.found);
345 return 0;
346 }
347
348 static void check_partition_flags(
349 const char *node,
350 unsigned long long pflags,
351 unsigned long long supported) {
352
353 assert(node);
354
355 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
356 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
357
358 if (pflags == 0)
359 return;
360
361 /* If there are other bits set, then log about it, to make things discoverable */
362 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
363 unsigned long long bit = 1ULL << i;
364 if (!FLAGS_SET(pflags, bit))
365 continue;
366
367 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
368 }
369 }
370
371 static int device_wait_for_initialization_harder(
372 sd_device *device,
373 const char *subsystem,
374 usec_t deadline,
375 sd_device **ret) {
376
377 _cleanup_free_ char *uevent = NULL;
378 usec_t start, left, retrigger_timeout;
379 int r;
380
381 start = now(CLOCK_MONOTONIC);
382 left = usec_sub_unsigned(deadline, start);
383
384 if (DEBUG_LOGGING) {
385 char buf[FORMAT_TIMESPAN_MAX];
386 const char *sn = NULL;
387
388 (void) sd_device_get_sysname(device, &sn);
389 log_debug("Waiting for device '%s' to initialize for %s.", strna(sn), format_timespan(buf, sizeof(buf), left, 0));
390 }
391
392 if (left != USEC_INFINITY)
393 retrigger_timeout = CLAMP(left / 4, 1 * USEC_PER_SEC, 5 * USEC_PER_SEC); /* A fourth of the total timeout, but let's clamp to 1s…5s range */
394 else
395 retrigger_timeout = 2 * USEC_PER_SEC;
396
397 for (;;) {
398 usec_t local_deadline, n;
399 bool last_try;
400
401 n = now(CLOCK_MONOTONIC);
402 assert(n >= start);
403
404 /* Find next deadline, when we'll retrigger */
405 local_deadline = start +
406 DIV_ROUND_UP(n - start, retrigger_timeout) * retrigger_timeout;
407
408 if (deadline != USEC_INFINITY && deadline <= local_deadline) {
409 local_deadline = deadline;
410 last_try = true;
411 } else
412 last_try = false;
413
414 r = device_wait_for_initialization(device, subsystem, local_deadline, ret);
415 if (r >= 0 && DEBUG_LOGGING) {
416 char buf[FORMAT_TIMESPAN_MAX];
417 const char *sn = NULL;
418
419 (void) sd_device_get_sysname(device, &sn);
420 log_debug("Successfully waited for device '%s' to initialize for %s.", strna(sn), format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
421
422 }
423 if (r != -ETIMEDOUT || last_try)
424 return r;
425
426 if (!uevent) {
427 const char *syspath;
428
429 r = sd_device_get_syspath(device, &syspath);
430 if (r < 0)
431 return r;
432
433 uevent = path_join(syspath, "uevent");
434 if (!uevent)
435 return -ENOMEM;
436 }
437
438 if (DEBUG_LOGGING) {
439 char buf[FORMAT_TIMESPAN_MAX];
440
441 log_debug("Device didn't initialize within %s, assuming lost event. Retriggering device through %s.",
442 format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0),
443 uevent);
444 }
445
446 r = write_string_file(uevent, "change", WRITE_STRING_FILE_DISABLE_BUFFER);
447 if (r < 0)
448 return r;
449 }
450 }
451 #endif
452
453 #define DEVICE_TIMEOUT_USEC (45 * USEC_PER_SEC)
454
455 int dissect_image(
456 int fd,
457 const VeritySettings *verity,
458 const MountOptions *mount_options,
459 DissectImageFlags flags,
460 DissectedImage **ret) {
461
462 #if HAVE_BLKID
463 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL,
464 usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
465 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
466 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
467 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
468 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
469 _cleanup_free_ char *generic_node = NULL;
470 sd_id128_t generic_uuid = SD_ID128_NULL;
471 const char *pttype = NULL;
472 blkid_partlist pl;
473 int r, generic_nr, n_partitions;
474 struct stat st;
475 usec_t deadline;
476
477 assert(fd >= 0);
478 assert(ret);
479 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
480 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
481
482 /* Probes a disk image, and returns information about what it found in *ret.
483 *
484 * Returns -ENOPKG if no suitable partition table or file system could be found.
485 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
486
487 if (verity && verity->root_hash) {
488 sd_id128_t fsuuid, vuuid;
489
490 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
491 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
492 * the final 128bit. */
493
494 if (verity->root_hash_size < sizeof(sd_id128_t))
495 return -EINVAL;
496
497 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
498 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
499
500 if (sd_id128_is_null(fsuuid))
501 return -EINVAL;
502 if (sd_id128_is_null(vuuid))
503 return -EINVAL;
504
505 /* If the verity data declares it's for the /usr partition, then search for that, in all
506 * other cases assume it's for the root partition. */
507 if (verity->designator == PARTITION_USR) {
508 usr_uuid = fsuuid;
509 usr_verity_uuid = vuuid;
510 } else {
511 root_uuid = fsuuid;
512 root_verity_uuid = vuuid;
513 }
514 }
515
516 if (fstat(fd, &st) < 0)
517 return -errno;
518
519 if (!S_ISBLK(st.st_mode))
520 return -ENOTBLK;
521
522 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
523 if (r < 0)
524 return r;
525
526 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
527 _cleanup_(sd_device_unrefp) sd_device *initialized = NULL;
528
529 /* If udev support is enabled, then let's wait for the device to be initialized before we doing anything. */
530
531 r = device_wait_for_initialization_harder(
532 d,
533 "block",
534 usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC),
535 &initialized);
536 if (r < 0)
537 return r;
538
539 sd_device_unref(d);
540 d = TAKE_PTR(initialized);
541 }
542
543 b = blkid_new_probe();
544 if (!b)
545 return -ENOMEM;
546
547 errno = 0;
548 r = blkid_probe_set_device(b, fd, 0, 0);
549 if (r != 0)
550 return errno_or_else(ENOMEM);
551
552 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
553 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
554 blkid_probe_enable_superblocks(b, 1);
555 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
556 }
557
558 blkid_probe_enable_partitions(b, 1);
559 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
560
561 errno = 0;
562 r = blkid_do_safeprobe(b);
563 if (IN_SET(r, -2, 1))
564 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
565 if (r != 0)
566 return errno_or_else(EIO);
567
568 m = new0(DissectedImage, 1);
569 if (!m)
570 return -ENOMEM;
571
572 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
573 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) ||
574 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
575 const char *usage = NULL;
576
577 /* If flags permit this, also allow using non-partitioned single-filesystem images */
578
579 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
580 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
581 const char *fstype = NULL, *options = NULL, *devname = NULL;
582 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
583
584 /* OK, we have found a file system, that's our root partition then. */
585 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
586
587 if (fstype) {
588 t = strdup(fstype);
589 if (!t)
590 return -ENOMEM;
591 }
592
593 r = sd_device_get_devname(d, &devname);
594 if (r < 0)
595 return r;
596
597 n = strdup(devname);
598 if (!n)
599 return -ENOMEM;
600
601 m->single_file_system = true;
602 m->verity = verity && verity->root_hash && verity->data_path && (verity->designator < 0 || verity->designator == PARTITION_ROOT);
603 m->can_verity = verity && verity->data_path;
604
605 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
606 if (options) {
607 o = strdup(options);
608 if (!o)
609 return -ENOMEM;
610 }
611
612 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
613 .found = true,
614 .rw = !m->verity,
615 .partno = -1,
616 .architecture = _ARCHITECTURE_INVALID,
617 .fstype = TAKE_PTR(t),
618 .node = TAKE_PTR(n),
619 .mount_options = TAKE_PTR(o),
620 };
621
622 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
623
624 *ret = TAKE_PTR(m);
625 return 0;
626 }
627 }
628
629 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
630 if (!pttype)
631 return -ENOPKG;
632
633 is_gpt = streq_ptr(pttype, "gpt");
634 is_mbr = streq_ptr(pttype, "dos");
635
636 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
637 return -ENOPKG;
638
639 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
640 * do partition scanning. */
641 r = blockdev_partscan_enabled(fd);
642 if (r < 0)
643 return r;
644 if (r == 0)
645 return -EPROTONOSUPPORT;
646
647 errno = 0;
648 pl = blkid_probe_get_partitions(b);
649 if (!pl)
650 return errno_or_else(ENOMEM);
651
652 errno = 0;
653 n_partitions = blkid_partlist_numof_partitions(pl);
654 if (n_partitions < 0)
655 return errno_or_else(EIO);
656
657 deadline = usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC);
658 for (int i = 0; i < n_partitions; i++) {
659 _cleanup_(sd_device_unrefp) sd_device *q = NULL;
660 unsigned long long pflags;
661 blkid_partition pp;
662 const char *node;
663 int nr;
664
665 errno = 0;
666 pp = blkid_partlist_get_partition(pl, i);
667 if (!pp)
668 return errno_or_else(EIO);
669
670 r = wait_for_partition_device(d, pp, deadline, &q);
671 if (r < 0)
672 return r;
673
674 r = sd_device_get_devname(q, &node);
675 if (r < 0)
676 return r;
677
678 pflags = blkid_partition_get_flags(pp);
679
680 errno = 0;
681 nr = blkid_partition_get_partno(pp);
682 if (nr < 0)
683 return errno_or_else(EIO);
684
685 if (is_gpt) {
686 PartitionDesignator designator = _PARTITION_DESIGNATOR_INVALID;
687 int architecture = _ARCHITECTURE_INVALID;
688 const char *stype, *sid, *fstype = NULL;
689 sd_id128_t type_id, id;
690 bool rw = true;
691
692 sid = blkid_partition_get_uuid(pp);
693 if (!sid)
694 continue;
695 if (sd_id128_from_string(sid, &id) < 0)
696 continue;
697
698 stype = blkid_partition_get_type_string(pp);
699 if (!stype)
700 continue;
701 if (sd_id128_from_string(stype, &type_id) < 0)
702 continue;
703
704 if (sd_id128_equal(type_id, GPT_HOME)) {
705
706 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
707
708 if (pflags & GPT_FLAG_NO_AUTO)
709 continue;
710
711 designator = PARTITION_HOME;
712 rw = !(pflags & GPT_FLAG_READ_ONLY);
713
714 } else if (sd_id128_equal(type_id, GPT_SRV)) {
715
716 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
717
718 if (pflags & GPT_FLAG_NO_AUTO)
719 continue;
720
721 designator = PARTITION_SRV;
722 rw = !(pflags & GPT_FLAG_READ_ONLY);
723
724 } else if (sd_id128_equal(type_id, GPT_ESP)) {
725
726 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is
727 * not defined there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
728 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
729 * Partitions"). */
730
731 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
732 continue;
733
734 designator = PARTITION_ESP;
735 fstype = "vfat";
736
737 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
738
739 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
740
741 if (pflags & GPT_FLAG_NO_AUTO)
742 continue;
743
744 designator = PARTITION_XBOOTLDR;
745 rw = !(pflags & GPT_FLAG_READ_ONLY);
746 }
747 #ifdef GPT_ROOT_NATIVE
748 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
749
750 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
751
752 if (pflags & GPT_FLAG_NO_AUTO)
753 continue;
754
755 /* If a root ID is specified, ignore everything but the root id */
756 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
757 continue;
758
759 designator = PARTITION_ROOT;
760 architecture = native_architecture();
761 rw = !(pflags & GPT_FLAG_READ_ONLY);
762
763 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
764
765 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
766
767 if (pflags & GPT_FLAG_NO_AUTO)
768 continue;
769
770 m->can_verity = true;
771
772 /* Ignore verity unless a root hash is specified */
773 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
774 continue;
775
776 designator = PARTITION_ROOT_VERITY;
777 fstype = "DM_verity_hash";
778 architecture = native_architecture();
779 rw = false;
780 }
781 #endif
782 #ifdef GPT_ROOT_SECONDARY
783 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
784
785 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
786
787 if (pflags & GPT_FLAG_NO_AUTO)
788 continue;
789
790 /* If a root ID is specified, ignore everything but the root id */
791 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
792 continue;
793
794 designator = PARTITION_ROOT_SECONDARY;
795 architecture = SECONDARY_ARCHITECTURE;
796 rw = !(pflags & GPT_FLAG_READ_ONLY);
797
798 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
799
800 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
801
802 if (pflags & GPT_FLAG_NO_AUTO)
803 continue;
804
805 m->can_verity = true;
806
807 /* Ignore verity unless root has is specified */
808 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
809 continue;
810
811 designator = PARTITION_ROOT_SECONDARY_VERITY;
812 fstype = "DM_verity_hash";
813 architecture = SECONDARY_ARCHITECTURE;
814 rw = false;
815 }
816 #endif
817 #ifdef GPT_USR_NATIVE
818 else if (sd_id128_equal(type_id, GPT_USR_NATIVE)) {
819
820 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
821
822 if (pflags & GPT_FLAG_NO_AUTO)
823 continue;
824
825 /* If a usr ID is specified, ignore everything but the usr id */
826 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
827 continue;
828
829 designator = PARTITION_USR;
830 architecture = native_architecture();
831 rw = !(pflags & GPT_FLAG_READ_ONLY);
832
833 } else if (sd_id128_equal(type_id, GPT_USR_NATIVE_VERITY)) {
834
835 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
836
837 if (pflags & GPT_FLAG_NO_AUTO)
838 continue;
839
840 m->can_verity = true;
841
842 /* Ignore verity unless a usr hash is specified */
843 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
844 continue;
845
846 designator = PARTITION_USR_VERITY;
847 fstype = "DM_verity_hash";
848 architecture = native_architecture();
849 rw = false;
850 }
851 #endif
852 #ifdef GPT_USR_SECONDARY
853 else if (sd_id128_equal(type_id, GPT_USR_SECONDARY)) {
854
855 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
856
857 if (pflags & GPT_FLAG_NO_AUTO)
858 continue;
859
860 /* If a usr ID is specified, ignore everything but the usr id */
861 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
862 continue;
863
864 designator = PARTITION_USR_SECONDARY;
865 architecture = SECONDARY_ARCHITECTURE;
866 rw = !(pflags & GPT_FLAG_READ_ONLY);
867
868 } else if (sd_id128_equal(type_id, GPT_USR_SECONDARY_VERITY)) {
869
870 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
871
872 if (pflags & GPT_FLAG_NO_AUTO)
873 continue;
874
875 m->can_verity = true;
876
877 /* Ignore verity unless usr has is specified */
878 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
879 continue;
880
881 designator = PARTITION_USR_SECONDARY_VERITY;
882 fstype = "DM_verity_hash";
883 architecture = SECONDARY_ARCHITECTURE;
884 rw = false;
885 }
886 #endif
887 else if (sd_id128_equal(type_id, GPT_SWAP)) {
888
889 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
890
891 if (pflags & GPT_FLAG_NO_AUTO)
892 continue;
893
894 designator = PARTITION_SWAP;
895 fstype = "swap";
896
897 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
898
899 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
900
901 if (pflags & GPT_FLAG_NO_AUTO)
902 continue;
903
904 if (generic_node)
905 multiple_generic = true;
906 else {
907 generic_nr = nr;
908 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
909 generic_uuid = id;
910 generic_node = strdup(node);
911 if (!generic_node)
912 return -ENOMEM;
913 }
914
915 } else if (sd_id128_equal(type_id, GPT_TMP)) {
916
917 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
918
919 if (pflags & GPT_FLAG_NO_AUTO)
920 continue;
921
922 designator = PARTITION_TMP;
923 rw = !(pflags & GPT_FLAG_READ_ONLY);
924
925 } else if (sd_id128_equal(type_id, GPT_VAR)) {
926
927 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
928
929 if (pflags & GPT_FLAG_NO_AUTO)
930 continue;
931
932 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
933 sd_id128_t var_uuid;
934
935 /* For /var we insist that the uuid of the partition matches the
936 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
937 * ID. Why? Unlike the other partitions /var is inherently
938 * installation specific, hence we need to be careful not to mount it
939 * in the wrong installation. By hashing the partition UUID from
940 * /etc/machine-id we can securely bind the partition to the
941 * installation. */
942
943 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
944 if (r < 0)
945 return r;
946
947 if (!sd_id128_equal(var_uuid, id)) {
948 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
949 continue;
950 }
951 }
952
953 designator = PARTITION_VAR;
954 rw = !(pflags & GPT_FLAG_READ_ONLY);
955 }
956
957 if (designator != _PARTITION_DESIGNATOR_INVALID) {
958 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
959 const char *options = NULL;
960
961 /* First one wins */
962 if (m->partitions[designator].found)
963 continue;
964
965 if (fstype) {
966 t = strdup(fstype);
967 if (!t)
968 return -ENOMEM;
969 }
970
971 n = strdup(node);
972 if (!n)
973 return -ENOMEM;
974
975 options = mount_options_from_designator(mount_options, designator);
976 if (options) {
977 o = strdup(options);
978 if (!o)
979 return -ENOMEM;
980 }
981
982 m->partitions[designator] = (DissectedPartition) {
983 .found = true,
984 .partno = nr,
985 .rw = rw,
986 .architecture = architecture,
987 .node = TAKE_PTR(n),
988 .fstype = TAKE_PTR(t),
989 .uuid = id,
990 .mount_options = TAKE_PTR(o),
991 };
992 }
993
994 } else if (is_mbr) {
995
996 switch (blkid_partition_get_type(pp)) {
997
998 case 0x83: /* Linux partition */
999
1000 if (pflags != 0x80) /* Bootable flag */
1001 continue;
1002
1003 if (generic_node)
1004 multiple_generic = true;
1005 else {
1006 generic_nr = nr;
1007 generic_rw = true;
1008 generic_node = strdup(node);
1009 if (!generic_node)
1010 return -ENOMEM;
1011 }
1012
1013 break;
1014
1015 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1016 _cleanup_free_ char *n = NULL, *o = NULL;
1017 sd_id128_t id = SD_ID128_NULL;
1018 const char *sid, *options = NULL;
1019
1020 /* First one wins */
1021 if (m->partitions[PARTITION_XBOOTLDR].found)
1022 continue;
1023
1024 sid = blkid_partition_get_uuid(pp);
1025 if (sid)
1026 (void) sd_id128_from_string(sid, &id);
1027
1028 n = strdup(node);
1029 if (!n)
1030 return -ENOMEM;
1031
1032 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
1033 if (options) {
1034 o = strdup(options);
1035 if (!o)
1036 return -ENOMEM;
1037 }
1038
1039 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1040 .found = true,
1041 .partno = nr,
1042 .rw = true,
1043 .architecture = _ARCHITECTURE_INVALID,
1044 .node = TAKE_PTR(n),
1045 .uuid = id,
1046 .mount_options = TAKE_PTR(o),
1047 };
1048
1049 break;
1050 }}
1051 }
1052 }
1053
1054 if (m->partitions[PARTITION_ROOT].found) {
1055 /* If we found the primary arch, then invalidate the secondary arch to avoid any ambiguities,
1056 * since we never want to mount the secondary arch in this case. */
1057 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
1058 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
1059 m->partitions[PARTITION_USR_SECONDARY].found = false;
1060 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
1061 } else {
1062 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
1063 * either, then check if there's a single generic one, and use that. */
1064
1065 if (m->partitions[PARTITION_ROOT_VERITY].found)
1066 return -EADDRNOTAVAIL;
1067
1068 /* We didn't find a primary architecture root, but we found a primary architecture /usr? Refuse that for now. */
1069 if (m->partitions[PARTITION_USR].found || m->partitions[PARTITION_USR_VERITY].found)
1070 return -EADDRNOTAVAIL;
1071
1072 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
1073 /* Upgrade secondary arch to first */
1074 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
1075 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
1076 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
1077 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
1078
1079 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1080 zero(m->partitions[PARTITION_USR_SECONDARY]);
1081 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1082 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
1083
1084 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
1085 _cleanup_free_ char *o = NULL;
1086 const char *options = NULL;
1087
1088 /* If the root hash was set, then we won't fall back to a generic node, because the
1089 * root hash decides. */
1090 if (verity && verity->root_hash)
1091 return -EADDRNOTAVAIL;
1092
1093 /* If we didn't find a generic node, then we can't fix this up either */
1094 if (!generic_node)
1095 return -ENXIO;
1096
1097 /* If we didn't find a properly marked root partition, but we did find a single suitable
1098 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1099 if (multiple_generic)
1100 return -ENOTUNIQ;
1101
1102 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
1103 if (options) {
1104 o = strdup(options);
1105 if (!o)
1106 return -ENOMEM;
1107 }
1108
1109 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1110 .found = true,
1111 .rw = generic_rw,
1112 .partno = generic_nr,
1113 .architecture = _ARCHITECTURE_INVALID,
1114 .node = TAKE_PTR(generic_node),
1115 .uuid = generic_uuid,
1116 .mount_options = TAKE_PTR(o),
1117 };
1118 }
1119 }
1120
1121 /* Refuse if we found a verity partition for /usr but no matching file system partition */
1122 if (!m->partitions[PARTITION_USR].found && m->partitions[PARTITION_USR_VERITY].found)
1123 return -EADDRNOTAVAIL;
1124
1125 /* Combinations of verity /usr with verity-less root is OK, but the reverse is not */
1126 if (m->partitions[PARTITION_ROOT_VERITY].found && m->partitions[PARTITION_USR].found && !m->partitions[PARTITION_USR_VERITY].found)
1127 return -EADDRNOTAVAIL;
1128
1129 if (verity && verity->root_hash) {
1130 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1131 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1132 return -EADDRNOTAVAIL;
1133
1134 /* If we found a verity setup, then the root partition is necessarily read-only. */
1135 m->partitions[PARTITION_ROOT].rw = false;
1136 m->verity = true;
1137 }
1138
1139 if (verity->designator == PARTITION_USR) {
1140 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1141 return -EADDRNOTAVAIL;
1142
1143 m->partitions[PARTITION_USR].rw = false;
1144 m->verity = true;
1145 }
1146 }
1147
1148 blkid_free_probe(b);
1149 b = NULL;
1150
1151 /* Fill in file system types if we don't know them yet. */
1152 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1153 DissectedPartition *p = m->partitions + i;
1154
1155 if (!p->found)
1156 continue;
1157
1158 if (!p->fstype && p->node) {
1159 r = probe_filesystem(p->node, &p->fstype);
1160 if (r < 0 && r != -EUCLEAN)
1161 return r;
1162 }
1163
1164 if (streq_ptr(p->fstype, "crypto_LUKS"))
1165 m->encrypted = true;
1166
1167 if (p->fstype && fstype_is_ro(p->fstype))
1168 p->rw = false;
1169 }
1170
1171 *ret = TAKE_PTR(m);
1172 return 0;
1173 #else
1174 return -EOPNOTSUPP;
1175 #endif
1176 }
1177
1178 DissectedImage* dissected_image_unref(DissectedImage *m) {
1179 if (!m)
1180 return NULL;
1181
1182 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1183 free(m->partitions[i].fstype);
1184 free(m->partitions[i].node);
1185 free(m->partitions[i].decrypted_fstype);
1186 free(m->partitions[i].decrypted_node);
1187 free(m->partitions[i].mount_options);
1188 }
1189
1190 free(m->hostname);
1191 strv_free(m->machine_info);
1192 strv_free(m->os_release);
1193
1194 return mfree(m);
1195 }
1196
1197 static int is_loop_device(const char *path) {
1198 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
1199 struct stat st;
1200
1201 assert(path);
1202
1203 if (stat(path, &st) < 0)
1204 return -errno;
1205
1206 if (!S_ISBLK(st.st_mode))
1207 return -ENOTBLK;
1208
1209 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
1210 if (access(s, F_OK) < 0) {
1211 if (errno != ENOENT)
1212 return -errno;
1213
1214 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1215 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
1216 if (access(s, F_OK) < 0)
1217 return errno == ENOENT ? false : -errno;
1218 }
1219
1220 return true;
1221 }
1222
1223 static int run_fsck(const char *node, const char *fstype) {
1224 int r, exit_status;
1225 pid_t pid;
1226
1227 assert(node);
1228 assert(fstype);
1229
1230 r = fsck_exists(fstype);
1231 if (r < 0) {
1232 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1233 return 0;
1234 }
1235 if (r == 0) {
1236 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
1237 return 0;
1238 }
1239
1240 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
1241 if (r < 0)
1242 return log_debug_errno(r, "Failed to fork off fsck: %m");
1243 if (r == 0) {
1244 /* Child */
1245 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
1246 log_debug_errno(errno, "Failed to execl() fsck: %m");
1247 _exit(FSCK_OPERATIONAL_ERROR);
1248 }
1249
1250 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1251 if (exit_status < 0)
1252 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1253
1254 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1255 log_debug("fsck failed with exit status %i.", exit_status);
1256
1257 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1258 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1259
1260 log_debug("Ignoring fsck error.");
1261 }
1262
1263 return 0;
1264 }
1265
1266 static int mount_partition(
1267 DissectedPartition *m,
1268 const char *where,
1269 const char *directory,
1270 uid_t uid_shift,
1271 DissectImageFlags flags) {
1272
1273 _cleanup_free_ char *chased = NULL, *options = NULL;
1274 const char *p, *node, *fstype;
1275 bool rw;
1276 int r;
1277
1278 assert(m);
1279 assert(where);
1280
1281 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1282 node = m->decrypted_node ?: m->node;
1283 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
1284
1285 if (!m->found || !node)
1286 return 0;
1287 if (!fstype)
1288 return -EAFNOSUPPORT;
1289
1290 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this case. */
1291 if (streq(fstype, "crypto_LUKS"))
1292 return -EUNATCH;
1293
1294 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
1295
1296 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1297 r = run_fsck(node, fstype);
1298 if (r < 0)
1299 return r;
1300 }
1301
1302 if (directory) {
1303 if (!FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY)) {
1304 /* Automatically create missing mount points, if necessary. */
1305 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1306 if (r < 0)
1307 return r;
1308 }
1309
1310 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
1311 if (r < 0)
1312 return r;
1313
1314 p = chased;
1315 } else
1316 p = where;
1317
1318 /* If requested, turn on discard support. */
1319 if (fstype_can_discard(fstype) &&
1320 ((flags & DISSECT_IMAGE_DISCARD) ||
1321 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
1322 options = strdup("discard");
1323 if (!options)
1324 return -ENOMEM;
1325 }
1326
1327 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
1328 _cleanup_free_ char *uid_option = NULL;
1329
1330 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1331 return -ENOMEM;
1332
1333 if (!strextend_with_separator(&options, ",", uid_option, NULL))
1334 return -ENOMEM;
1335 }
1336
1337 if (!isempty(m->mount_options))
1338 if (!strextend_with_separator(&options, ",", m->mount_options, NULL))
1339 return -ENOMEM;
1340
1341 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1342 r = mkdir_p(p, 0755);
1343 if (r < 0)
1344 return r;
1345 }
1346
1347 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
1348 if (r < 0)
1349 return r;
1350
1351 return 1;
1352 }
1353
1354 int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1355 int r, xbootldr_mounted;
1356
1357 assert(m);
1358 assert(where);
1359
1360 /* Returns:
1361 *
1362 * -ENXIO → No root partition found
1363 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release file found
1364 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1365 * -EUCLEAN → fsck for file system failed
1366 * -EBUSY → File system already mounted/used elsewhere (kernel)
1367 * -EAFNOSUPPORT → File system type not supported or not known
1368 */
1369
1370 if (!m->partitions[PARTITION_ROOT].found)
1371 return -ENXIO;
1372
1373 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1374 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
1375 if (r < 0)
1376 return r;
1377 }
1378
1379 /* Mask DISSECT_IMAGE_MKDIR for all subdirs: the idea is that only the top-level mount point is
1380 * created if needed, but the image itself not modified. */
1381 flags &= ~DISSECT_IMAGE_MKDIR;
1382
1383 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1384 /* For us mounting root always means mounting /usr as well */
1385 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, flags);
1386 if (r < 0)
1387 return r;
1388
1389 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
1390 r = path_is_os_tree(where);
1391 if (r < 0)
1392 return r;
1393 if (r == 0)
1394 return -EMEDIUMTYPE;
1395 }
1396 }
1397
1398 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
1399 return 0;
1400
1401 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
1402 if (r < 0)
1403 return r;
1404
1405 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
1406 if (r < 0)
1407 return r;
1408
1409 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, flags);
1410 if (r < 0)
1411 return r;
1412
1413 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, flags);
1414 if (r < 0)
1415 return r;
1416
1417 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, flags);
1418 if (xbootldr_mounted < 0)
1419 return xbootldr_mounted;
1420
1421 if (m->partitions[PARTITION_ESP].found) {
1422 int esp_done = false;
1423
1424 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1425 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1426
1427 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1428 if (r < 0) {
1429 if (r != -ENOENT)
1430 return r;
1431
1432 /* /efi doesn't exist. Let's see if /boot is suitable then */
1433
1434 if (!xbootldr_mounted) {
1435 _cleanup_free_ char *p = NULL;
1436
1437 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1438 if (r < 0) {
1439 if (r != -ENOENT)
1440 return r;
1441 } else if (dir_is_empty(p) > 0) {
1442 /* It exists and is an empty directory. Let's mount the ESP there. */
1443 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, flags);
1444 if (r < 0)
1445 return r;
1446
1447 esp_done = true;
1448 }
1449 }
1450 }
1451
1452 if (!esp_done) {
1453 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1454
1455 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, flags);
1456 if (r < 0)
1457 return r;
1458 }
1459 }
1460
1461 return 0;
1462 }
1463
1464 int dissected_image_mount_and_warn(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1465 int r;
1466
1467 assert(m);
1468 assert(where);
1469
1470 r = dissected_image_mount(m, where, uid_shift, flags);
1471 if (r == -ENXIO)
1472 return log_error_errno(r, "Not root file system found in image.");
1473 if (r == -EMEDIUMTYPE)
1474 return log_error_errno(r, "No suitable os-release file in image found.");
1475 if (r == -EUNATCH)
1476 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1477 if (r == -EUCLEAN)
1478 return log_error_errno(r, "File system check on image failed.");
1479 if (r == -EBUSY)
1480 return log_error_errno(r, "File system already mounted elsewhere.");
1481 if (r == -EAFNOSUPPORT)
1482 return log_error_errno(r, "File system type not supported or not known.");
1483 if (r < 0)
1484 return log_error_errno(r, "Failed to mount image: %m");
1485
1486 return r;
1487 }
1488
1489 #if HAVE_LIBCRYPTSETUP
1490 typedef struct DecryptedPartition {
1491 struct crypt_device *device;
1492 char *name;
1493 bool relinquished;
1494 } DecryptedPartition;
1495
1496 struct DecryptedImage {
1497 DecryptedPartition *decrypted;
1498 size_t n_decrypted;
1499 size_t n_allocated;
1500 };
1501 #endif
1502
1503 DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
1504 #if HAVE_LIBCRYPTSETUP
1505 size_t i;
1506 int r;
1507
1508 if (!d)
1509 return NULL;
1510
1511 for (i = 0; i < d->n_decrypted; i++) {
1512 DecryptedPartition *p = d->decrypted + i;
1513
1514 if (p->device && p->name && !p->relinquished) {
1515 r = sym_crypt_deactivate_by_name(p->device, p->name, 0);
1516 if (r < 0)
1517 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1518 }
1519
1520 if (p->device)
1521 sym_crypt_free(p->device);
1522 free(p->name);
1523 }
1524
1525 free(d);
1526 #endif
1527 return NULL;
1528 }
1529
1530 #if HAVE_LIBCRYPTSETUP
1531
1532 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1533 _cleanup_free_ char *name = NULL, *node = NULL;
1534 const char *base;
1535
1536 assert(original_node);
1537 assert(suffix);
1538 assert(ret_name);
1539 assert(ret_node);
1540
1541 base = strrchr(original_node, '/');
1542 if (!base)
1543 base = original_node;
1544 else
1545 base++;
1546 if (isempty(base))
1547 return -EINVAL;
1548
1549 name = strjoin(base, suffix);
1550 if (!name)
1551 return -ENOMEM;
1552 if (!filename_is_valid(name))
1553 return -EINVAL;
1554
1555 node = path_join(sym_crypt_get_dir(), name);
1556 if (!node)
1557 return -ENOMEM;
1558
1559 *ret_name = TAKE_PTR(name);
1560 *ret_node = TAKE_PTR(node);
1561
1562 return 0;
1563 }
1564
1565 static int decrypt_partition(
1566 DissectedPartition *m,
1567 const char *passphrase,
1568 DissectImageFlags flags,
1569 DecryptedImage *d) {
1570
1571 _cleanup_free_ char *node = NULL, *name = NULL;
1572 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
1573 int r;
1574
1575 assert(m);
1576 assert(d);
1577
1578 if (!m->found || !m->node || !m->fstype)
1579 return 0;
1580
1581 if (!streq(m->fstype, "crypto_LUKS"))
1582 return 0;
1583
1584 if (!passphrase)
1585 return -ENOKEY;
1586
1587 r = dlopen_cryptsetup();
1588 if (r < 0)
1589 return r;
1590
1591 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1592 if (r < 0)
1593 return r;
1594
1595 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1596 return -ENOMEM;
1597
1598 r = sym_crypt_init(&cd, m->node);
1599 if (r < 0)
1600 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
1601
1602 cryptsetup_enable_logging(cd);
1603
1604 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
1605 if (r < 0)
1606 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
1607
1608 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1609 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1610 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
1611 if (r < 0) {
1612 log_debug_errno(r, "Failed to activate LUKS device: %m");
1613 return r == -EPERM ? -EKEYREJECTED : r;
1614 }
1615
1616 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1617 .name = TAKE_PTR(name),
1618 .device = TAKE_PTR(cd),
1619 };
1620
1621 m->decrypted_node = TAKE_PTR(node);
1622
1623 return 0;
1624 }
1625
1626 static int verity_can_reuse(
1627 const VeritySettings *verity,
1628 const char *name,
1629 struct crypt_device **ret_cd) {
1630
1631 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1632 _cleanup_free_ char *root_hash_existing = NULL;
1633 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
1634 struct crypt_params_verity crypt_params = {};
1635 size_t root_hash_existing_size;
1636 int r;
1637
1638 assert(verity);
1639 assert(name);
1640 assert(ret_cd);
1641
1642 r = sym_crypt_init_by_name(&cd, name);
1643 if (r < 0)
1644 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
1645
1646 r = sym_crypt_get_verity_info(cd, &crypt_params);
1647 if (r < 0)
1648 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
1649
1650 root_hash_existing_size = verity->root_hash_size;
1651 root_hash_existing = malloc0(root_hash_existing_size);
1652 if (!root_hash_existing)
1653 return -ENOMEM;
1654
1655 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
1656 if (r < 0)
1657 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
1658 if (verity->root_hash_size != root_hash_existing_size ||
1659 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
1660 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
1661
1662 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1663 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1664 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1665 * signing for the new one, and viceversa. */
1666 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
1667 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1668 #endif
1669
1670 *ret_cd = TAKE_PTR(cd);
1671 return 0;
1672 }
1673
1674 static inline void dm_deferred_remove_clean(char *name) {
1675 if (!name)
1676 return;
1677
1678 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
1679 free(name);
1680 }
1681 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1682
1683 static int verity_partition(
1684 PartitionDesignator designator,
1685 DissectedPartition *m,
1686 DissectedPartition *v,
1687 const VeritySettings *verity,
1688 DissectImageFlags flags,
1689 DecryptedImage *d) {
1690
1691 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
1692 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
1693 _cleanup_free_ char *node = NULL, *name = NULL;
1694 int r;
1695
1696 assert(m);
1697 assert(v || (verity && verity->data_path));
1698
1699 if (!verity || !verity->root_hash)
1700 return 0;
1701 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
1702 (verity->designator == designator)))
1703 return 0;
1704
1705 if (!m->found || !m->node || !m->fstype)
1706 return 0;
1707 if (!verity->data_path) {
1708 if (!v->found || !v->node || !v->fstype)
1709 return 0;
1710
1711 if (!streq(v->fstype, "DM_verity_hash"))
1712 return 0;
1713 }
1714
1715 r = dlopen_cryptsetup();
1716 if (r < 0)
1717 return r;
1718
1719 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
1720 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1721 _cleanup_free_ char *root_hash_encoded = NULL;
1722
1723 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
1724 if (!root_hash_encoded)
1725 return -ENOMEM;
1726
1727 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
1728 } else
1729 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
1730 if (r < 0)
1731 return r;
1732
1733 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
1734 if (r < 0)
1735 return r;
1736
1737 cryptsetup_enable_logging(cd);
1738
1739 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
1740 if (r < 0)
1741 return r;
1742
1743 r = sym_crypt_set_data_device(cd, m->node);
1744 if (r < 0)
1745 return r;
1746
1747 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1748 return -ENOMEM;
1749
1750 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1751 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1752 * retry a few times before giving up. */
1753 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
1754 if (verity->root_hash_sig) {
1755 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1756 r = sym_crypt_activate_by_signed_key(
1757 cd,
1758 name,
1759 verity->root_hash,
1760 verity->root_hash_size,
1761 verity->root_hash_sig,
1762 verity->root_hash_sig_size,
1763 CRYPT_ACTIVATE_READONLY);
1764 #else
1765 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1766 "Activation of verity device with signature requested, but not supported by %s due to missing crypt_activate_by_signed_key().", program_invocation_short_name);
1767 #endif
1768 } else
1769 r = sym_crypt_activate_by_volume_key(
1770 cd,
1771 name,
1772 verity->root_hash,
1773 verity->root_hash_size,
1774 CRYPT_ACTIVATE_READONLY);
1775 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1776 * There's no way to distinguish this situation from a genuine error due to invalid
1777 * parameters, so immediately fall back to activating the device with a unique name.
1778 * Improvements in libcrypsetup can ensure this never happens:
1779 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1780 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1781 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1782 if (!IN_SET(r,
1783 0, /* Success */
1784 -EEXIST, /* Volume is already open and ready to be used */
1785 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
1786 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
1787 return r;
1788 if (IN_SET(r, -EEXIST, -EBUSY)) {
1789 struct crypt_device *existing_cd = NULL;
1790
1791 if (!restore_deferred_remove){
1792 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1793 r = dm_deferred_remove_cancel(name);
1794 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
1795 if (r < 0 && r != -ENXIO)
1796 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
1797 if (r == 0) {
1798 restore_deferred_remove = strdup(name);
1799 if (!restore_deferred_remove)
1800 return -ENOMEM;
1801 }
1802 }
1803
1804 r = verity_can_reuse(verity, name, &existing_cd);
1805 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1806 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1807 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1808 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
1809 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
1810 if (r == 0) {
1811 /* devmapper might say that the device exists, but the devlink might not yet have been
1812 * created. Check and wait for the udev event in that case. */
1813 r = device_wait_for_devlink(node, "block", usec_add(now(CLOCK_MONOTONIC), 100 * USEC_PER_MSEC), NULL);
1814 /* Fallback to activation with a unique device if it's taking too long */
1815 if (r == -ETIMEDOUT)
1816 break;
1817 if (r < 0)
1818 return r;
1819
1820 if (cd)
1821 sym_crypt_free(cd);
1822 cd = existing_cd;
1823 }
1824 }
1825 if (r == 0)
1826 break;
1827
1828 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
1829 (void) usleep(2 * USEC_PER_MSEC);
1830 }
1831
1832 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1833 * Fall back to activating it with a unique device name. */
1834 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1835 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1836
1837 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1838 restore_deferred_remove = mfree(restore_deferred_remove);
1839
1840 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1841 .name = TAKE_PTR(name),
1842 .device = TAKE_PTR(cd),
1843 };
1844
1845 m->decrypted_node = TAKE_PTR(node);
1846
1847 return 0;
1848 }
1849 #endif
1850
1851 int dissected_image_decrypt(
1852 DissectedImage *m,
1853 const char *passphrase,
1854 const VeritySettings *verity,
1855 DissectImageFlags flags,
1856 DecryptedImage **ret) {
1857
1858 #if HAVE_LIBCRYPTSETUP
1859 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
1860 int r;
1861 #endif
1862
1863 assert(m);
1864 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
1865
1866 /* Returns:
1867 *
1868 * = 0 → There was nothing to decrypt
1869 * > 0 → Decrypted successfully
1870 * -ENOKEY → There's something to decrypt but no key was supplied
1871 * -EKEYREJECTED → Passed key was not correct
1872 */
1873
1874 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
1875 return -EINVAL;
1876
1877 if (!m->encrypted && !m->verity) {
1878 *ret = NULL;
1879 return 0;
1880 }
1881
1882 #if HAVE_LIBCRYPTSETUP
1883 d = new0(DecryptedImage, 1);
1884 if (!d)
1885 return -ENOMEM;
1886
1887 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1888 DissectedPartition *p = m->partitions + i;
1889 PartitionDesignator k;
1890
1891 if (!p->found)
1892 continue;
1893
1894 r = decrypt_partition(p, passphrase, flags, d);
1895 if (r < 0)
1896 return r;
1897
1898 k = PARTITION_VERITY_OF(i);
1899 if (k >= 0) {
1900 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
1901 if (r < 0)
1902 return r;
1903 }
1904
1905 if (!p->decrypted_fstype && p->decrypted_node) {
1906 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
1907 if (r < 0 && r != -EUCLEAN)
1908 return r;
1909 }
1910 }
1911
1912 *ret = TAKE_PTR(d);
1913
1914 return 1;
1915 #else
1916 return -EOPNOTSUPP;
1917 #endif
1918 }
1919
1920 int dissected_image_decrypt_interactively(
1921 DissectedImage *m,
1922 const char *passphrase,
1923 const VeritySettings *verity,
1924 DissectImageFlags flags,
1925 DecryptedImage **ret) {
1926
1927 _cleanup_strv_free_erase_ char **z = NULL;
1928 int n = 3, r;
1929
1930 if (passphrase)
1931 n--;
1932
1933 for (;;) {
1934 r = dissected_image_decrypt(m, passphrase, verity, flags, ret);
1935 if (r >= 0)
1936 return r;
1937 if (r == -EKEYREJECTED)
1938 log_error_errno(r, "Incorrect passphrase, try again!");
1939 else if (r != -ENOKEY)
1940 return log_error_errno(r, "Failed to decrypt image: %m");
1941
1942 if (--n < 0)
1943 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1944 "Too many retries.");
1945
1946 z = strv_free(z);
1947
1948 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
1949 if (r < 0)
1950 return log_error_errno(r, "Failed to query for passphrase: %m");
1951
1952 passphrase = z[0];
1953 }
1954 }
1955
1956 int decrypted_image_relinquish(DecryptedImage *d) {
1957
1958 #if HAVE_LIBCRYPTSETUP
1959 size_t i;
1960 int r;
1961 #endif
1962
1963 assert(d);
1964
1965 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1966 * that we don't clean it up ourselves either anymore */
1967
1968 #if HAVE_LIBCRYPTSETUP
1969 for (i = 0; i < d->n_decrypted; i++) {
1970 DecryptedPartition *p = d->decrypted + i;
1971
1972 if (p->relinquished)
1973 continue;
1974
1975 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
1976 if (r < 0)
1977 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1978
1979 p->relinquished = true;
1980 }
1981 #endif
1982
1983 return 0;
1984 }
1985
1986 static char *build_auxiliary_path(const char *image, const char *suffix) {
1987 const char *e;
1988 char *n;
1989
1990 assert(image);
1991 assert(suffix);
1992
1993 e = endswith(image, ".raw");
1994 if (!e)
1995 return strjoin(e, suffix);
1996
1997 n = new(char, e - image + strlen(suffix) + 1);
1998 if (!n)
1999 return NULL;
2000
2001 strcpy(mempcpy(n, image, e - image), suffix);
2002 return n;
2003 }
2004
2005 void verity_settings_done(VeritySettings *v) {
2006 assert(v);
2007
2008 v->root_hash = mfree(v->root_hash);
2009 v->root_hash_size = 0;
2010
2011 v->root_hash_sig = mfree(v->root_hash_sig);
2012 v->root_hash_sig_size = 0;
2013
2014 v->data_path = mfree(v->data_path);
2015 }
2016
2017 int verity_settings_load(
2018 VeritySettings *verity,
2019 const char *image,
2020 const char *root_hash_path,
2021 const char *root_hash_sig_path) {
2022
2023 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2024 size_t root_hash_size = 0, root_hash_sig_size = 0;
2025 _cleanup_free_ char *verity_data_path = NULL;
2026 PartitionDesignator designator;
2027 int r;
2028
2029 assert(verity);
2030 assert(image);
2031 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
2032
2033 /* If we are asked to load the root hash for a device node, exit early */
2034 if (is_device_path(image))
2035 return 0;
2036
2037 designator = verity->designator;
2038
2039 /* We only fill in what isn't already filled in */
2040
2041 if (!verity->root_hash) {
2042 _cleanup_free_ char *text = NULL;
2043
2044 if (root_hash_path) {
2045 /* If explicitly specified it takes precedence */
2046 r = read_one_line_file(root_hash_path, &text);
2047 if (r < 0)
2048 return r;
2049
2050 if (designator < 0)
2051 designator = PARTITION_ROOT;
2052 } else {
2053 /* Otherwise look for xattr and separate file, and first for the data for root and if
2054 * that doesn't exist for /usr */
2055
2056 if (designator < 0 || designator == PARTITION_ROOT) {
2057 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
2058 if (r < 0) {
2059 _cleanup_free_ char *p = NULL;
2060
2061 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2062 return r;
2063
2064 p = build_auxiliary_path(image, ".roothash");
2065 if (!p)
2066 return -ENOMEM;
2067
2068 r = read_one_line_file(p, &text);
2069 if (r < 0 && r != -ENOENT)
2070 return r;
2071 }
2072
2073 if (text)
2074 designator = PARTITION_ROOT;
2075 }
2076
2077 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2078 /* So in the "roothash" xattr/file name above the "root" of course primarily
2079 * refers to the root of the Verity Merkle tree. But coincidentally it also
2080 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2081 * two distinct concepts called "root". Taking benefit of this happy
2082 * coincidence we call the file with the root hash for the /usr/ file system
2083 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2084 * confusing. We thus drop the reference to the root of the Merkle tree, and
2085 * just indicate which file system it's about. */
2086 r = getxattr_malloc(image, "user.verity.usrhash", &text, true);
2087 if (r < 0) {
2088 _cleanup_free_ char *p = NULL;
2089
2090 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2091 return r;
2092
2093 p = build_auxiliary_path(image, ".usrhash");
2094 if (!p)
2095 return -ENOMEM;
2096
2097 r = read_one_line_file(p, &text);
2098 if (r < 0 && r != -ENOENT)
2099 return r;
2100 }
2101
2102 if (text)
2103 designator = PARTITION_USR;
2104 }
2105 }
2106
2107 if (text) {
2108 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
2109 if (r < 0)
2110 return r;
2111 if (root_hash_size < sizeof(sd_id128_t))
2112 return -EINVAL;
2113 }
2114 }
2115
2116 if (verity->root_hash && !verity->root_hash_sig) {
2117 if (root_hash_sig_path) {
2118 r = read_full_file_full(AT_FDCWD, root_hash_sig_path, 0, NULL, (char**) &root_hash_sig, &root_hash_sig_size);
2119 if (r < 0 && r != -ENOENT)
2120 return r;
2121
2122 if (designator < 0)
2123 designator = PARTITION_ROOT;
2124 } else {
2125 if (designator < 0 || designator == PARTITION_ROOT) {
2126 _cleanup_free_ char *p = NULL;
2127
2128 /* Follow naming convention recommended by the relevant RFC:
2129 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2130 p = build_auxiliary_path(image, ".roothash.p7s");
2131 if (!p)
2132 return -ENOMEM;
2133
2134 r = read_full_file_full(AT_FDCWD, p, 0, NULL, (char**) &root_hash_sig, &root_hash_sig_size);
2135 if (r < 0 && r != -ENOENT)
2136 return r;
2137 if (r >= 0)
2138 designator = PARTITION_ROOT;
2139 }
2140
2141 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2142 _cleanup_free_ char *p = NULL;
2143
2144 p = build_auxiliary_path(image, ".usrhash.p7s");
2145 if (!p)
2146 return -ENOMEM;
2147
2148 r = read_full_file_full(AT_FDCWD, p, 0, NULL, (char**) &root_hash_sig, &root_hash_sig_size);
2149 if (r < 0 && r != -ENOENT)
2150 return r;
2151 if (r >= 0)
2152 designator = PARTITION_USR;
2153 }
2154 }
2155
2156 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
2157 return -EINVAL;
2158 }
2159
2160 if (!verity->data_path) {
2161 _cleanup_free_ char *p = NULL;
2162
2163 p = build_auxiliary_path(image, ".verity");
2164 if (!p)
2165 return -ENOMEM;
2166
2167 if (access(p, F_OK) < 0) {
2168 if (errno != ENOENT)
2169 return -errno;
2170 } else
2171 verity_data_path = TAKE_PTR(p);
2172 }
2173
2174 if (root_hash) {
2175 verity->root_hash = TAKE_PTR(root_hash);
2176 verity->root_hash_size = root_hash_size;
2177 }
2178
2179 if (root_hash_sig) {
2180 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2181 verity->root_hash_sig_size = root_hash_sig_size;
2182 }
2183
2184 if (verity_data_path)
2185 verity->data_path = TAKE_PTR(verity_data_path);
2186
2187 if (verity->designator < 0)
2188 verity->designator = designator;
2189
2190 return 1;
2191 }
2192
2193 int dissected_image_acquire_metadata(DissectedImage *m) {
2194
2195 enum {
2196 META_HOSTNAME,
2197 META_MACHINE_ID,
2198 META_MACHINE_INFO,
2199 META_OS_RELEASE,
2200 _META_MAX,
2201 };
2202
2203 static const char *const paths[_META_MAX] = {
2204 [META_HOSTNAME] = "/etc/hostname\0",
2205 [META_MACHINE_ID] = "/etc/machine-id\0",
2206 [META_MACHINE_INFO] = "/etc/machine-info\0",
2207 [META_OS_RELEASE] = "/etc/os-release\0"
2208 "/usr/lib/os-release\0",
2209 };
2210
2211 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
2212 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
2213 _cleanup_(rmdir_and_freep) char *t = NULL;
2214 _cleanup_(sigkill_waitp) pid_t child = 0;
2215 sd_id128_t machine_id = SD_ID128_NULL;
2216 _cleanup_free_ char *hostname = NULL;
2217 unsigned n_meta_initialized = 0, k;
2218 int fds[2 * _META_MAX], r, v;
2219 ssize_t n;
2220
2221 BLOCK_SIGNALS(SIGCHLD);
2222
2223 assert(m);
2224
2225 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
2226 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2227 r = -errno;
2228 goto finish;
2229 }
2230
2231 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2232 if (r < 0)
2233 goto finish;
2234
2235 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2236 r = -errno;
2237 goto finish;
2238 }
2239
2240 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
2241 if (r < 0)
2242 goto finish;
2243 if (r == 0) {
2244 error_pipe[0] = safe_close(error_pipe[0]);
2245
2246 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
2247 if (r < 0) {
2248 /* Let parent know the error */
2249 (void) write(error_pipe[1], &r, sizeof(r));
2250
2251 log_debug_errno(r, "Failed to mount dissected image: %m");
2252 _exit(EXIT_FAILURE);
2253 }
2254
2255 for (k = 0; k < _META_MAX; k++) {
2256 _cleanup_close_ int fd = -ENOENT;
2257 const char *p;
2258
2259 fds[2*k] = safe_close(fds[2*k]);
2260
2261 NULSTR_FOREACH(p, paths[k]) {
2262 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
2263 if (fd >= 0)
2264 break;
2265 }
2266 if (fd < 0) {
2267 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
2268 fds[2*k+1] = safe_close(fds[2*k+1]);
2269 continue;
2270 }
2271
2272 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
2273 if (r < 0) {
2274 (void) write(error_pipe[1], &r, sizeof(r));
2275 _exit(EXIT_FAILURE);
2276 }
2277
2278 fds[2*k+1] = safe_close(fds[2*k+1]);
2279 }
2280
2281 _exit(EXIT_SUCCESS);
2282 }
2283
2284 error_pipe[1] = safe_close(error_pipe[1]);
2285
2286 for (k = 0; k < _META_MAX; k++) {
2287 _cleanup_fclose_ FILE *f = NULL;
2288
2289 fds[2*k+1] = safe_close(fds[2*k+1]);
2290
2291 f = take_fdopen(&fds[2*k], "r");
2292 if (!f) {
2293 r = -errno;
2294 goto finish;
2295 }
2296
2297 switch (k) {
2298
2299 case META_HOSTNAME:
2300 r = read_etc_hostname_stream(f, &hostname);
2301 if (r < 0)
2302 log_debug_errno(r, "Failed to read /etc/hostname: %m");
2303
2304 break;
2305
2306 case META_MACHINE_ID: {
2307 _cleanup_free_ char *line = NULL;
2308
2309 r = read_line(f, LONG_LINE_MAX, &line);
2310 if (r < 0)
2311 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
2312 else if (r == 33) {
2313 r = sd_id128_from_string(line, &machine_id);
2314 if (r < 0)
2315 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
2316 } else if (r == 0)
2317 log_debug("/etc/machine-id file is empty.");
2318 else if (streq(line, "uninitialized"))
2319 log_debug("/etc/machine-id file is uninitialized (likely aborted first boot).");
2320 else
2321 log_debug("/etc/machine-id has unexpected length %i.", r);
2322
2323 break;
2324 }
2325
2326 case META_MACHINE_INFO:
2327 r = load_env_file_pairs(f, "machine-info", &machine_info);
2328 if (r < 0)
2329 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
2330
2331 break;
2332
2333 case META_OS_RELEASE:
2334 r = load_env_file_pairs(f, "os-release", &os_release);
2335 if (r < 0)
2336 log_debug_errno(r, "Failed to read OS release file: %m");
2337
2338 break;
2339 }
2340 }
2341
2342 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
2343 child = 0;
2344 if (r < 0)
2345 return r;
2346
2347 n = read(error_pipe[0], &v, sizeof(v));
2348 if (n < 0)
2349 return -errno;
2350 if (n == sizeof(v))
2351 return v; /* propagate error sent to us from child */
2352 if (n != 0)
2353 return -EIO;
2354
2355 if (r != EXIT_SUCCESS)
2356 return -EPROTO;
2357
2358 free_and_replace(m->hostname, hostname);
2359 m->machine_id = machine_id;
2360 strv_free_and_replace(m->machine_info, machine_info);
2361 strv_free_and_replace(m->os_release, os_release);
2362
2363 finish:
2364 for (k = 0; k < n_meta_initialized; k++)
2365 safe_close_pair(fds + 2*k);
2366
2367 return r;
2368 }
2369
2370 int dissect_image_and_warn(
2371 int fd,
2372 const char *name,
2373 const VeritySettings *verity,
2374 const MountOptions *mount_options,
2375 DissectImageFlags flags,
2376 DissectedImage **ret) {
2377
2378 _cleanup_free_ char *buffer = NULL;
2379 int r;
2380
2381 if (!name) {
2382 r = fd_get_path(fd, &buffer);
2383 if (r < 0)
2384 return r;
2385
2386 name = buffer;
2387 }
2388
2389 r = dissect_image(fd, verity, mount_options, flags, ret);
2390 switch (r) {
2391
2392 case -EOPNOTSUPP:
2393 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
2394
2395 case -ENOPKG:
2396 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
2397
2398 case -EADDRNOTAVAIL:
2399 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
2400
2401 case -ENOTUNIQ:
2402 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
2403
2404 case -ENXIO:
2405 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
2406
2407 case -EPROTONOSUPPORT:
2408 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
2409
2410 default:
2411 if (r < 0)
2412 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
2413
2414 return r;
2415 }
2416 }
2417
2418 bool dissected_image_can_do_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
2419 if (image->single_file_system)
2420 return partition_designator == PARTITION_ROOT && image->can_verity;
2421
2422 return PARTITION_VERITY_OF(partition_designator) >= 0;
2423 }
2424
2425 bool dissected_image_has_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
2426 int k;
2427
2428 if (image->single_file_system)
2429 return partition_designator == PARTITION_ROOT && image->verity;
2430
2431 k = PARTITION_VERITY_OF(partition_designator);
2432 return k >= 0 && image->partitions[k].found;
2433 }
2434
2435 MountOptions* mount_options_free_all(MountOptions *options) {
2436 MountOptions *m;
2437
2438 while ((m = options)) {
2439 LIST_REMOVE(mount_options, options, m);
2440 free(m->options);
2441 free(m);
2442 }
2443
2444 return NULL;
2445 }
2446
2447 const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
2448 const MountOptions *m;
2449
2450 LIST_FOREACH(mount_options, m, options)
2451 if (designator == m->partition_designator && !isempty(m->options))
2452 return m->options;
2453
2454 return NULL;
2455 }
2456
2457 int mount_image_privately_interactively(
2458 const char *image,
2459 DissectImageFlags flags,
2460 char **ret_directory,
2461 LoopDevice **ret_loop_device,
2462 DecryptedImage **ret_decrypted_image) {
2463
2464 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2465 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2466 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2467 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
2468 _cleanup_free_ char *temp = NULL;
2469 int r;
2470
2471 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2472 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2473 * easily. */
2474
2475 assert(image);
2476 assert(ret_directory);
2477 assert(ret_loop_device);
2478 assert(ret_decrypted_image);
2479
2480 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
2481 if (r < 0)
2482 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
2483
2484 r = loop_device_make_by_path(
2485 image,
2486 FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY) ? O_RDONLY : O_RDWR,
2487 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2488 &d);
2489 if (r < 0)
2490 return log_error_errno(r, "Failed to set up loopback device: %m");
2491
2492 r = dissect_image_and_warn(d->fd, image, NULL, NULL, flags, &dissected_image);
2493 if (r < 0)
2494 return r;
2495
2496 r = dissected_image_decrypt_interactively(dissected_image, NULL, NULL, flags, &decrypted_image);
2497 if (r < 0)
2498 return r;
2499
2500 r = detach_mount_namespace();
2501 if (r < 0)
2502 return log_error_errno(r, "Failed to detach mount namespace: %m");
2503
2504 r = mkdir_p(temp, 0700);
2505 if (r < 0)
2506 return log_error_errno(r, "Failed to create mount point: %m");
2507
2508 created_dir = TAKE_PTR(temp);
2509
2510 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, flags);
2511 if (r < 0)
2512 return r;
2513
2514 if (decrypted_image) {
2515 r = decrypted_image_relinquish(decrypted_image);
2516 if (r < 0)
2517 return log_error_errno(r, "Failed to relinquish DM devices: %m");
2518 }
2519
2520 loop_device_relinquish(d);
2521
2522 *ret_directory = TAKE_PTR(created_dir);
2523 *ret_loop_device = TAKE_PTR(d);
2524 *ret_decrypted_image = TAKE_PTR(decrypted_image);
2525
2526 return 0;
2527 }
2528
2529 static const char *const partition_designator_table[] = {
2530 [PARTITION_ROOT] = "root",
2531 [PARTITION_ROOT_SECONDARY] = "root-secondary",
2532 [PARTITION_USR] = "usr",
2533 [PARTITION_USR_SECONDARY] = "usr-secondary",
2534 [PARTITION_HOME] = "home",
2535 [PARTITION_SRV] = "srv",
2536 [PARTITION_ESP] = "esp",
2537 [PARTITION_XBOOTLDR] = "xbootldr",
2538 [PARTITION_SWAP] = "swap",
2539 [PARTITION_ROOT_VERITY] = "root-verity",
2540 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
2541 [PARTITION_USR_VERITY] = "usr-verity",
2542 [PARTITION_USR_SECONDARY_VERITY] = "usr-secondary-verity",
2543 [PARTITION_TMP] = "tmp",
2544 [PARTITION_VAR] = "var",
2545 };
2546
2547 DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);