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