]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
dissect-image: add env var for disabling "sidecar" loading of verity params
[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 "discover-image.h"
27 #include "dissect-image.h"
28 #include "dm-util.h"
29 #include "env-file.h"
30 #include "env-util.h"
31 #include "extension-release.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "fs-util.h"
35 #include "fsck-util.h"
36 #include "gpt.h"
37 #include "hexdecoct.h"
38 #include "hostname-setup.h"
39 #include "id128-util.h"
40 #include "import-util.h"
41 #include "mkdir.h"
42 #include "mount-util.h"
43 #include "mountpoint-util.h"
44 #include "namespace-util.h"
45 #include "nulstr-util.h"
46 #include "os-util.h"
47 #include "path-util.h"
48 #include "process-util.h"
49 #include "raw-clone.h"
50 #include "resize-fs.h"
51 #include "signal-util.h"
52 #include "stat-util.h"
53 #include "stdio-util.h"
54 #include "string-table.h"
55 #include "string-util.h"
56 #include "strv.h"
57 #include "tmpfile-util.h"
58 #include "udev-util.h"
59 #include "user-util.h"
60 #include "xattr-util.h"
61
62 /* how many times to wait for the device nodes to appear */
63 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
64
65 int probe_filesystem(const char *node, char **ret_fstype) {
66 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
67 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
68 * different error otherwise. */
69
70 #if HAVE_BLKID
71 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
72 const char *fstype;
73 int r;
74
75 errno = 0;
76 b = blkid_new_probe_from_filename(node);
77 if (!b)
78 return errno_or_else(ENOMEM);
79
80 blkid_probe_enable_superblocks(b, 1);
81 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
82
83 errno = 0;
84 r = blkid_do_safeprobe(b);
85 if (r == 1) {
86 log_debug("No type detected on partition %s", node);
87 goto not_found;
88 }
89 if (r == -2)
90 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
91 "Results ambiguous for partition %s", node);
92 if (r != 0)
93 return errno_or_else(EIO);
94
95 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
96
97 if (fstype) {
98 char *t;
99
100 t = strdup(fstype);
101 if (!t)
102 return -ENOMEM;
103
104 *ret_fstype = t;
105 return 1;
106 }
107
108 not_found:
109 *ret_fstype = NULL;
110 return 0;
111 #else
112 return -EOPNOTSUPP;
113 #endif
114 }
115
116 #if HAVE_BLKID
117 static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
118 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
119 int r;
120
121 assert(d);
122 assert(ret);
123
124 r = sd_device_enumerator_new(&e);
125 if (r < 0)
126 return r;
127
128 r = sd_device_enumerator_add_match_subsystem(e, "block", true);
129 if (r < 0)
130 return r;
131
132 r = sd_device_enumerator_add_match_parent(e, d);
133 if (r < 0)
134 return r;
135
136 r = sd_device_enumerator_add_match_sysattr(e, "partition", NULL, true);
137 if (r < 0)
138 return r;
139
140 *ret = TAKE_PTR(e);
141 return 0;
142 }
143
144 static int device_is_partition(
145 sd_device *d,
146 sd_device *expected_parent,
147 blkid_partition pp) {
148
149 const char *v, *parent_syspath, *expected_parent_syspath;
150 blkid_loff_t bsize, bstart;
151 uint64_t size, start;
152 int partno, bpartno, r;
153 sd_device *parent;
154
155 assert(d);
156 assert(expected_parent);
157 assert(pp);
158
159 r = sd_device_get_subsystem(d, &v);
160 if (r < 0)
161 return r;
162 if (!streq(v, "block"))
163 return false;
164
165 if (sd_device_get_devtype(d, &v) < 0 || !streq(v, "partition"))
166 return false;
167
168 r = sd_device_get_parent(d, &parent);
169 if (r < 0)
170 return false; /* Doesn't have a parent? No relevant to us */
171
172 r = sd_device_get_syspath(parent, &parent_syspath); /* Check parent of device of this action */
173 if (r < 0)
174 return r;
175
176 r = sd_device_get_syspath(expected_parent, &expected_parent_syspath); /* Check parent of device we are looking for */
177 if (r < 0)
178 return r;
179
180 if (!path_equal(parent_syspath, expected_parent_syspath))
181 return false; /* Has a different parent than what we need, not interesting to us */
182
183 /* On kernel uevents we may find the partition number in the PARTN= field. Let's use that preferably,
184 * since it's cheaper and more importantly: the sysfs attribute "partition" appears to become
185 * available late, hence let's use the property instead, which is available at the moment we see the
186 * uevent. */
187 r = sd_device_get_property_value(d, "PARTN", &v);
188 if (r == -ENOENT)
189 r = sd_device_get_sysattr_value(d, "partition", &v);
190 if (r < 0)
191 return r;
192
193 r = safe_atoi(v, &partno);
194 if (r < 0)
195 return r;
196
197 errno = 0;
198 bpartno = blkid_partition_get_partno(pp);
199 if (bpartno < 0)
200 return errno_or_else(EIO);
201
202 if (partno != bpartno)
203 return false;
204
205 r = sd_device_get_sysattr_value(d, "start", &v);
206 if (r < 0)
207 return r;
208 r = safe_atou64(v, &start);
209 if (r < 0)
210 return r;
211
212 errno = 0;
213 bstart = blkid_partition_get_start(pp);
214 if (bstart < 0)
215 return errno_or_else(EIO);
216
217 if (start != (uint64_t) bstart)
218 return false;
219
220 r = sd_device_get_sysattr_value(d, "size", &v);
221 if (r < 0)
222 return r;
223 r = safe_atou64(v, &size);
224 if (r < 0)
225 return r;
226
227 errno = 0;
228 bsize = blkid_partition_get_size(pp);
229 if (bsize < 0)
230 return errno_or_else(EIO);
231
232 if (size != (uint64_t) bsize)
233 return false;
234
235 return true;
236 }
237
238 static int find_partition(
239 sd_device *parent,
240 blkid_partition pp,
241 usec_t timestamp_not_before,
242 DissectImageFlags flags,
243 sd_device **ret) {
244
245 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
246 sd_device *q;
247 int r;
248
249 assert(parent);
250 assert(pp);
251 assert(ret);
252
253 r = enumerator_for_parent(parent, &e);
254 if (r < 0)
255 return r;
256
257 FOREACH_DEVICE(e, q) {
258 uint64_t usec;
259
260 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
261 r = sd_device_get_usec_initialized(q, &usec);
262 if (r == -EBUSY) /* Not initialized yet */
263 continue;
264 if (r < 0)
265 return r;
266
267 if (timestamp_not_before != USEC_INFINITY &&
268 usec < timestamp_not_before) /* udev database entry older than our attachment? Then it's not ours */
269 continue;
270 }
271
272 r = device_is_partition(q, parent, pp);
273 if (r < 0)
274 return r;
275 if (r > 0) {
276 *ret = sd_device_ref(q);
277 return 0;
278 }
279 }
280
281 return -ENXIO;
282 }
283
284 struct wait_data {
285 sd_device *parent_device;
286 blkid_partition blkidp;
287 sd_device *found;
288 uint64_t diskseq;
289 uint64_t uevent_seqnum_not_before;
290 usec_t timestamp_not_before;
291 DissectImageFlags flags;
292 };
293
294 static inline void wait_data_done(struct wait_data *d) {
295 sd_device_unref(d->found);
296 }
297
298 static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) {
299 struct wait_data *w = userdata;
300 int r;
301
302 assert(w);
303
304 if (device_for_action(device, SD_DEVICE_REMOVE))
305 return 0;
306
307 if (w->diskseq != 0) {
308 uint64_t diskseq;
309
310 /* If w->diskseq is non-zero, then we must have a disk seqnum */
311 r = sd_device_get_diskseq(device, &diskseq);
312 if (r < 0) {
313 log_debug_errno(r, "Dropping event because it has no diskseq, but waiting for %" PRIu64, w->diskseq);
314 return 0;
315 }
316 if (diskseq < w->diskseq) {
317 log_debug("Dropping event because diskseq too old (%" PRIu64 " < %" PRIu64 ")",
318 diskseq, w->diskseq);
319 return 0;
320 }
321 if (diskseq > w->diskseq) {
322 r = -EBUSY;
323 goto finish; /* Newer than what we were expecting, so we missed it, stop waiting */
324 }
325 } else if (w->uevent_seqnum_not_before != UINT64_MAX) {
326 uint64_t seqnum;
327
328 r = sd_device_get_seqnum(device, &seqnum);
329 if (r < 0)
330 goto finish;
331
332 if (seqnum <= w->uevent_seqnum_not_before) { /* From an older use of this loop device */
333 log_debug("Dropping event because seqnum too old (%" PRIu64 " <= %" PRIu64 ")",
334 seqnum, w->uevent_seqnum_not_before);
335 return 0;
336 }
337 }
338
339 r = device_is_partition(device, w->parent_device, w->blkidp);
340 if (r < 0)
341 goto finish;
342 if (r == 0) /* Not the one we need */
343 return 0;
344
345 /* It's the one we need! Yay! */
346 assert(!w->found);
347 w->found = sd_device_ref(device);
348 r = 0;
349
350 finish:
351 return sd_event_exit(sd_device_monitor_get_event(monitor), r);
352 }
353
354 static int timeout_handler(sd_event_source *s, uint64_t usec, void *userdata) {
355 struct wait_data *w = userdata;
356 int r;
357
358 assert(w);
359
360 /* Why partition not appeared within the timeout? We may lost some uevent, as some properties
361 * were not ready when we received uevent... Not sure, but anyway, let's try to find the
362 * partition again before give up. */
363
364 r = find_partition(w->parent_device, w->blkidp, w->timestamp_not_before, w->flags, &w->found);
365 if (r == -ENXIO)
366 return log_debug_errno(SYNTHETIC_ERRNO(ETIMEDOUT),
367 "Partition still not appeared after timeout reached.");
368 if (r < 0)
369 return log_debug_errno(r, "Failed to find partition: %m");
370
371 log_debug("Partition appeared after timeout reached.");
372 return sd_event_exit(sd_event_source_get_event(s), 0);
373 }
374
375 static int retry_handler(sd_event_source *s, uint64_t usec, void *userdata) {
376 struct wait_data *w = userdata;
377 int r;
378
379 assert(w);
380
381 r = find_partition(w->parent_device, w->blkidp, w->timestamp_not_before, w->flags, &w->found);
382 if (r != -ENXIO) {
383 if (r < 0)
384 return log_debug_errno(r, "Failed to find partition: %m");
385
386 log_debug("Partition found by a periodic search.");
387 return sd_event_exit(sd_event_source_get_event(s), 0);
388 }
389
390 r = sd_event_source_set_time_relative(s, 500 * USEC_PER_MSEC);
391 if (r < 0)
392 return r;
393
394 return sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
395 }
396
397 static int wait_for_partition_device(
398 sd_device *parent,
399 blkid_partition pp,
400 usec_t deadline,
401 uint64_t diskseq,
402 uint64_t uevent_seqnum_not_before,
403 usec_t timestamp_not_before,
404 DissectImageFlags flags,
405 sd_device **ret) {
406
407 _cleanup_(sd_event_source_unrefp) sd_event_source *timeout_source = NULL, *retry_source = NULL;
408 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
409 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
410 int r;
411
412 assert(parent);
413 assert(pp);
414 assert(ret);
415
416 r = find_partition(parent, pp, timestamp_not_before, flags, ret);
417 if (r != -ENXIO)
418 return r;
419
420 r = sd_event_new(&event);
421 if (r < 0)
422 return r;
423
424 r = sd_device_monitor_new(&monitor);
425 if (r < 0)
426 return r;
427
428 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "block", "partition");
429 if (r < 0)
430 return r;
431
432 r = sd_device_monitor_filter_add_match_parent(monitor, parent, true);
433 if (r < 0)
434 return r;
435
436 r = sd_device_monitor_filter_add_match_sysattr(monitor, "partition", NULL, true);
437 if (r < 0)
438 return r;
439
440 r = sd_device_monitor_attach_event(monitor, event);
441 if (r < 0)
442 return r;
443
444 _cleanup_(wait_data_done) struct wait_data w = {
445 .parent_device = parent,
446 .blkidp = pp,
447 .diskseq = diskseq,
448 .uevent_seqnum_not_before = uevent_seqnum_not_before,
449 .timestamp_not_before = timestamp_not_before,
450 .flags = flags,
451 };
452
453 r = sd_device_monitor_start(monitor, device_monitor_handler, &w);
454 if (r < 0)
455 return r;
456
457 /* Check again, the partition might have appeared in the meantime */
458 r = find_partition(parent, pp, timestamp_not_before, flags, ret);
459 if (r != -ENXIO)
460 return r;
461
462 if (deadline != USEC_INFINITY) {
463 r = sd_event_add_time(
464 event, &timeout_source,
465 CLOCK_MONOTONIC, deadline, 0,
466 timeout_handler, &w);
467 if (r < 0)
468 return r;
469
470 r = sd_event_source_set_exit_on_failure(timeout_source, true);
471 if (r < 0)
472 return r;
473 }
474
475 /* If we don't have a disk sequence number then we cannot do exact matching,
476 * and we cannot know if we missed it or if it has not been sent yet, so set
477 * up additional retries to increase the chances of receiving the event. */
478 if (diskseq == 0) {
479 r = sd_event_add_time_relative(
480 event, &retry_source,
481 CLOCK_MONOTONIC, 500 * USEC_PER_MSEC, 0,
482 retry_handler, &w);
483 if (r < 0)
484 return r;
485
486 r = sd_event_source_set_exit_on_failure(retry_source, true);
487 if (r < 0)
488 return r;
489 }
490
491 r = sd_event_loop(event);
492 if (r < 0)
493 return r;
494
495 assert(w.found);
496 *ret = TAKE_PTR(w.found);
497 return 0;
498 }
499
500 static void check_partition_flags(
501 const char *node,
502 unsigned long long pflags,
503 unsigned long long supported) {
504
505 assert(node);
506
507 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
508 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
509
510 if (pflags == 0)
511 return;
512
513 /* If there are other bits set, then log about it, to make things discoverable */
514 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
515 unsigned long long bit = 1ULL << i;
516 if (!FLAGS_SET(pflags, bit))
517 continue;
518
519 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
520 }
521 }
522
523 static int device_wait_for_initialization_harder(
524 sd_device *device,
525 const char *subsystem,
526 usec_t deadline,
527 sd_device **ret) {
528
529 usec_t start, left, retrigger_timeout;
530 int r;
531
532 start = now(CLOCK_MONOTONIC);
533 left = usec_sub_unsigned(deadline, start);
534
535 if (DEBUG_LOGGING) {
536 const char *sn = NULL;
537
538 (void) sd_device_get_sysname(device, &sn);
539 log_device_debug(device,
540 "Waiting for device '%s' to initialize for %s.", strna(sn), FORMAT_TIMESPAN(left, 0));
541 }
542
543 if (left != USEC_INFINITY)
544 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 */
545 else
546 retrigger_timeout = 2 * USEC_PER_SEC;
547
548 for (;;) {
549 usec_t local_deadline, n;
550 bool last_try;
551
552 n = now(CLOCK_MONOTONIC);
553 assert(n >= start);
554
555 /* Find next deadline, when we'll retrigger */
556 local_deadline = start +
557 DIV_ROUND_UP(n - start, retrigger_timeout) * retrigger_timeout;
558
559 if (deadline != USEC_INFINITY && deadline <= local_deadline) {
560 local_deadline = deadline;
561 last_try = true;
562 } else
563 last_try = false;
564
565 r = device_wait_for_initialization(device, subsystem, local_deadline, ret);
566 if (r >= 0 && DEBUG_LOGGING) {
567 const char *sn = NULL;
568
569 (void) sd_device_get_sysname(device, &sn);
570 log_device_debug(device,
571 "Successfully waited for device '%s' to initialize for %s.",
572 strna(sn),
573 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
574
575 }
576 if (r != -ETIMEDOUT || last_try)
577 return r;
578
579 if (DEBUG_LOGGING)
580 log_device_debug(device,
581 "Device didn't initialize within %s, assuming lost event. Retriggering device.",
582 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
583
584 r = sd_device_trigger(device, SD_DEVICE_CHANGE);
585 if (r < 0)
586 return r;
587 }
588 }
589 #endif
590
591 #define DEVICE_TIMEOUT_USEC (45 * USEC_PER_SEC)
592
593 static void dissected_partition_done(DissectedPartition *p) {
594 assert(p);
595
596 free(p->fstype);
597 free(p->node);
598 free(p->label);
599 free(p->decrypted_fstype);
600 free(p->decrypted_node);
601 free(p->mount_options);
602
603 *p = (DissectedPartition) {
604 .partno = -1,
605 .architecture = -1
606 };
607 }
608
609 int dissect_image(
610 int fd,
611 const VeritySettings *verity,
612 const MountOptions *mount_options,
613 uint64_t diskseq,
614 uint64_t uevent_seqnum_not_before,
615 usec_t timestamp_not_before,
616 DissectImageFlags flags,
617 DissectedImage **ret) {
618
619 #if HAVE_BLKID
620 #ifdef GPT_ROOT_NATIVE
621 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL;
622 #endif
623 #ifdef GPT_USR_NATIVE
624 sd_id128_t usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
625 #endif
626 bool is_gpt, is_mbr, multiple_generic = false,
627 generic_rw = false, /* initialize to appease gcc */
628 generic_growfs = false;
629 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
630 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
631 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
632 _cleanup_free_ char *generic_node = NULL;
633 sd_id128_t generic_uuid = SD_ID128_NULL;
634 const char *pttype = NULL, *sysname = NULL;
635 blkid_partlist pl;
636 int r, generic_nr = -1, n_partitions;
637 struct stat st;
638 usec_t deadline;
639
640 assert(fd >= 0);
641 assert(ret);
642 assert(!verity || verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
643 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
644 assert(!verity || verity->root_hash_sig || verity->root_hash_sig_size == 0);
645 assert(!verity || (verity->root_hash || !verity->root_hash_sig));
646 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
647
648 /* Probes a disk image, and returns information about what it found in *ret.
649 *
650 * Returns -ENOPKG if no suitable partition table or file system could be found.
651 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
652 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
653 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that */
654
655 if (verity && verity->root_hash) {
656 sd_id128_t fsuuid, vuuid;
657
658 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
659 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
660 * the final 128bit. */
661
662 if (verity->root_hash_size < sizeof(sd_id128_t))
663 return -EINVAL;
664
665 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
666 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
667
668 if (sd_id128_is_null(fsuuid))
669 return -EINVAL;
670 if (sd_id128_is_null(vuuid))
671 return -EINVAL;
672
673 /* If the verity data declares it's for the /usr partition, then search for that, in all
674 * other cases assume it's for the root partition. */
675 #ifdef GPT_USR_NATIVE
676 if (verity->designator == PARTITION_USR) {
677 usr_uuid = fsuuid;
678 usr_verity_uuid = vuuid;
679 } else {
680 #endif
681 #ifdef GPT_ROOT_NATIVE
682 root_uuid = fsuuid;
683 root_verity_uuid = vuuid;
684 #endif
685 #ifdef GPT_USR_NATIVE
686 }
687 #endif
688 }
689
690 if (fstat(fd, &st) < 0)
691 return -errno;
692
693 if (!S_ISBLK(st.st_mode))
694 return -ENOTBLK;
695
696 r = sd_device_new_from_stat_rdev(&d, &st);
697 if (r < 0)
698 return r;
699
700 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
701 _cleanup_(sd_device_unrefp) sd_device *initialized = NULL;
702
703 /* If udev support is enabled, then let's wait for the device to be initialized before we doing anything. */
704
705 r = device_wait_for_initialization_harder(
706 d,
707 "block",
708 usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC),
709 &initialized);
710 if (r < 0)
711 return r;
712
713 sd_device_unref(d);
714 d = TAKE_PTR(initialized);
715 }
716
717 b = blkid_new_probe();
718 if (!b)
719 return -ENOMEM;
720
721 errno = 0;
722 r = blkid_probe_set_device(b, fd, 0, 0);
723 if (r != 0)
724 return errno_or_else(ENOMEM);
725
726 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
727 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
728 blkid_probe_enable_superblocks(b, 1);
729 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
730 }
731
732 blkid_probe_enable_partitions(b, 1);
733 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
734
735 errno = 0;
736 r = blkid_do_safeprobe(b);
737 if (IN_SET(r, -2, 1))
738 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
739 if (r != 0)
740 return errno_or_else(EIO);
741
742 m = new0(DissectedImage, 1);
743 if (!m)
744 return -ENOMEM;
745
746 r = sd_device_get_sysname(d, &sysname);
747 if (r < 0)
748 return log_debug_errno(r, "Failed to get device sysname: %m");
749 if (startswith(sysname, "loop")) {
750 _cleanup_free_ char *name_stripped = NULL;
751 const char *full_path;
752
753 r = sd_device_get_sysattr_value(d, "loop/backing_file", &full_path);
754 if (r < 0)
755 log_debug_errno(r, "Failed to lookup image name via loop device backing file sysattr, ignoring: %m");
756 else {
757 r = raw_strip_suffixes(basename(full_path), &name_stripped);
758 if (r < 0)
759 return r;
760 }
761
762 free_and_replace(m->image_name, name_stripped);
763 } else {
764 r = free_and_strdup(&m->image_name, sysname);
765 if (r < 0)
766 return r;
767 }
768
769 if (!image_name_is_valid(m->image_name)) {
770 log_debug("Image name %s is not valid, ignoring", strempty(m->image_name));
771 m->image_name = mfree(m->image_name);
772 }
773
774 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
775 (flags & DISSECT_IMAGE_GENERIC_ROOT)) ||
776 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
777 const char *usage = NULL;
778
779 /* If flags permit this, also allow using non-partitioned single-filesystem images */
780
781 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
782 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
783 const char *fstype = NULL, *options = NULL, *devname = NULL;
784 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
785
786 /* OK, we have found a file system, that's our root partition then. */
787 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
788
789 if (fstype) {
790 t = strdup(fstype);
791 if (!t)
792 return -ENOMEM;
793 }
794
795 r = sd_device_get_devname(d, &devname);
796 if (r < 0)
797 return r;
798
799 n = strdup(devname);
800 if (!n)
801 return -ENOMEM;
802
803 m->single_file_system = true;
804 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
805
806 m->has_verity = verity && verity->data_path;
807 m->verity_ready = m->has_verity &&
808 verity->root_hash &&
809 (verity->designator < 0 || verity->designator == PARTITION_ROOT);
810
811 m->has_verity_sig = false; /* signature not embedded, must be specified */
812 m->verity_sig_ready = m->verity_ready &&
813 verity->root_hash_sig;
814
815 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
816 if (options) {
817 o = strdup(options);
818 if (!o)
819 return -ENOMEM;
820 }
821
822 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
823 .found = true,
824 .rw = !m->verity_ready && !fstype_is_ro(fstype),
825 .partno = -1,
826 .architecture = _ARCHITECTURE_INVALID,
827 .fstype = TAKE_PTR(t),
828 .node = TAKE_PTR(n),
829 .mount_options = TAKE_PTR(o),
830 .offset = 0,
831 .size = UINT64_MAX,
832 };
833
834 *ret = TAKE_PTR(m);
835 return 0;
836 }
837 }
838
839 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
840 if (!pttype)
841 return -ENOPKG;
842
843 is_gpt = streq_ptr(pttype, "gpt");
844 is_mbr = streq_ptr(pttype, "dos");
845
846 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
847 return -ENOPKG;
848
849 /* We support external verity data partitions only if the image has no partition table */
850 if (verity && verity->data_path)
851 return -EBADR;
852
853 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
854 * do partition scanning. */
855 r = blockdev_partscan_enabled(fd);
856 if (r < 0)
857 return r;
858 if (r == 0)
859 return -EPROTONOSUPPORT;
860
861 errno = 0;
862 pl = blkid_probe_get_partitions(b);
863 if (!pl)
864 return errno_or_else(ENOMEM);
865
866 errno = 0;
867 n_partitions = blkid_partlist_numof_partitions(pl);
868 if (n_partitions < 0)
869 return errno_or_else(EIO);
870
871 deadline = usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC);
872 for (int i = 0; i < n_partitions; i++) {
873 _cleanup_(sd_device_unrefp) sd_device *q = NULL;
874 unsigned long long pflags;
875 blkid_loff_t start, size;
876 blkid_partition pp;
877 const char *node;
878 int nr;
879
880 errno = 0;
881 pp = blkid_partlist_get_partition(pl, i);
882 if (!pp)
883 return errno_or_else(EIO);
884
885 r = wait_for_partition_device(d, pp, deadline, diskseq, uevent_seqnum_not_before, timestamp_not_before, flags, &q);
886 if (r < 0)
887 return r;
888
889 r = sd_device_get_devname(q, &node);
890 if (r < 0)
891 return r;
892
893 pflags = blkid_partition_get_flags(pp);
894
895 errno = 0;
896 nr = blkid_partition_get_partno(pp);
897 if (nr < 0)
898 return errno_or_else(EIO);
899
900 errno = 0;
901 start = blkid_partition_get_start(pp);
902 if (start < 0)
903 return errno_or_else(EIO);
904
905 assert((uint64_t) start < UINT64_MAX/512);
906
907 errno = 0;
908 size = blkid_partition_get_size(pp);
909 if (size < 0)
910 return errno_or_else(EIO);
911
912 assert((uint64_t) size < UINT64_MAX/512);
913
914 if (is_gpt) {
915 PartitionDesignator designator = _PARTITION_DESIGNATOR_INVALID;
916 int architecture = _ARCHITECTURE_INVALID;
917 const char *stype, *sid, *fstype = NULL, *label;
918 sd_id128_t type_id, id;
919 bool rw = true, growfs = false;
920
921 sid = blkid_partition_get_uuid(pp);
922 if (!sid)
923 continue;
924 if (sd_id128_from_string(sid, &id) < 0)
925 continue;
926
927 stype = blkid_partition_get_type_string(pp);
928 if (!stype)
929 continue;
930 if (sd_id128_from_string(stype, &type_id) < 0)
931 continue;
932
933 label = blkid_partition_get_name(pp); /* libblkid returns NULL here if empty */
934
935 if (sd_id128_equal(type_id, GPT_HOME)) {
936
937 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
938
939 if (pflags & GPT_FLAG_NO_AUTO)
940 continue;
941
942 designator = PARTITION_HOME;
943 rw = !(pflags & GPT_FLAG_READ_ONLY);
944 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
945
946 } else if (sd_id128_equal(type_id, GPT_SRV)) {
947
948 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
949
950 if (pflags & GPT_FLAG_NO_AUTO)
951 continue;
952
953 designator = PARTITION_SRV;
954 rw = !(pflags & GPT_FLAG_READ_ONLY);
955 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
956
957 } else if (sd_id128_equal(type_id, GPT_ESP)) {
958
959 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is
960 * not defined there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
961 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
962 * Partitions"). */
963
964 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
965 continue;
966
967 designator = PARTITION_ESP;
968 fstype = "vfat";
969
970 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
971
972 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
973
974 if (pflags & GPT_FLAG_NO_AUTO)
975 continue;
976
977 designator = PARTITION_XBOOTLDR;
978 rw = !(pflags & GPT_FLAG_READ_ONLY);
979 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
980 }
981 #ifdef GPT_ROOT_NATIVE
982 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
983
984 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
985
986 if (pflags & GPT_FLAG_NO_AUTO)
987 continue;
988
989 /* If a root ID is specified, ignore everything but the root id */
990 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
991 continue;
992
993 designator = PARTITION_ROOT;
994 architecture = native_architecture();
995 rw = !(pflags & GPT_FLAG_READ_ONLY);
996 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
997
998 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
999
1000 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1001
1002 if (pflags & GPT_FLAG_NO_AUTO)
1003 continue;
1004
1005 m->has_verity = true;
1006
1007 /* If no verity configuration is specified, then don't do verity */
1008 if (!verity)
1009 continue;
1010 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1011 continue;
1012
1013 /* If root hash is specified, then ignore everything but the root id */
1014 if (!sd_id128_is_null(root_verity_uuid) && !sd_id128_equal(root_verity_uuid, id))
1015 continue;
1016
1017 designator = PARTITION_ROOT_VERITY;
1018 fstype = "DM_verity_hash";
1019 architecture = native_architecture();
1020 rw = false;
1021
1022 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY_SIG)) {
1023
1024 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1025
1026 if (pflags & GPT_FLAG_NO_AUTO)
1027 continue;
1028
1029 m->has_verity_sig = true;
1030
1031 /* If root hash is specified explicitly, then ignore any embedded signature */
1032 if (!verity)
1033 continue;
1034 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1035 continue;
1036 if (verity->root_hash)
1037 continue;
1038
1039 designator = PARTITION_ROOT_VERITY_SIG;
1040 fstype = "verity_hash_signature";
1041 architecture = native_architecture();
1042 rw = false;
1043 }
1044 #endif
1045 #ifdef GPT_ROOT_SECONDARY
1046 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
1047
1048 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1049
1050 if (pflags & GPT_FLAG_NO_AUTO)
1051 continue;
1052
1053 /* If a root ID is specified, ignore everything but the root id */
1054 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
1055 continue;
1056
1057 designator = PARTITION_ROOT_SECONDARY;
1058 architecture = SECONDARY_ARCHITECTURE;
1059 rw = !(pflags & GPT_FLAG_READ_ONLY);
1060 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1061
1062 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
1063
1064 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1065
1066 if (pflags & GPT_FLAG_NO_AUTO)
1067 continue;
1068
1069 m->has_verity = true;
1070
1071 /* Don't do verity if no verity config is passed in */
1072 if (!verity)
1073 continue;
1074 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1075 continue;
1076
1077 /* If root hash is specified, then ignore everything but the root id */
1078 if (!sd_id128_is_null(root_verity_uuid) && !sd_id128_equal(root_verity_uuid, id))
1079 continue;
1080
1081 designator = PARTITION_ROOT_SECONDARY_VERITY;
1082 fstype = "DM_verity_hash";
1083 architecture = SECONDARY_ARCHITECTURE;
1084 rw = false;
1085
1086 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY_SIG)) {
1087
1088 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1089
1090 if (pflags & GPT_FLAG_NO_AUTO)
1091 continue;
1092
1093 m->has_verity_sig = true;
1094
1095 /* If root hash is specified explicitly, then ignore any embedded signature */
1096 if (!verity)
1097 continue;
1098 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1099 continue;
1100 if (verity->root_hash)
1101 continue;
1102
1103 designator = PARTITION_ROOT_SECONDARY_VERITY_SIG;
1104 fstype = "verity_hash_signature";
1105 architecture = native_architecture();
1106 rw = false;
1107 }
1108 #endif
1109 #ifdef GPT_USR_NATIVE
1110 else if (sd_id128_equal(type_id, GPT_USR_NATIVE)) {
1111
1112 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1113
1114 if (pflags & GPT_FLAG_NO_AUTO)
1115 continue;
1116
1117 /* If a usr ID is specified, ignore everything but the usr id */
1118 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1119 continue;
1120
1121 designator = PARTITION_USR;
1122 architecture = native_architecture();
1123 rw = !(pflags & GPT_FLAG_READ_ONLY);
1124 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1125
1126 } else if (sd_id128_equal(type_id, GPT_USR_NATIVE_VERITY)) {
1127
1128 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1129
1130 if (pflags & GPT_FLAG_NO_AUTO)
1131 continue;
1132
1133 m->has_verity = true;
1134
1135 if (!verity)
1136 continue;
1137 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1138 continue;
1139
1140 /* If usr hash is specified, then ignore everything but the usr id */
1141 if (!sd_id128_is_null(usr_verity_uuid) && !sd_id128_equal(usr_verity_uuid, id))
1142 continue;
1143
1144 designator = PARTITION_USR_VERITY;
1145 fstype = "DM_verity_hash";
1146 architecture = native_architecture();
1147 rw = false;
1148
1149 } else if (sd_id128_equal(type_id, GPT_USR_NATIVE_VERITY_SIG)) {
1150
1151 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1152
1153 if (pflags & GPT_FLAG_NO_AUTO)
1154 continue;
1155
1156 m->has_verity_sig = true;
1157
1158 /* If usr hash is specified explicitly, then ignore any embedded signature */
1159 if (!verity)
1160 continue;
1161 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1162 continue;
1163 if (verity->root_hash)
1164 continue;
1165
1166 designator = PARTITION_USR_VERITY_SIG;
1167 fstype = "verity_hash_signature";
1168 architecture = native_architecture();
1169 rw = false;
1170 }
1171 #endif
1172 #ifdef GPT_USR_SECONDARY
1173 else if (sd_id128_equal(type_id, GPT_USR_SECONDARY)) {
1174
1175 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1176
1177 if (pflags & GPT_FLAG_NO_AUTO)
1178 continue;
1179
1180 /* If a usr ID is specified, ignore everything but the usr id */
1181 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1182 continue;
1183
1184 designator = PARTITION_USR_SECONDARY;
1185 architecture = SECONDARY_ARCHITECTURE;
1186 rw = !(pflags & GPT_FLAG_READ_ONLY);
1187 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1188
1189 } else if (sd_id128_equal(type_id, GPT_USR_SECONDARY_VERITY)) {
1190
1191 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1192
1193 if (pflags & GPT_FLAG_NO_AUTO)
1194 continue;
1195
1196 m->has_verity = true;
1197
1198 if (!verity)
1199 continue;
1200 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1201 continue;
1202
1203 /* If usr hash is specified, then ignore everything but the root id */
1204 if (!sd_id128_is_null(usr_verity_uuid) && !sd_id128_equal(usr_verity_uuid, id))
1205 continue;
1206
1207 designator = PARTITION_USR_SECONDARY_VERITY;
1208 fstype = "DM_verity_hash";
1209 architecture = SECONDARY_ARCHITECTURE;
1210 rw = false;
1211
1212 } else if (sd_id128_equal(type_id, GPT_USR_SECONDARY_VERITY_SIG)) {
1213
1214 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1215
1216 if (pflags & GPT_FLAG_NO_AUTO)
1217 continue;
1218
1219 m->has_verity_sig = true;
1220
1221 /* If usr hash is specified explicitly, then ignore any embedded signature */
1222 if (!verity)
1223 continue;
1224 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1225 continue;
1226 if (verity->root_hash)
1227 continue;
1228
1229 designator = PARTITION_USR_SECONDARY_VERITY_SIG;
1230 fstype = "verity_hash_signature";
1231 architecture = native_architecture();
1232 rw = false;
1233 }
1234 #endif
1235 else if (sd_id128_equal(type_id, GPT_SWAP)) {
1236
1237 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
1238
1239 if (pflags & GPT_FLAG_NO_AUTO)
1240 continue;
1241
1242 designator = PARTITION_SWAP;
1243
1244 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
1245
1246 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1247
1248 if (pflags & GPT_FLAG_NO_AUTO)
1249 continue;
1250
1251 if (generic_node)
1252 multiple_generic = true;
1253 else {
1254 generic_nr = nr;
1255 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
1256 generic_growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1257 generic_uuid = id;
1258 generic_node = strdup(node);
1259 if (!generic_node)
1260 return -ENOMEM;
1261 }
1262
1263 } else if (sd_id128_equal(type_id, GPT_TMP)) {
1264
1265 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1266
1267 if (pflags & GPT_FLAG_NO_AUTO)
1268 continue;
1269
1270 designator = PARTITION_TMP;
1271 rw = !(pflags & GPT_FLAG_READ_ONLY);
1272 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1273
1274 } else if (sd_id128_equal(type_id, GPT_VAR)) {
1275
1276 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1277
1278 if (pflags & GPT_FLAG_NO_AUTO)
1279 continue;
1280
1281 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
1282 sd_id128_t var_uuid;
1283
1284 /* For /var we insist that the uuid of the partition matches the
1285 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1286 * ID. Why? Unlike the other partitions /var is inherently
1287 * installation specific, hence we need to be careful not to mount it
1288 * in the wrong installation. By hashing the partition UUID from
1289 * /etc/machine-id we can securely bind the partition to the
1290 * installation. */
1291
1292 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
1293 if (r < 0)
1294 return r;
1295
1296 if (!sd_id128_equal(var_uuid, id)) {
1297 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
1298 continue;
1299 }
1300 }
1301
1302 designator = PARTITION_VAR;
1303 rw = !(pflags & GPT_FLAG_READ_ONLY);
1304 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1305 }
1306
1307 if (designator != _PARTITION_DESIGNATOR_INVALID) {
1308 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL, *l = NULL;
1309 const char *options = NULL;
1310
1311 if (m->partitions[designator].found) {
1312 /* For most partition types the first one we see wins. Except for the
1313 * rootfs and /usr, where we do a version compare of the label, and
1314 * let the newest version win. This permits a simple A/B versioning
1315 * scheme in OS images. */
1316
1317 if (!PARTITION_DESIGNATOR_VERSIONED(designator) ||
1318 strverscmp_improved(m->partitions[designator].label, label) >= 0)
1319 continue;
1320
1321 dissected_partition_done(m->partitions + designator);
1322 }
1323
1324 if (fstype) {
1325 t = strdup(fstype);
1326 if (!t)
1327 return -ENOMEM;
1328 }
1329
1330 n = strdup(node);
1331 if (!n)
1332 return -ENOMEM;
1333
1334 if (label) {
1335 l = strdup(label);
1336 if (!l)
1337 return -ENOMEM;
1338 }
1339
1340 options = mount_options_from_designator(mount_options, designator);
1341 if (options) {
1342 o = strdup(options);
1343 if (!o)
1344 return -ENOMEM;
1345 }
1346
1347 m->partitions[designator] = (DissectedPartition) {
1348 .found = true,
1349 .partno = nr,
1350 .rw = rw,
1351 .growfs = growfs,
1352 .architecture = architecture,
1353 .node = TAKE_PTR(n),
1354 .fstype = TAKE_PTR(t),
1355 .label = TAKE_PTR(l),
1356 .uuid = id,
1357 .mount_options = TAKE_PTR(o),
1358 .offset = (uint64_t) start * 512,
1359 .size = (uint64_t) size * 512,
1360 };
1361 }
1362
1363 } else if (is_mbr) {
1364
1365 switch (blkid_partition_get_type(pp)) {
1366
1367 case 0x83: /* Linux partition */
1368
1369 if (pflags != 0x80) /* Bootable flag */
1370 continue;
1371
1372 if (generic_node)
1373 multiple_generic = true;
1374 else {
1375 generic_nr = nr;
1376 generic_rw = true;
1377 generic_growfs = false;
1378 generic_node = strdup(node);
1379 if (!generic_node)
1380 return -ENOMEM;
1381 }
1382
1383 break;
1384
1385 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1386 _cleanup_free_ char *n = NULL, *o = NULL;
1387 sd_id128_t id = SD_ID128_NULL;
1388 const char *sid, *options = NULL;
1389
1390 /* First one wins */
1391 if (m->partitions[PARTITION_XBOOTLDR].found)
1392 continue;
1393
1394 sid = blkid_partition_get_uuid(pp);
1395 if (sid)
1396 (void) sd_id128_from_string(sid, &id);
1397
1398 n = strdup(node);
1399 if (!n)
1400 return -ENOMEM;
1401
1402 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
1403 if (options) {
1404 o = strdup(options);
1405 if (!o)
1406 return -ENOMEM;
1407 }
1408
1409 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1410 .found = true,
1411 .partno = nr,
1412 .rw = true,
1413 .growfs = false,
1414 .architecture = _ARCHITECTURE_INVALID,
1415 .node = TAKE_PTR(n),
1416 .uuid = id,
1417 .mount_options = TAKE_PTR(o),
1418 .offset = (uint64_t) start * 512,
1419 .size = (uint64_t) size * 512,
1420 };
1421
1422 break;
1423 }}
1424 }
1425 }
1426
1427 if (m->partitions[PARTITION_ROOT].found) {
1428 /* If we found the primary arch, then invalidate the secondary arch to avoid any ambiguities,
1429 * since we never want to mount the secondary arch in this case. */
1430 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
1431 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
1432 m->partitions[PARTITION_ROOT_SECONDARY_VERITY_SIG].found = false;
1433 m->partitions[PARTITION_USR_SECONDARY].found = false;
1434 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
1435 m->partitions[PARTITION_USR_SECONDARY_VERITY_SIG].found = false;
1436
1437 } else if (m->partitions[PARTITION_ROOT_VERITY].found ||
1438 m->partitions[PARTITION_ROOT_VERITY_SIG].found)
1439 return -EADDRNOTAVAIL; /* Verity found but no matching rootfs? Something is off, refuse. */
1440
1441 else if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
1442
1443 /* No root partition found but there's one for the secondary architecture? Then upgrade
1444 * secondary arch to first */
1445
1446 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
1447 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
1448 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
1449 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
1450 m->partitions[PARTITION_ROOT_VERITY_SIG] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY_SIG];
1451 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY_SIG]);
1452
1453 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1454 zero(m->partitions[PARTITION_USR_SECONDARY]);
1455 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1456 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
1457 m->partitions[PARTITION_USR_VERITY_SIG] = m->partitions[PARTITION_USR_SECONDARY_VERITY_SIG];
1458 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY_SIG]);
1459
1460 } else if (m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found ||
1461 m->partitions[PARTITION_ROOT_SECONDARY_VERITY_SIG].found)
1462 return -EADDRNOTAVAIL; /* as above */
1463
1464 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1465 if (m->partitions[PARTITION_ROOT_VERITY_SIG].found && !m->partitions[PARTITION_ROOT_VERITY].found)
1466 return -EADDRNOTAVAIL;
1467
1468 if (m->partitions[PARTITION_USR].found) {
1469 /* Invalidate secondary arch /usr/ if we found the primary arch */
1470 m->partitions[PARTITION_USR_SECONDARY].found = false;
1471 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
1472 m->partitions[PARTITION_USR_SECONDARY_VERITY_SIG].found = false;
1473
1474 } else if (m->partitions[PARTITION_USR_VERITY].found ||
1475 m->partitions[PARTITION_USR_VERITY_SIG].found)
1476 return -EADDRNOTAVAIL; /* as above */
1477
1478 else if (m->partitions[PARTITION_USR_SECONDARY].found) {
1479
1480 /* Upgrade secondary arch to primary */
1481 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1482 zero(m->partitions[PARTITION_USR_SECONDARY]);
1483 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1484 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
1485 m->partitions[PARTITION_USR_VERITY_SIG] = m->partitions[PARTITION_USR_SECONDARY_VERITY_SIG];
1486 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY_SIG]);
1487
1488 } else if (m->partitions[PARTITION_USR_SECONDARY_VERITY].found ||
1489 m->partitions[PARTITION_USR_SECONDARY_VERITY_SIG].found)
1490 return -EADDRNOTAVAIL; /* as above */
1491
1492 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1493 if (m->partitions[PARTITION_USR_VERITY_SIG].found && !m->partitions[PARTITION_USR_VERITY].found)
1494 return -EADDRNOTAVAIL;
1495
1496 /* If root and /usr are combined then insist that the architecture matches */
1497 if (m->partitions[PARTITION_ROOT].found &&
1498 m->partitions[PARTITION_USR].found &&
1499 (m->partitions[PARTITION_ROOT].architecture >= 0 &&
1500 m->partitions[PARTITION_USR].architecture >= 0 &&
1501 m->partitions[PARTITION_ROOT].architecture != m->partitions[PARTITION_USR].architecture))
1502 return -EADDRNOTAVAIL;
1503
1504 if (!m->partitions[PARTITION_ROOT].found &&
1505 !m->partitions[PARTITION_USR].found &&
1506 (flags & DISSECT_IMAGE_GENERIC_ROOT) &&
1507 (!verity || !verity->root_hash || verity->designator != PARTITION_USR)) {
1508
1509 /* OK, we found nothing usable, then check if there's a single generic one distro, and use
1510 * that. If the root hash was set however, then we won't fall back to a generic node, because
1511 * the root hash decides. */
1512
1513 /* If we didn't find a properly marked root partition, but we did find a single suitable
1514 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1515 if (multiple_generic)
1516 return -ENOTUNIQ;
1517
1518 /* If we didn't find a generic node, then we can't fix this up either */
1519 if (generic_node) {
1520 _cleanup_free_ char *o = NULL;
1521 const char *options;
1522
1523 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
1524 if (options) {
1525 o = strdup(options);
1526 if (!o)
1527 return -ENOMEM;
1528 }
1529
1530 assert(generic_nr >= 0);
1531 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1532 .found = true,
1533 .rw = generic_rw,
1534 .growfs = generic_growfs,
1535 .partno = generic_nr,
1536 .architecture = _ARCHITECTURE_INVALID,
1537 .node = TAKE_PTR(generic_node),
1538 .uuid = generic_uuid,
1539 .mount_options = TAKE_PTR(o),
1540 .offset = UINT64_MAX,
1541 .size = UINT64_MAX,
1542 };
1543 }
1544 }
1545
1546 /* Check if we have a root fs if we are told to do check. /usr alone is fine too, but only if appropriate flag for that is set too */
1547 if (FLAGS_SET(flags, DISSECT_IMAGE_REQUIRE_ROOT) &&
1548 !(m->partitions[PARTITION_ROOT].found || (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1549 return -ENXIO;
1550
1551 if (m->partitions[PARTITION_ROOT_VERITY].found) {
1552 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1553 if (m->partitions[PARTITION_USR_VERITY].found)
1554 return -ENOTUNIQ;
1555
1556 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1557 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1558 if (m->partitions[PARTITION_USR].found)
1559 return -EADDRNOTAVAIL;
1560 }
1561
1562 if (verity) {
1563 /* If a verity designator is specified, then insist that the matching partition exists */
1564 if (verity->designator >= 0 && !m->partitions[verity->designator].found)
1565 return -EADDRNOTAVAIL;
1566
1567 if (verity->root_hash) {
1568 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1569 * Verity, set things up for it */
1570
1571 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1572 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1573 return -EADDRNOTAVAIL;
1574
1575 /* If we found a verity setup, then the root partition is necessarily read-only. */
1576 m->partitions[PARTITION_ROOT].rw = false;
1577 m->verity_ready = true;
1578
1579 } else {
1580 assert(verity->designator == PARTITION_USR);
1581
1582 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1583 return -EADDRNOTAVAIL;
1584
1585 m->partitions[PARTITION_USR].rw = false;
1586 m->verity_ready = true;
1587 }
1588
1589 if (m->verity_ready)
1590 m->verity_sig_ready = !!verity->root_hash_sig;
1591
1592 } else if (m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR_VERITY_SIG : PARTITION_ROOT_VERITY_SIG].found) {
1593
1594 /* If we found an embedded signature partition, we are ready, too. */
1595
1596 m->verity_ready = m->verity_sig_ready = true;
1597 m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR : PARTITION_ROOT].rw = false;
1598 }
1599 }
1600
1601 blkid_free_probe(b);
1602 b = NULL;
1603
1604 /* Fill in file system types if we don't know them yet. */
1605 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1606 DissectedPartition *p = m->partitions + i;
1607
1608 if (!p->found)
1609 continue;
1610
1611 if (!p->fstype && p->node) {
1612 r = probe_filesystem(p->node, &p->fstype);
1613 if (r < 0 && r != -EUCLEAN)
1614 return r;
1615 }
1616
1617 if (streq_ptr(p->fstype, "crypto_LUKS"))
1618 m->encrypted = true;
1619
1620 if (p->fstype && fstype_is_ro(p->fstype))
1621 p->rw = false;
1622
1623 if (!p->rw)
1624 p->growfs = false;
1625 }
1626
1627 *ret = TAKE_PTR(m);
1628 return 0;
1629 #else
1630 return -EOPNOTSUPP;
1631 #endif
1632 }
1633
1634 DissectedImage* dissected_image_unref(DissectedImage *m) {
1635 if (!m)
1636 return NULL;
1637
1638 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
1639 dissected_partition_done(m->partitions + i);
1640
1641 free(m->image_name);
1642 free(m->hostname);
1643 strv_free(m->machine_info);
1644 strv_free(m->os_release);
1645 strv_free(m->extension_release);
1646
1647 return mfree(m);
1648 }
1649
1650 static int is_loop_device(const char *path) {
1651 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
1652 struct stat st;
1653
1654 assert(path);
1655
1656 if (stat(path, &st) < 0)
1657 return -errno;
1658
1659 if (!S_ISBLK(st.st_mode))
1660 return -ENOTBLK;
1661
1662 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
1663 if (access(s, F_OK) < 0) {
1664 if (errno != ENOENT)
1665 return -errno;
1666
1667 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1668 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
1669 if (access(s, F_OK) < 0)
1670 return errno == ENOENT ? false : -errno;
1671 }
1672
1673 return true;
1674 }
1675
1676 static int run_fsck(const char *node, const char *fstype) {
1677 int r, exit_status;
1678 pid_t pid;
1679
1680 assert(node);
1681 assert(fstype);
1682
1683 r = fsck_exists(fstype);
1684 if (r < 0) {
1685 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1686 return 0;
1687 }
1688 if (r == 0) {
1689 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
1690 return 0;
1691 }
1692
1693 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
1694 if (r < 0)
1695 return log_debug_errno(r, "Failed to fork off fsck: %m");
1696 if (r == 0) {
1697 /* Child */
1698 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
1699 log_open();
1700 log_debug_errno(errno, "Failed to execl() fsck: %m");
1701 _exit(FSCK_OPERATIONAL_ERROR);
1702 }
1703
1704 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1705 if (exit_status < 0)
1706 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1707
1708 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1709 log_debug("fsck failed with exit status %i.", exit_status);
1710
1711 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1712 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1713
1714 log_debug("Ignoring fsck error.");
1715 }
1716
1717 return 0;
1718 }
1719
1720 static int fs_grow(const char *node_path, const char *mount_path) {
1721 _cleanup_close_ int mount_fd = -1, node_fd = -1;
1722 uint64_t size, newsize;
1723 int r;
1724
1725 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1726 if (node_fd < 0)
1727 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
1728
1729 if (ioctl(node_fd, BLKGETSIZE64, &size) != 0)
1730 return log_debug_errno(errno, "Failed to get block device size of %s: %m", node_path);
1731
1732 mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1733 if (mount_fd < 0)
1734 return log_debug_errno(errno, "Failed to open mountd file system %s: %m", mount_path);
1735
1736 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", mount_path, size);
1737 r = resize_fs(mount_fd, size, &newsize);
1738 if (r < 0)
1739 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", mount_path, size);
1740
1741 if (newsize == size)
1742 log_debug("Successfully resized \"%s\" to %s bytes.",
1743 mount_path, FORMAT_BYTES(newsize));
1744 else {
1745 assert(newsize < size);
1746 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
1747 mount_path, FORMAT_BYTES(newsize), size - newsize);
1748 }
1749
1750 return 0;
1751 }
1752
1753 static int mount_partition(
1754 DissectedPartition *m,
1755 const char *where,
1756 const char *directory,
1757 uid_t uid_shift,
1758 uid_t uid_range,
1759 DissectImageFlags flags) {
1760
1761 _cleanup_free_ char *chased = NULL, *options = NULL;
1762 const char *p, *node, *fstype;
1763 bool rw, remap_uid_gid = false;
1764 int r;
1765
1766 assert(m);
1767 assert(where);
1768
1769 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1770 node = m->decrypted_node ?: m->node;
1771 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
1772
1773 if (!m->found || !node)
1774 return 0;
1775 if (!fstype)
1776 return -EAFNOSUPPORT;
1777
1778 /* 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. */
1779 if (streq(fstype, "crypto_LUKS"))
1780 return -EUNATCH;
1781
1782 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
1783
1784 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1785 r = run_fsck(node, fstype);
1786 if (r < 0)
1787 return r;
1788 }
1789
1790 if (directory) {
1791 /* Automatically create missing mount points inside the image, if necessary. */
1792 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1793 if (r < 0 && r != -EROFS)
1794 return r;
1795
1796 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
1797 if (r < 0)
1798 return r;
1799
1800 p = chased;
1801 } else {
1802 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1803 * image (as the branch above does) but the host hierarchy, and the created directory might
1804 * survive our mount in the host hierarchy hence. */
1805 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1806 r = mkdir_p(where, 0755);
1807 if (r < 0)
1808 return r;
1809 }
1810
1811 p = where;
1812 }
1813
1814 /* If requested, turn on discard support. */
1815 if (fstype_can_discard(fstype) &&
1816 ((flags & DISSECT_IMAGE_DISCARD) ||
1817 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
1818 options = strdup("discard");
1819 if (!options)
1820 return -ENOMEM;
1821 }
1822
1823 if (uid_is_valid(uid_shift) && uid_shift != 0) {
1824
1825 if (fstype_can_uid_gid(fstype)) {
1826 _cleanup_free_ char *uid_option = NULL;
1827
1828 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1829 return -ENOMEM;
1830
1831 if (!strextend_with_separator(&options, ",", uid_option))
1832 return -ENOMEM;
1833 } else if (FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED))
1834 remap_uid_gid = true;
1835 }
1836
1837 if (!isempty(m->mount_options))
1838 if (!strextend_with_separator(&options, ",", m->mount_options))
1839 return -ENOMEM;
1840
1841 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1842 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1843 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1844 * from the upper file system still get propagated through to the underlying file system,
1845 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1846 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1847 * carry a per file system table here.
1848 *
1849 * Note that this means that we might not be able to mount corrupted file systems as read-only
1850 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1851 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1852 * mount options for loopback devices this is the right choice, since otherwise using the same
1853 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1854 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1855 * access that actually modifies stuff work on such image files. Or to say this differently: if
1856 * people want their file systems to be fixed up they should just open them in writable mode, where
1857 * all these problems don't exist. */
1858 if (!rw && STRPTR_IN_SET(fstype, "ext3", "ext4", "xfs", "btrfs"))
1859 if (!strextend_with_separator(&options, ",", "norecovery"))
1860 return -ENOMEM;
1861
1862 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
1863 if (r < 0)
1864 return r;
1865
1866 if (rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS))
1867 (void) fs_grow(node, p);
1868
1869 if (remap_uid_gid) {
1870 r = remount_idmap(p, uid_shift, uid_range);
1871 if (r < 0)
1872 return r;
1873 }
1874
1875 return 1;
1876 }
1877
1878 static int mount_root_tmpfs(const char *where, uid_t uid_shift, DissectImageFlags flags) {
1879 _cleanup_free_ char *options = NULL;
1880 int r;
1881
1882 assert(where);
1883
1884 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1885
1886 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1887 r = mkdir_p(where, 0755);
1888 if (r < 0)
1889 return r;
1890 }
1891
1892 if (uid_is_valid(uid_shift)) {
1893 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1894 return -ENOMEM;
1895 }
1896
1897 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
1898 if (r < 0)
1899 return r;
1900
1901 return 1;
1902 }
1903
1904 int dissected_image_mount(
1905 DissectedImage *m,
1906 const char *where,
1907 uid_t uid_shift,
1908 uid_t uid_range,
1909 DissectImageFlags flags) {
1910
1911 int r, xbootldr_mounted;
1912
1913 assert(m);
1914 assert(where);
1915
1916 /* Returns:
1917 *
1918 * -ENXIO → No root partition found
1919 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1920 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1921 * -EUCLEAN → fsck for file system failed
1922 * -EBUSY → File system already mounted/used elsewhere (kernel)
1923 * -EAFNOSUPPORT → File system type not supported or not known
1924 */
1925
1926 if (!(m->partitions[PARTITION_ROOT].found ||
1927 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1928 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
1929
1930 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1931
1932 /* First mount the root fs. If there's none we use a tmpfs. */
1933 if (m->partitions[PARTITION_ROOT].found)
1934 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, flags);
1935 else
1936 r = mount_root_tmpfs(where, uid_shift, flags);
1937 if (r < 0)
1938 return r;
1939
1940 /* For us mounting root always means mounting /usr as well */
1941 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, flags);
1942 if (r < 0)
1943 return r;
1944
1945 if ((flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
1946 /* If either one of the validation flags are set, ensure that the image qualifies
1947 * as one or the other (or both). */
1948 bool ok = false;
1949
1950 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
1951 r = path_is_os_tree(where);
1952 if (r < 0)
1953 return r;
1954 if (r > 0)
1955 ok = true;
1956 }
1957 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT)) {
1958 r = path_is_extension_tree(where, m->image_name);
1959 if (r < 0)
1960 return r;
1961 if (r > 0)
1962 ok = true;
1963 }
1964
1965 if (!ok)
1966 return -ENOMEDIUM;
1967 }
1968 }
1969
1970 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
1971 return 0;
1972
1973 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, flags);
1974 if (r < 0)
1975 return r;
1976
1977 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, flags);
1978 if (r < 0)
1979 return r;
1980
1981 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, flags);
1982 if (r < 0)
1983 return r;
1984
1985 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, flags);
1986 if (r < 0)
1987 return r;
1988
1989 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, flags);
1990 if (xbootldr_mounted < 0)
1991 return xbootldr_mounted;
1992
1993 if (m->partitions[PARTITION_ESP].found) {
1994 int esp_done = false;
1995
1996 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1997 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1998
1999 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
2000 if (r < 0) {
2001 if (r != -ENOENT)
2002 return r;
2003
2004 /* /efi doesn't exist. Let's see if /boot is suitable then */
2005
2006 if (!xbootldr_mounted) {
2007 _cleanup_free_ char *p = NULL;
2008
2009 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
2010 if (r < 0) {
2011 if (r != -ENOENT)
2012 return r;
2013 } else if (dir_is_empty(p) > 0) {
2014 /* It exists and is an empty directory. Let's mount the ESP there. */
2015 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, uid_range, flags);
2016 if (r < 0)
2017 return r;
2018
2019 esp_done = true;
2020 }
2021 }
2022 }
2023
2024 if (!esp_done) {
2025 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
2026
2027 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, uid_range, flags);
2028 if (r < 0)
2029 return r;
2030 }
2031 }
2032
2033 return 0;
2034 }
2035
2036 int dissected_image_mount_and_warn(
2037 DissectedImage *m,
2038 const char *where,
2039 uid_t uid_shift,
2040 uid_t uid_range,
2041 DissectImageFlags flags) {
2042
2043 int r;
2044
2045 assert(m);
2046 assert(where);
2047
2048 r = dissected_image_mount(m, where, uid_shift, uid_range, flags);
2049 if (r == -ENXIO)
2050 return log_error_errno(r, "Not root file system found in image.");
2051 if (r == -EMEDIUMTYPE)
2052 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
2053 if (r == -EUNATCH)
2054 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
2055 if (r == -EUCLEAN)
2056 return log_error_errno(r, "File system check on image failed.");
2057 if (r == -EBUSY)
2058 return log_error_errno(r, "File system already mounted elsewhere.");
2059 if (r == -EAFNOSUPPORT)
2060 return log_error_errno(r, "File system type not supported or not known.");
2061 if (r < 0)
2062 return log_error_errno(r, "Failed to mount image: %m");
2063
2064 return r;
2065 }
2066
2067 #if HAVE_LIBCRYPTSETUP
2068 typedef struct DecryptedPartition {
2069 struct crypt_device *device;
2070 char *name;
2071 bool relinquished;
2072 } DecryptedPartition;
2073
2074 struct DecryptedImage {
2075 DecryptedPartition *decrypted;
2076 size_t n_decrypted;
2077 };
2078 #endif
2079
2080 DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
2081 #if HAVE_LIBCRYPTSETUP
2082 int r;
2083
2084 if (!d)
2085 return NULL;
2086
2087 for (size_t i = 0; i < d->n_decrypted; i++) {
2088 DecryptedPartition *p = d->decrypted + i;
2089
2090 if (p->device && p->name && !p->relinquished) {
2091 r = sym_crypt_deactivate_by_name(p->device, p->name, 0);
2092 if (r < 0)
2093 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
2094 }
2095
2096 if (p->device)
2097 sym_crypt_free(p->device);
2098 free(p->name);
2099 }
2100
2101 free(d->decrypted);
2102 free(d);
2103 #endif
2104 return NULL;
2105 }
2106
2107 #if HAVE_LIBCRYPTSETUP
2108
2109 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
2110 _cleanup_free_ char *name = NULL, *node = NULL;
2111 const char *base;
2112
2113 assert(original_node);
2114 assert(suffix);
2115 assert(ret_name);
2116 assert(ret_node);
2117
2118 base = strrchr(original_node, '/');
2119 if (!base)
2120 base = original_node;
2121 else
2122 base++;
2123 if (isempty(base))
2124 return -EINVAL;
2125
2126 name = strjoin(base, suffix);
2127 if (!name)
2128 return -ENOMEM;
2129 if (!filename_is_valid(name))
2130 return -EINVAL;
2131
2132 node = path_join(sym_crypt_get_dir(), name);
2133 if (!node)
2134 return -ENOMEM;
2135
2136 *ret_name = TAKE_PTR(name);
2137 *ret_node = TAKE_PTR(node);
2138
2139 return 0;
2140 }
2141
2142 static int decrypt_partition(
2143 DissectedPartition *m,
2144 const char *passphrase,
2145 DissectImageFlags flags,
2146 DecryptedImage *d) {
2147
2148 _cleanup_free_ char *node = NULL, *name = NULL;
2149 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2150 int r;
2151
2152 assert(m);
2153 assert(d);
2154
2155 if (!m->found || !m->node || !m->fstype)
2156 return 0;
2157
2158 if (!streq(m->fstype, "crypto_LUKS"))
2159 return 0;
2160
2161 if (!passphrase)
2162 return -ENOKEY;
2163
2164 r = dlopen_cryptsetup();
2165 if (r < 0)
2166 return r;
2167
2168 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
2169 if (r < 0)
2170 return r;
2171
2172 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2173 return -ENOMEM;
2174
2175 r = sym_crypt_init(&cd, m->node);
2176 if (r < 0)
2177 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
2178
2179 cryptsetup_enable_logging(cd);
2180
2181 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
2182 if (r < 0)
2183 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
2184
2185 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
2186 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
2187 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
2188 if (r < 0) {
2189 log_debug_errno(r, "Failed to activate LUKS device: %m");
2190 return r == -EPERM ? -EKEYREJECTED : r;
2191 }
2192
2193 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2194 .name = TAKE_PTR(name),
2195 .device = TAKE_PTR(cd),
2196 };
2197
2198 m->decrypted_node = TAKE_PTR(node);
2199
2200 return 0;
2201 }
2202
2203 static int verity_can_reuse(
2204 const VeritySettings *verity,
2205 const char *name,
2206 struct crypt_device **ret_cd) {
2207
2208 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2209 _cleanup_free_ char *root_hash_existing = NULL;
2210 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2211 struct crypt_params_verity crypt_params = {};
2212 size_t root_hash_existing_size;
2213 int r;
2214
2215 assert(verity);
2216 assert(name);
2217 assert(ret_cd);
2218
2219 r = sym_crypt_init_by_name(&cd, name);
2220 if (r < 0)
2221 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
2222
2223 cryptsetup_enable_logging(cd);
2224
2225 r = sym_crypt_get_verity_info(cd, &crypt_params);
2226 if (r < 0)
2227 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
2228
2229 root_hash_existing_size = verity->root_hash_size;
2230 root_hash_existing = malloc0(root_hash_existing_size);
2231 if (!root_hash_existing)
2232 return -ENOMEM;
2233
2234 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
2235 if (r < 0)
2236 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
2237 if (verity->root_hash_size != root_hash_existing_size ||
2238 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
2239 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
2240
2241 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2242 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2243 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2244 * signing for the new one, and vice versa. */
2245 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
2246 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
2247 #endif
2248
2249 *ret_cd = TAKE_PTR(cd);
2250 return 0;
2251 }
2252
2253 static inline char* dm_deferred_remove_clean(char *name) {
2254 if (!name)
2255 return NULL;
2256
2257 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
2258 return mfree(name);
2259 }
2260 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
2261
2262 static int verity_partition(
2263 PartitionDesignator designator,
2264 DissectedPartition *m,
2265 DissectedPartition *v,
2266 const VeritySettings *verity,
2267 DissectImageFlags flags,
2268 DecryptedImage *d) {
2269
2270 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2271 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
2272 _cleanup_free_ char *node = NULL, *name = NULL;
2273 int r;
2274
2275 assert(m);
2276 assert(v || (verity && verity->data_path));
2277
2278 if (!verity || !verity->root_hash)
2279 return 0;
2280 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2281 (verity->designator == designator)))
2282 return 0;
2283
2284 if (!m->found || !m->node || !m->fstype)
2285 return 0;
2286 if (!verity->data_path) {
2287 if (!v->found || !v->node || !v->fstype)
2288 return 0;
2289
2290 if (!streq(v->fstype, "DM_verity_hash"))
2291 return 0;
2292 }
2293
2294 r = dlopen_cryptsetup();
2295 if (r < 0)
2296 return r;
2297
2298 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2299 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2300 _cleanup_free_ char *root_hash_encoded = NULL;
2301
2302 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
2303 if (!root_hash_encoded)
2304 return -ENOMEM;
2305
2306 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2307 } else
2308 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
2309 if (r < 0)
2310 return r;
2311
2312 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
2313 if (r < 0)
2314 return r;
2315
2316 cryptsetup_enable_logging(cd);
2317
2318 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
2319 if (r < 0)
2320 return r;
2321
2322 r = sym_crypt_set_data_device(cd, m->node);
2323 if (r < 0)
2324 return r;
2325
2326 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2327 return -ENOMEM;
2328
2329 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2330 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2331 * retry a few times before giving up. */
2332 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
2333 if (verity->root_hash_sig) {
2334 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2335 r = sym_crypt_activate_by_signed_key(
2336 cd,
2337 name,
2338 verity->root_hash,
2339 verity->root_hash_size,
2340 verity->root_hash_sig,
2341 verity->root_hash_sig_size,
2342 CRYPT_ACTIVATE_READONLY);
2343 #else
2344 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2345 "Activation of verity device with signature requested, but not supported by %s due to missing crypt_activate_by_signed_key().", program_invocation_short_name);
2346 #endif
2347 } else
2348 r = sym_crypt_activate_by_volume_key(
2349 cd,
2350 name,
2351 verity->root_hash,
2352 verity->root_hash_size,
2353 CRYPT_ACTIVATE_READONLY);
2354 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2355 * There's no way to distinguish this situation from a genuine error due to invalid
2356 * parameters, so immediately fall back to activating the device with a unique name.
2357 * Improvements in libcrypsetup can ensure this never happens:
2358 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2359 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2360 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2361 if (!IN_SET(r,
2362 0, /* Success */
2363 -EEXIST, /* Volume is already open and ready to be used */
2364 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
2365 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
2366 return r;
2367 if (IN_SET(r, -EEXIST, -EBUSY)) {
2368 struct crypt_device *existing_cd = NULL;
2369
2370 if (!restore_deferred_remove){
2371 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2372 r = dm_deferred_remove_cancel(name);
2373 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
2374 if (r < 0 && r != -ENXIO)
2375 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
2376 if (r == 0) {
2377 restore_deferred_remove = strdup(name);
2378 if (!restore_deferred_remove)
2379 return -ENOMEM;
2380 }
2381 }
2382
2383 r = verity_can_reuse(verity, name, &existing_cd);
2384 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2385 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2386 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2387 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
2388 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
2389 if (r == 0) {
2390 /* devmapper might say that the device exists, but the devlink might not yet have been
2391 * created. Check and wait for the udev event in that case. */
2392 r = device_wait_for_devlink(node, "block", usec_add(now(CLOCK_MONOTONIC), 100 * USEC_PER_MSEC), NULL);
2393 /* Fallback to activation with a unique device if it's taking too long */
2394 if (r == -ETIMEDOUT)
2395 break;
2396 if (r < 0)
2397 return r;
2398
2399 if (cd)
2400 sym_crypt_free(cd);
2401 cd = existing_cd;
2402 }
2403 }
2404 if (r == 0)
2405 break;
2406
2407 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
2408 (void) usleep(2 * USEC_PER_MSEC);
2409 }
2410
2411 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
2412 * Fall back to activating it with a unique device name. */
2413 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2414 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2415
2416 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2417 restore_deferred_remove = mfree(restore_deferred_remove);
2418
2419 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2420 .name = TAKE_PTR(name),
2421 .device = TAKE_PTR(cd),
2422 };
2423
2424 m->decrypted_node = TAKE_PTR(node);
2425
2426 return 0;
2427 }
2428 #endif
2429
2430 int dissected_image_decrypt(
2431 DissectedImage *m,
2432 const char *passphrase,
2433 const VeritySettings *verity,
2434 DissectImageFlags flags,
2435 DecryptedImage **ret) {
2436
2437 #if HAVE_LIBCRYPTSETUP
2438 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2439 int r;
2440 #endif
2441
2442 assert(m);
2443 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
2444
2445 /* Returns:
2446 *
2447 * = 0 → There was nothing to decrypt
2448 * > 0 → Decrypted successfully
2449 * -ENOKEY → There's something to decrypt but no key was supplied
2450 * -EKEYREJECTED → Passed key was not correct
2451 */
2452
2453 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
2454 return -EINVAL;
2455
2456 if (!m->encrypted && !m->verity_ready) {
2457 *ret = NULL;
2458 return 0;
2459 }
2460
2461 #if HAVE_LIBCRYPTSETUP
2462 d = new0(DecryptedImage, 1);
2463 if (!d)
2464 return -ENOMEM;
2465
2466 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
2467 DissectedPartition *p = m->partitions + i;
2468 PartitionDesignator k;
2469
2470 if (!p->found)
2471 continue;
2472
2473 r = decrypt_partition(p, passphrase, flags, d);
2474 if (r < 0)
2475 return r;
2476
2477 k = PARTITION_VERITY_OF(i);
2478 if (k >= 0) {
2479 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
2480 if (r < 0)
2481 return r;
2482 }
2483
2484 if (!p->decrypted_fstype && p->decrypted_node) {
2485 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
2486 if (r < 0 && r != -EUCLEAN)
2487 return r;
2488 }
2489 }
2490
2491 *ret = TAKE_PTR(d);
2492
2493 return 1;
2494 #else
2495 return -EOPNOTSUPP;
2496 #endif
2497 }
2498
2499 int dissected_image_decrypt_interactively(
2500 DissectedImage *m,
2501 const char *passphrase,
2502 const VeritySettings *verity,
2503 DissectImageFlags flags,
2504 DecryptedImage **ret) {
2505
2506 _cleanup_strv_free_erase_ char **z = NULL;
2507 int n = 3, r;
2508
2509 if (passphrase)
2510 n--;
2511
2512 for (;;) {
2513 r = dissected_image_decrypt(m, passphrase, verity, flags, ret);
2514 if (r >= 0)
2515 return r;
2516 if (r == -EKEYREJECTED)
2517 log_error_errno(r, "Incorrect passphrase, try again!");
2518 else if (r != -ENOKEY)
2519 return log_error_errno(r, "Failed to decrypt image: %m");
2520
2521 if (--n < 0)
2522 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
2523 "Too many retries.");
2524
2525 z = strv_free(z);
2526
2527 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY, 0, &z);
2528 if (r < 0)
2529 return log_error_errno(r, "Failed to query for passphrase: %m");
2530
2531 passphrase = z[0];
2532 }
2533 }
2534
2535 int decrypted_image_relinquish(DecryptedImage *d) {
2536 assert(d);
2537
2538 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2539 * boolean so that we don't clean it up ourselves either anymore */
2540
2541 #if HAVE_LIBCRYPTSETUP
2542 int r;
2543
2544 for (size_t i = 0; i < d->n_decrypted; i++) {
2545 DecryptedPartition *p = d->decrypted + i;
2546
2547 if (p->relinquished)
2548 continue;
2549
2550 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
2551 if (r < 0)
2552 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
2553
2554 p->relinquished = true;
2555 }
2556 #endif
2557
2558 return 0;
2559 }
2560
2561 static char *build_auxiliary_path(const char *image, const char *suffix) {
2562 const char *e;
2563 char *n;
2564
2565 assert(image);
2566 assert(suffix);
2567
2568 e = endswith(image, ".raw");
2569 if (!e)
2570 return strjoin(e, suffix);
2571
2572 n = new(char, e - image + strlen(suffix) + 1);
2573 if (!n)
2574 return NULL;
2575
2576 strcpy(mempcpy(n, image, e - image), suffix);
2577 return n;
2578 }
2579
2580 void verity_settings_done(VeritySettings *v) {
2581 assert(v);
2582
2583 v->root_hash = mfree(v->root_hash);
2584 v->root_hash_size = 0;
2585
2586 v->root_hash_sig = mfree(v->root_hash_sig);
2587 v->root_hash_sig_size = 0;
2588
2589 v->data_path = mfree(v->data_path);
2590 }
2591
2592 int verity_settings_load(
2593 VeritySettings *verity,
2594 const char *image,
2595 const char *root_hash_path,
2596 const char *root_hash_sig_path) {
2597
2598 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2599 size_t root_hash_size = 0, root_hash_sig_size = 0;
2600 _cleanup_free_ char *verity_data_path = NULL;
2601 PartitionDesignator designator;
2602 int r;
2603
2604 assert(verity);
2605 assert(image);
2606 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
2607
2608 /* If we are asked to load the root hash for a device node, exit early */
2609 if (is_device_path(image))
2610 return 0;
2611
2612 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2613 if (r < 0 && r != -ENXIO)
2614 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2615 if (r == 0)
2616 return 0;
2617
2618 designator = verity->designator;
2619
2620 /* We only fill in what isn't already filled in */
2621
2622 if (!verity->root_hash) {
2623 _cleanup_free_ char *text = NULL;
2624
2625 if (root_hash_path) {
2626 /* If explicitly specified it takes precedence */
2627 r = read_one_line_file(root_hash_path, &text);
2628 if (r < 0)
2629 return r;
2630
2631 if (designator < 0)
2632 designator = PARTITION_ROOT;
2633 } else {
2634 /* Otherwise look for xattr and separate file, and first for the data for root and if
2635 * that doesn't exist for /usr */
2636
2637 if (designator < 0 || designator == PARTITION_ROOT) {
2638 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
2639 if (r < 0) {
2640 _cleanup_free_ char *p = NULL;
2641
2642 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2643 return r;
2644
2645 p = build_auxiliary_path(image, ".roothash");
2646 if (!p)
2647 return -ENOMEM;
2648
2649 r = read_one_line_file(p, &text);
2650 if (r < 0 && r != -ENOENT)
2651 return r;
2652 }
2653
2654 if (text)
2655 designator = PARTITION_ROOT;
2656 }
2657
2658 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2659 /* So in the "roothash" xattr/file name above the "root" of course primarily
2660 * refers to the root of the Verity Merkle tree. But coincidentally it also
2661 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2662 * two distinct concepts called "root". Taking benefit of this happy
2663 * coincidence we call the file with the root hash for the /usr/ file system
2664 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2665 * confusing. We thus drop the reference to the root of the Merkle tree, and
2666 * just indicate which file system it's about. */
2667 r = getxattr_malloc(image, "user.verity.usrhash", &text, true);
2668 if (r < 0) {
2669 _cleanup_free_ char *p = NULL;
2670
2671 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2672 return r;
2673
2674 p = build_auxiliary_path(image, ".usrhash");
2675 if (!p)
2676 return -ENOMEM;
2677
2678 r = read_one_line_file(p, &text);
2679 if (r < 0 && r != -ENOENT)
2680 return r;
2681 }
2682
2683 if (text)
2684 designator = PARTITION_USR;
2685 }
2686 }
2687
2688 if (text) {
2689 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
2690 if (r < 0)
2691 return r;
2692 if (root_hash_size < sizeof(sd_id128_t))
2693 return -EINVAL;
2694 }
2695 }
2696
2697 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
2698 if (root_hash_sig_path) {
2699 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
2700 if (r < 0 && r != -ENOENT)
2701 return r;
2702
2703 if (designator < 0)
2704 designator = PARTITION_ROOT;
2705 } else {
2706 if (designator < 0 || designator == PARTITION_ROOT) {
2707 _cleanup_free_ char *p = NULL;
2708
2709 /* Follow naming convention recommended by the relevant RFC:
2710 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2711 p = build_auxiliary_path(image, ".roothash.p7s");
2712 if (!p)
2713 return -ENOMEM;
2714
2715 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
2716 if (r < 0 && r != -ENOENT)
2717 return r;
2718 if (r >= 0)
2719 designator = PARTITION_ROOT;
2720 }
2721
2722 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2723 _cleanup_free_ char *p = NULL;
2724
2725 p = build_auxiliary_path(image, ".usrhash.p7s");
2726 if (!p)
2727 return -ENOMEM;
2728
2729 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
2730 if (r < 0 && r != -ENOENT)
2731 return r;
2732 if (r >= 0)
2733 designator = PARTITION_USR;
2734 }
2735 }
2736
2737 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
2738 return -EINVAL;
2739 }
2740
2741 if (!verity->data_path) {
2742 _cleanup_free_ char *p = NULL;
2743
2744 p = build_auxiliary_path(image, ".verity");
2745 if (!p)
2746 return -ENOMEM;
2747
2748 if (access(p, F_OK) < 0) {
2749 if (errno != ENOENT)
2750 return -errno;
2751 } else
2752 verity_data_path = TAKE_PTR(p);
2753 }
2754
2755 if (root_hash) {
2756 verity->root_hash = TAKE_PTR(root_hash);
2757 verity->root_hash_size = root_hash_size;
2758 }
2759
2760 if (root_hash_sig) {
2761 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2762 verity->root_hash_sig_size = root_hash_sig_size;
2763 }
2764
2765 if (verity_data_path)
2766 verity->data_path = TAKE_PTR(verity_data_path);
2767
2768 if (verity->designator < 0)
2769 verity->designator = designator;
2770
2771 return 1;
2772 }
2773
2774 int dissected_image_load_verity_sig_partition(
2775 DissectedImage *m,
2776 int fd,
2777 VeritySettings *verity) {
2778
2779 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2780 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
2781 size_t root_hash_size, root_hash_sig_size;
2782 _cleanup_free_ char *buf = NULL;
2783 PartitionDesignator d;
2784 DissectedPartition *p;
2785 JsonVariant *rh, *sig;
2786 ssize_t n;
2787 char *e;
2788 int r;
2789
2790 assert(m);
2791 assert(fd >= 0);
2792 assert(verity);
2793
2794 if (verity->root_hash && verity->root_hash_sig) /* Already loaded? */
2795 return 0;
2796
2797 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
2798 if (r < 0 && r != -ENXIO)
2799 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
2800 if (r == 0)
2801 return 0;
2802
2803 d = PARTITION_VERITY_SIG_OF(verity->designator < 0 ? PARTITION_ROOT : verity->designator);
2804 assert(d >= 0);
2805
2806 p = m->partitions + d;
2807 if (!p->found)
2808 return 0;
2809 if (p->offset == UINT64_MAX || p->size == UINT64_MAX)
2810 return -EINVAL;
2811
2812 if (p->size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
2813 return -EFBIG;
2814
2815 buf = new(char, p->size+1);
2816 if (!buf)
2817 return -ENOMEM;
2818
2819 n = pread(fd, buf, p->size, p->offset);
2820 if (n < 0)
2821 return -ENOMEM;
2822 if ((uint64_t) n != p->size)
2823 return -EIO;
2824
2825 e = memchr(buf, 0, p->size);
2826 if (e) {
2827 /* If we found a NUL byte then the rest of the data must be NUL too */
2828 if (!memeqzero(e, p->size - (e - buf)))
2829 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
2830 } else
2831 buf[p->size] = 0;
2832
2833 r = json_parse(buf, 0, &v, NULL, NULL);
2834 if (r < 0)
2835 return log_debug_errno(r, "Failed to parse signature JSON data: %m");
2836
2837 rh = json_variant_by_key(v, "rootHash");
2838 if (!rh)
2839 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
2840 if (!json_variant_is_string(rh))
2841 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'rootHash' field of signature JSON object is not a string.");
2842
2843 r = unhexmem(json_variant_string(rh), SIZE_MAX, &root_hash, &root_hash_size);
2844 if (r < 0)
2845 return log_debug_errno(r, "Failed to parse root hash field: %m");
2846
2847 /* Check if specified root hash matches if it is specified */
2848 if (verity->root_hash &&
2849 memcmp_nn(verity->root_hash, verity->root_hash_size, root_hash, root_hash_size) != 0) {
2850 _cleanup_free_ char *a = NULL, *b = NULL;
2851
2852 a = hexmem(root_hash, root_hash_size);
2853 b = hexmem(verity->root_hash, verity->root_hash_size);
2854
2855 return log_debug_errno(r, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a), strna(b));
2856 }
2857
2858 sig = json_variant_by_key(v, "signature");
2859 if (!sig)
2860 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
2861 if (!json_variant_is_string(sig))
2862 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'signature' field of signature JSON object is not a string.");
2863
2864 r = unbase64mem(json_variant_string(sig), SIZE_MAX, &root_hash_sig, &root_hash_sig_size);
2865 if (r < 0)
2866 return log_debug_errno(r, "Failed to parse signature field: %m");
2867
2868 free_and_replace(verity->root_hash, root_hash);
2869 verity->root_hash_size = root_hash_size;
2870
2871 free_and_replace(verity->root_hash_sig, root_hash_sig);
2872 verity->root_hash_sig_size = root_hash_sig_size;
2873
2874 return 1;
2875 }
2876
2877 int dissected_image_acquire_metadata(DissectedImage *m) {
2878
2879 enum {
2880 META_HOSTNAME,
2881 META_MACHINE_ID,
2882 META_MACHINE_INFO,
2883 META_OS_RELEASE,
2884 META_EXTENSION_RELEASE,
2885 _META_MAX,
2886 };
2887
2888 static const char *const paths[_META_MAX] = {
2889 [META_HOSTNAME] = "/etc/hostname\0",
2890 [META_MACHINE_ID] = "/etc/machine-id\0",
2891 [META_MACHINE_INFO] = "/etc/machine-info\0",
2892 [META_OS_RELEASE] = ("/etc/os-release\0"
2893 "/usr/lib/os-release\0"),
2894 [META_EXTENSION_RELEASE] = "extension-release\0", /* Used only for logging. */
2895 };
2896
2897 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **extension_release = NULL;
2898 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
2899 _cleanup_(rmdir_and_freep) char *t = NULL;
2900 _cleanup_(sigkill_waitp) pid_t child = 0;
2901 sd_id128_t machine_id = SD_ID128_NULL;
2902 _cleanup_free_ char *hostname = NULL;
2903 unsigned n_meta_initialized = 0;
2904 int fds[2 * _META_MAX], r, v;
2905 ssize_t n;
2906
2907 BLOCK_SIGNALS(SIGCHLD);
2908
2909 assert(m);
2910
2911 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++) {
2912 if (!paths[n_meta_initialized]) {
2913 fds[2*n_meta_initialized] = fds[2*n_meta_initialized+1] = -1;
2914 continue;
2915 }
2916
2917 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2918 r = -errno;
2919 goto finish;
2920 }
2921 }
2922
2923 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2924 if (r < 0)
2925 goto finish;
2926
2927 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2928 r = -errno;
2929 goto finish;
2930 }
2931
2932 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
2933 if (r < 0)
2934 goto finish;
2935 if (r == 0) {
2936 error_pipe[0] = safe_close(error_pipe[0]);
2937
2938 r = dissected_image_mount(
2939 m,
2940 t,
2941 UID_INVALID,
2942 UID_INVALID,
2943 DISSECT_IMAGE_READ_ONLY|
2944 DISSECT_IMAGE_MOUNT_ROOT_ONLY|
2945 DISSECT_IMAGE_VALIDATE_OS|
2946 DISSECT_IMAGE_VALIDATE_OS_EXT|
2947 DISSECT_IMAGE_USR_NO_ROOT);
2948 if (r < 0) {
2949 /* Let parent know the error */
2950 (void) write(error_pipe[1], &r, sizeof(r));
2951
2952 log_debug_errno(r, "Failed to mount dissected image: %m");
2953 _exit(EXIT_FAILURE);
2954 }
2955
2956 for (unsigned k = 0; k < _META_MAX; k++) {
2957 _cleanup_close_ int fd = -ENOENT;
2958 const char *p;
2959
2960 if (!paths[k])
2961 continue;
2962
2963 fds[2*k] = safe_close(fds[2*k]);
2964
2965 if (k == META_EXTENSION_RELEASE) {
2966 /* As per the os-release spec, if the image is an extension it will have a file
2967 * named after the image name in extension-release.d/ - we use the image name
2968 * and try to resolve it with the extension-release helpers, as sometimes
2969 * the image names are mangled on deployment and do not match anymore.
2970 * Unlike other paths this is not fixed, and the image name
2971 * can be mangled on deployment, so by calling into the helper
2972 * we allow a fallback that matches on the first extension-release
2973 * file found in the directory, if one named after the image cannot
2974 * be found first. */
2975 r = open_extension_release(t, m->image_name, NULL, &fd);
2976 if (r < 0)
2977 fd = r; /* Propagate the error. */
2978 } else
2979 NULSTR_FOREACH(p, paths[k]) {
2980 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
2981 if (fd >= 0)
2982 break;
2983 }
2984 if (fd < 0) {
2985 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
2986 fds[2*k+1] = safe_close(fds[2*k+1]);
2987 continue;
2988 }
2989
2990 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
2991 if (r < 0) {
2992 (void) write(error_pipe[1], &r, sizeof(r));
2993 _exit(EXIT_FAILURE);
2994 }
2995
2996 fds[2*k+1] = safe_close(fds[2*k+1]);
2997 }
2998
2999 _exit(EXIT_SUCCESS);
3000 }
3001
3002 error_pipe[1] = safe_close(error_pipe[1]);
3003
3004 for (unsigned k = 0; k < _META_MAX; k++) {
3005 _cleanup_fclose_ FILE *f = NULL;
3006
3007 if (!paths[k])
3008 continue;
3009
3010 fds[2*k+1] = safe_close(fds[2*k+1]);
3011
3012 f = take_fdopen(&fds[2*k], "r");
3013 if (!f) {
3014 r = -errno;
3015 goto finish;
3016 }
3017
3018 switch (k) {
3019
3020 case META_HOSTNAME:
3021 r = read_etc_hostname_stream(f, &hostname);
3022 if (r < 0)
3023 log_debug_errno(r, "Failed to read /etc/hostname: %m");
3024
3025 break;
3026
3027 case META_MACHINE_ID: {
3028 _cleanup_free_ char *line = NULL;
3029
3030 r = read_line(f, LONG_LINE_MAX, &line);
3031 if (r < 0)
3032 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
3033 else if (r == 33) {
3034 r = sd_id128_from_string(line, &machine_id);
3035 if (r < 0)
3036 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
3037 } else if (r == 0)
3038 log_debug("/etc/machine-id file is empty.");
3039 else if (streq(line, "uninitialized"))
3040 log_debug("/etc/machine-id file is uninitialized (likely aborted first boot).");
3041 else
3042 log_debug("/etc/machine-id has unexpected length %i.", r);
3043
3044 break;
3045 }
3046
3047 case META_MACHINE_INFO:
3048 r = load_env_file_pairs(f, "machine-info", &machine_info);
3049 if (r < 0)
3050 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
3051
3052 break;
3053
3054 case META_OS_RELEASE:
3055 r = load_env_file_pairs(f, "os-release", &os_release);
3056 if (r < 0)
3057 log_debug_errno(r, "Failed to read OS release file: %m");
3058
3059 break;
3060
3061 case META_EXTENSION_RELEASE:
3062 r = load_env_file_pairs(f, "extension-release", &extension_release);
3063 if (r < 0)
3064 log_debug_errno(r, "Failed to read extension release file: %m");
3065
3066 break;
3067 }
3068 }
3069
3070 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3071 child = 0;
3072 if (r < 0)
3073 return r;
3074
3075 n = read(error_pipe[0], &v, sizeof(v));
3076 if (n < 0)
3077 return -errno;
3078 if (n == sizeof(v))
3079 return v; /* propagate error sent to us from child */
3080 if (n != 0)
3081 return -EIO;
3082
3083 if (r != EXIT_SUCCESS)
3084 return -EPROTO;
3085
3086 free_and_replace(m->hostname, hostname);
3087 m->machine_id = machine_id;
3088 strv_free_and_replace(m->machine_info, machine_info);
3089 strv_free_and_replace(m->os_release, os_release);
3090 strv_free_and_replace(m->extension_release, extension_release);
3091
3092 finish:
3093 for (unsigned k = 0; k < n_meta_initialized; k++)
3094 safe_close_pair(fds + 2*k);
3095
3096 return r;
3097 }
3098
3099 int dissect_image_and_warn(
3100 int fd,
3101 const char *name,
3102 const VeritySettings *verity,
3103 const MountOptions *mount_options,
3104 uint64_t diskseq,
3105 uint64_t uevent_seqnum_not_before,
3106 usec_t timestamp_not_before,
3107 DissectImageFlags flags,
3108 DissectedImage **ret) {
3109
3110 _cleanup_free_ char *buffer = NULL;
3111 int r;
3112
3113 if (!name) {
3114 r = fd_get_path(fd, &buffer);
3115 if (r < 0)
3116 return r;
3117
3118 name = buffer;
3119 }
3120
3121 r = dissect_image(fd, verity, mount_options, diskseq, uevent_seqnum_not_before, timestamp_not_before, flags, ret);
3122 switch (r) {
3123
3124 case -EOPNOTSUPP:
3125 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
3126
3127 case -ENOPKG:
3128 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
3129
3130 case -EADDRNOTAVAIL:
3131 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
3132
3133 case -ENOTUNIQ:
3134 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
3135
3136 case -ENXIO:
3137 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
3138
3139 case -EPROTONOSUPPORT:
3140 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
3141
3142 default:
3143 if (r < 0)
3144 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
3145
3146 return r;
3147 }
3148 }
3149
3150 bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
3151 assert(image);
3152
3153 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3154 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3155 * images we only check the partition type.
3156 *
3157 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3158 * image. */
3159
3160 if (image->single_file_system)
3161 return partition_designator == PARTITION_ROOT && image->has_verity;
3162
3163 return PARTITION_VERITY_OF(partition_designator) >= 0;
3164 }
3165
3166 bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3167 PartitionDesignator k;
3168
3169 assert(image);
3170
3171 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3172 * works for the root partition, for others only if the associated verity partition was found. */
3173
3174 if (!image->verity_ready)
3175 return false;
3176
3177 if (image->single_file_system)
3178 return partition_designator == PARTITION_ROOT;
3179
3180 k = PARTITION_VERITY_OF(partition_designator);
3181 return k >= 0 && image->partitions[k].found;
3182 }
3183
3184 bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3185 PartitionDesignator k;
3186
3187 assert(image);
3188
3189 /* Checks if this partition has verity signature data available that we can use. */
3190
3191 if (!image->verity_sig_ready)
3192 return false;
3193
3194 if (image->single_file_system)
3195 return partition_designator == PARTITION_ROOT;
3196
3197 k = PARTITION_VERITY_SIG_OF(partition_designator);
3198 return k >= 0 && image->partitions[k].found;
3199 }
3200
3201 MountOptions* mount_options_free_all(MountOptions *options) {
3202 MountOptions *m;
3203
3204 while ((m = options)) {
3205 LIST_REMOVE(mount_options, options, m);
3206 free(m->options);
3207 free(m);
3208 }
3209
3210 return NULL;
3211 }
3212
3213 const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
3214 const MountOptions *m;
3215
3216 LIST_FOREACH(mount_options, m, options)
3217 if (designator == m->partition_designator && !isempty(m->options))
3218 return m->options;
3219
3220 return NULL;
3221 }
3222
3223 int mount_image_privately_interactively(
3224 const char *image,
3225 DissectImageFlags flags,
3226 char **ret_directory,
3227 LoopDevice **ret_loop_device,
3228 DecryptedImage **ret_decrypted_image) {
3229
3230 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3231 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
3232 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
3233 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3234 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
3235 _cleanup_free_ char *temp = NULL;
3236 int r;
3237
3238 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3239 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3240 * easily. */
3241
3242 assert(image);
3243 assert(ret_directory);
3244 assert(ret_loop_device);
3245 assert(ret_decrypted_image);
3246
3247 r = verity_settings_load(&verity, image, NULL, NULL);
3248 if (r < 0)
3249 return log_error_errno(r, "Failed to load root hash data: %m");
3250
3251 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
3252 if (r < 0)
3253 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
3254
3255 r = loop_device_make_by_path(
3256 image,
3257 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
3258 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
3259 &d);
3260 if (r < 0)
3261 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
3262
3263 r = dissect_image_and_warn(d->fd, image, &verity, NULL, d->diskseq, d->uevent_seqnum_not_before, d->timestamp_not_before, flags, &dissected_image);
3264 if (r < 0)
3265 return r;
3266
3267 r = dissected_image_load_verity_sig_partition(dissected_image, d->fd, &verity);
3268 if (r < 0)
3269 return r;
3270
3271 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags, &decrypted_image);
3272 if (r < 0)
3273 return r;
3274
3275 r = detach_mount_namespace();
3276 if (r < 0)
3277 return log_error_errno(r, "Failed to detach mount namespace: %m");
3278
3279 r = mkdir_p(temp, 0700);
3280 if (r < 0)
3281 return log_error_errno(r, "Failed to create mount point: %m");
3282
3283 created_dir = TAKE_PTR(temp);
3284
3285 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, UID_INVALID, flags);
3286 if (r < 0)
3287 return r;
3288
3289 if (decrypted_image) {
3290 r = decrypted_image_relinquish(decrypted_image);
3291 if (r < 0)
3292 return log_error_errno(r, "Failed to relinquish DM devices: %m");
3293 }
3294
3295 loop_device_relinquish(d);
3296
3297 *ret_directory = TAKE_PTR(created_dir);
3298 *ret_loop_device = TAKE_PTR(d);
3299 *ret_decrypted_image = TAKE_PTR(decrypted_image);
3300
3301 return 0;
3302 }
3303
3304 static const char *const partition_designator_table[] = {
3305 [PARTITION_ROOT] = "root",
3306 [PARTITION_ROOT_SECONDARY] = "root-secondary",
3307 [PARTITION_USR] = "usr",
3308 [PARTITION_USR_SECONDARY] = "usr-secondary",
3309 [PARTITION_HOME] = "home",
3310 [PARTITION_SRV] = "srv",
3311 [PARTITION_ESP] = "esp",
3312 [PARTITION_XBOOTLDR] = "xbootldr",
3313 [PARTITION_SWAP] = "swap",
3314 [PARTITION_ROOT_VERITY] = "root-verity",
3315 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
3316 [PARTITION_USR_VERITY] = "usr-verity",
3317 [PARTITION_USR_SECONDARY_VERITY] = "usr-secondary-verity",
3318 [PARTITION_ROOT_VERITY_SIG] = "root-verity-sig",
3319 [PARTITION_ROOT_SECONDARY_VERITY_SIG] = "root-secondary-verity-sig",
3320 [PARTITION_USR_VERITY_SIG] = "usr-verity-sig",
3321 [PARTITION_USR_SECONDARY_VERITY_SIG] = "usr-secondary-verity-sig",
3322 [PARTITION_TMP] = "tmp",
3323 [PARTITION_VAR] = "var",
3324 };
3325
3326 int verity_dissect_and_mount(
3327 const char *src,
3328 const char *dest,
3329 const MountOptions *options,
3330 const char *required_host_os_release_id,
3331 const char *required_host_os_release_version_id,
3332 const char *required_host_os_release_sysext_level) {
3333
3334 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
3335 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
3336 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3337 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3338 DissectImageFlags dissect_image_flags;
3339 int r;
3340
3341 assert(src);
3342 assert(dest);
3343
3344 r = verity_settings_load(&verity, src, NULL, NULL);
3345 if (r < 0)
3346 return log_debug_errno(r, "Failed to load root hash: %m");
3347
3348 dissect_image_flags = verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0;
3349
3350 r = loop_device_make_by_path(
3351 src,
3352 -1,
3353 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
3354 &loop_device);
3355 if (r < 0)
3356 return log_debug_errno(r, "Failed to create loop device for image: %m");
3357
3358 r = dissect_image(
3359 loop_device->fd,
3360 &verity,
3361 options,
3362 loop_device->diskseq,
3363 loop_device->uevent_seqnum_not_before,
3364 loop_device->timestamp_not_before,
3365 dissect_image_flags,
3366 &dissected_image);
3367 /* No partition table? Might be a single-filesystem image, try again */
3368 if (!verity.data_path && r == -ENOPKG)
3369 r = dissect_image(
3370 loop_device->fd,
3371 &verity,
3372 options,
3373 loop_device->diskseq,
3374 loop_device->uevent_seqnum_not_before,
3375 loop_device->timestamp_not_before,
3376 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
3377 &dissected_image);
3378 if (r < 0)
3379 return log_debug_errno(r, "Failed to dissect image: %m");
3380
3381 r = dissected_image_load_verity_sig_partition(dissected_image, loop_device->fd, &verity);
3382 if (r < 0)
3383 return r;
3384
3385 r = dissected_image_decrypt(
3386 dissected_image,
3387 NULL,
3388 &verity,
3389 dissect_image_flags,
3390 &decrypted_image);
3391 if (r < 0)
3392 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
3393
3394 r = mkdir_p_label(dest, 0755);
3395 if (r < 0)
3396 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
3397 r = umount_recursive(dest, 0);
3398 if (r < 0)
3399 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
3400
3401 r = dissected_image_mount(dissected_image, dest, UID_INVALID, UID_INVALID, dissect_image_flags);
3402 if (r < 0)
3403 return log_debug_errno(r, "Failed to mount image: %m");
3404
3405 /* If we got os-release values from the caller, then we need to match them with the image's
3406 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3407 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3408 * available, or else fallback to VERSION_ID. */
3409 if (required_host_os_release_id &&
3410 (required_host_os_release_version_id || required_host_os_release_sysext_level)) {
3411 _cleanup_strv_free_ char **extension_release = NULL;
3412
3413 r = load_extension_release_pairs(dest, dissected_image->image_name, &extension_release);
3414 if (r < 0)
3415 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
3416
3417 r = extension_release_validate(
3418 dissected_image->image_name,
3419 required_host_os_release_id,
3420 required_host_os_release_version_id,
3421 required_host_os_release_sysext_level,
3422 extension_release);
3423 if (r == 0)
3424 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
3425 if (r < 0)
3426 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
3427 }
3428
3429 if (decrypted_image) {
3430 r = decrypted_image_relinquish(decrypted_image);
3431 if (r < 0)
3432 return log_debug_errno(r, "Failed to relinquish decrypted image: %m");
3433 }
3434
3435 loop_device_relinquish(loop_device);
3436
3437 return 0;
3438 }
3439
3440 DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);