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