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