]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
dissect-image: tighten assertion checks on verity data
[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,
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 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
843 * do partition scanning. */
844 r = blockdev_partscan_enabled(fd);
845 if (r < 0)
846 return r;
847 if (r == 0)
848 return -EPROTONOSUPPORT;
849
850 errno = 0;
851 pl = blkid_probe_get_partitions(b);
852 if (!pl)
853 return errno_or_else(ENOMEM);
854
855 errno = 0;
856 n_partitions = blkid_partlist_numof_partitions(pl);
857 if (n_partitions < 0)
858 return errno_or_else(EIO);
859
860 deadline = usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC);
861 for (int i = 0; i < n_partitions; i++) {
862 _cleanup_(sd_device_unrefp) sd_device *q = NULL;
863 unsigned long long pflags;
864 blkid_partition pp;
865 const char *node;
866 int nr;
867
868 errno = 0;
869 pp = blkid_partlist_get_partition(pl, i);
870 if (!pp)
871 return errno_or_else(EIO);
872
873 r = wait_for_partition_device(d, pp, deadline, diskseq, uevent_seqnum_not_before, timestamp_not_before, flags, &q);
874 if (r < 0)
875 return r;
876
877 r = sd_device_get_devname(q, &node);
878 if (r < 0)
879 return r;
880
881 pflags = blkid_partition_get_flags(pp);
882
883 errno = 0;
884 nr = blkid_partition_get_partno(pp);
885 if (nr < 0)
886 return errno_or_else(EIO);
887
888 if (is_gpt) {
889 PartitionDesignator designator = _PARTITION_DESIGNATOR_INVALID;
890 int architecture = _ARCHITECTURE_INVALID;
891 const char *stype, *sid, *fstype = NULL, *label;
892 sd_id128_t type_id, id;
893 bool rw = true, growfs = false;
894
895 sid = blkid_partition_get_uuid(pp);
896 if (!sid)
897 continue;
898 if (sd_id128_from_string(sid, &id) < 0)
899 continue;
900
901 stype = blkid_partition_get_type_string(pp);
902 if (!stype)
903 continue;
904 if (sd_id128_from_string(stype, &type_id) < 0)
905 continue;
906
907 label = blkid_partition_get_name(pp); /* libblkid returns NULL here if empty */
908
909 if (sd_id128_equal(type_id, GPT_HOME)) {
910
911 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
912
913 if (pflags & GPT_FLAG_NO_AUTO)
914 continue;
915
916 designator = PARTITION_HOME;
917 rw = !(pflags & GPT_FLAG_READ_ONLY);
918 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
919
920 } else if (sd_id128_equal(type_id, GPT_SRV)) {
921
922 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
923
924 if (pflags & GPT_FLAG_NO_AUTO)
925 continue;
926
927 designator = PARTITION_SRV;
928 rw = !(pflags & GPT_FLAG_READ_ONLY);
929 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
930
931 } else if (sd_id128_equal(type_id, GPT_ESP)) {
932
933 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is
934 * not defined there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
935 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
936 * Partitions"). */
937
938 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
939 continue;
940
941 designator = PARTITION_ESP;
942 fstype = "vfat";
943
944 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
945
946 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
947
948 if (pflags & GPT_FLAG_NO_AUTO)
949 continue;
950
951 designator = PARTITION_XBOOTLDR;
952 rw = !(pflags & GPT_FLAG_READ_ONLY);
953 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
954 }
955 #ifdef GPT_ROOT_NATIVE
956 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
957
958 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
959
960 if (pflags & GPT_FLAG_NO_AUTO)
961 continue;
962
963 /* If a root ID is specified, ignore everything but the root id */
964 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
965 continue;
966
967 designator = PARTITION_ROOT;
968 architecture = native_architecture();
969 rw = !(pflags & GPT_FLAG_READ_ONLY);
970 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
971
972 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
973
974 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
975
976 if (pflags & GPT_FLAG_NO_AUTO)
977 continue;
978
979 m->has_verity = true;
980
981 /* Ignore verity unless a root hash is specified */
982 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
983 continue;
984
985 designator = PARTITION_ROOT_VERITY;
986 fstype = "DM_verity_hash";
987 architecture = native_architecture();
988 rw = false;
989 }
990 #endif
991 #ifdef GPT_ROOT_SECONDARY
992 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
993
994 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
995
996 if (pflags & GPT_FLAG_NO_AUTO)
997 continue;
998
999 /* If a root ID is specified, ignore everything but the root id */
1000 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
1001 continue;
1002
1003 designator = PARTITION_ROOT_SECONDARY;
1004 architecture = SECONDARY_ARCHITECTURE;
1005 rw = !(pflags & GPT_FLAG_READ_ONLY);
1006 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1007
1008 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
1009
1010 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1011
1012 if (pflags & GPT_FLAG_NO_AUTO)
1013 continue;
1014
1015 m->has_verity = true;
1016
1017 /* Ignore verity unless root has is specified */
1018 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
1019 continue;
1020
1021 designator = PARTITION_ROOT_SECONDARY_VERITY;
1022 fstype = "DM_verity_hash";
1023 architecture = SECONDARY_ARCHITECTURE;
1024 rw = false;
1025 }
1026 #endif
1027 #ifdef GPT_USR_NATIVE
1028 else if (sd_id128_equal(type_id, GPT_USR_NATIVE)) {
1029
1030 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1031
1032 if (pflags & GPT_FLAG_NO_AUTO)
1033 continue;
1034
1035 /* If a usr ID is specified, ignore everything but the usr id */
1036 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1037 continue;
1038
1039 designator = PARTITION_USR;
1040 architecture = native_architecture();
1041 rw = !(pflags & GPT_FLAG_READ_ONLY);
1042 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1043
1044 } else if (sd_id128_equal(type_id, GPT_USR_NATIVE_VERITY)) {
1045
1046 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1047
1048 if (pflags & GPT_FLAG_NO_AUTO)
1049 continue;
1050
1051 m->has_verity = true;
1052
1053 /* Ignore verity unless a usr hash is specified */
1054 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
1055 continue;
1056
1057 designator = PARTITION_USR_VERITY;
1058 fstype = "DM_verity_hash";
1059 architecture = native_architecture();
1060 rw = false;
1061 }
1062 #endif
1063 #ifdef GPT_USR_SECONDARY
1064 else if (sd_id128_equal(type_id, GPT_USR_SECONDARY)) {
1065
1066 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1067
1068 if (pflags & GPT_FLAG_NO_AUTO)
1069 continue;
1070
1071 /* If a usr ID is specified, ignore everything but the usr id */
1072 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1073 continue;
1074
1075 designator = PARTITION_USR_SECONDARY;
1076 architecture = SECONDARY_ARCHITECTURE;
1077 rw = !(pflags & GPT_FLAG_READ_ONLY);
1078 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1079
1080 } else if (sd_id128_equal(type_id, GPT_USR_SECONDARY_VERITY)) {
1081
1082 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
1083
1084 if (pflags & GPT_FLAG_NO_AUTO)
1085 continue;
1086
1087 m->has_verity = true;
1088
1089 /* Ignore verity unless usr has is specified */
1090 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
1091 continue;
1092
1093 designator = PARTITION_USR_SECONDARY_VERITY;
1094 fstype = "DM_verity_hash";
1095 architecture = SECONDARY_ARCHITECTURE;
1096 rw = false;
1097 }
1098 #endif
1099 else if (sd_id128_equal(type_id, GPT_SWAP)) {
1100
1101 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
1102
1103 if (pflags & GPT_FLAG_NO_AUTO)
1104 continue;
1105
1106 designator = PARTITION_SWAP;
1107
1108 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
1109
1110 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1111
1112 if (pflags & GPT_FLAG_NO_AUTO)
1113 continue;
1114
1115 if (generic_node)
1116 multiple_generic = true;
1117 else {
1118 generic_nr = nr;
1119 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
1120 generic_growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1121 generic_uuid = id;
1122 generic_node = strdup(node);
1123 if (!generic_node)
1124 return -ENOMEM;
1125 }
1126
1127 } else if (sd_id128_equal(type_id, GPT_TMP)) {
1128
1129 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1130
1131 if (pflags & GPT_FLAG_NO_AUTO)
1132 continue;
1133
1134 designator = PARTITION_TMP;
1135 rw = !(pflags & GPT_FLAG_READ_ONLY);
1136 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1137
1138 } else if (sd_id128_equal(type_id, GPT_VAR)) {
1139
1140 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY|GPT_FLAG_GROWFS);
1141
1142 if (pflags & GPT_FLAG_NO_AUTO)
1143 continue;
1144
1145 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
1146 sd_id128_t var_uuid;
1147
1148 /* For /var we insist that the uuid of the partition matches the
1149 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1150 * ID. Why? Unlike the other partitions /var is inherently
1151 * installation specific, hence we need to be careful not to mount it
1152 * in the wrong installation. By hashing the partition UUID from
1153 * /etc/machine-id we can securely bind the partition to the
1154 * installation. */
1155
1156 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
1157 if (r < 0)
1158 return r;
1159
1160 if (!sd_id128_equal(var_uuid, id)) {
1161 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
1162 continue;
1163 }
1164 }
1165
1166 designator = PARTITION_VAR;
1167 rw = !(pflags & GPT_FLAG_READ_ONLY);
1168 growfs = FLAGS_SET(pflags, GPT_FLAG_GROWFS);
1169 }
1170
1171 if (designator != _PARTITION_DESIGNATOR_INVALID) {
1172 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL, *l = NULL;
1173 const char *options = NULL;
1174
1175 if (m->partitions[designator].found) {
1176 /* For most partition types the first one we see wins. Except for the
1177 * rootfs and /usr, where we do a version compare of the label, and
1178 * let the newest version win. This permits a simple A/B versioning
1179 * scheme in OS images. */
1180
1181 if (!PARTITION_DESIGNATOR_VERSIONED(designator) ||
1182 strverscmp_improved(m->partitions[designator].label, label) >= 0)
1183 continue;
1184
1185 dissected_partition_done(m->partitions + designator);
1186 }
1187
1188 if (fstype) {
1189 t = strdup(fstype);
1190 if (!t)
1191 return -ENOMEM;
1192 }
1193
1194 n = strdup(node);
1195 if (!n)
1196 return -ENOMEM;
1197
1198 if (label) {
1199 l = strdup(label);
1200 if (!l)
1201 return -ENOMEM;
1202 }
1203
1204 options = mount_options_from_designator(mount_options, designator);
1205 if (options) {
1206 o = strdup(options);
1207 if (!o)
1208 return -ENOMEM;
1209 }
1210
1211 m->partitions[designator] = (DissectedPartition) {
1212 .found = true,
1213 .partno = nr,
1214 .rw = rw,
1215 .growfs = growfs,
1216 .architecture = architecture,
1217 .node = TAKE_PTR(n),
1218 .fstype = TAKE_PTR(t),
1219 .label = TAKE_PTR(l),
1220 .uuid = id,
1221 .mount_options = TAKE_PTR(o),
1222 };
1223 }
1224
1225 } else if (is_mbr) {
1226
1227 switch (blkid_partition_get_type(pp)) {
1228
1229 case 0x83: /* Linux partition */
1230
1231 if (pflags != 0x80) /* Bootable flag */
1232 continue;
1233
1234 if (generic_node)
1235 multiple_generic = true;
1236 else {
1237 generic_nr = nr;
1238 generic_rw = true;
1239 generic_growfs = false;
1240 generic_node = strdup(node);
1241 if (!generic_node)
1242 return -ENOMEM;
1243 }
1244
1245 break;
1246
1247 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1248 _cleanup_free_ char *n = NULL, *o = NULL;
1249 sd_id128_t id = SD_ID128_NULL;
1250 const char *sid, *options = NULL;
1251
1252 /* First one wins */
1253 if (m->partitions[PARTITION_XBOOTLDR].found)
1254 continue;
1255
1256 sid = blkid_partition_get_uuid(pp);
1257 if (sid)
1258 (void) sd_id128_from_string(sid, &id);
1259
1260 n = strdup(node);
1261 if (!n)
1262 return -ENOMEM;
1263
1264 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
1265 if (options) {
1266 o = strdup(options);
1267 if (!o)
1268 return -ENOMEM;
1269 }
1270
1271 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1272 .found = true,
1273 .partno = nr,
1274 .rw = true,
1275 .growfs = false,
1276 .architecture = _ARCHITECTURE_INVALID,
1277 .node = TAKE_PTR(n),
1278 .uuid = id,
1279 .mount_options = TAKE_PTR(o),
1280 };
1281
1282 break;
1283 }}
1284 }
1285 }
1286
1287 if (m->partitions[PARTITION_ROOT].found) {
1288 /* If we found the primary arch, then invalidate the secondary arch to avoid any ambiguities,
1289 * since we never want to mount the secondary arch in this case. */
1290 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
1291 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
1292 m->partitions[PARTITION_USR_SECONDARY].found = false;
1293 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
1294
1295 } else if (m->partitions[PARTITION_ROOT_VERITY].found)
1296 return -EADDRNOTAVAIL; /* Verity found but no matching rootfs? Something is off, refuse. */
1297
1298 else if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
1299
1300 /* No root partition found but there's one for the secondary architecture? Then upgrade
1301 * secondary arch to first */
1302
1303 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
1304 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
1305 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
1306 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
1307
1308 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1309 zero(m->partitions[PARTITION_USR_SECONDARY]);
1310 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1311 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
1312
1313 } else if (m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found)
1314 return -EADDRNOTAVAIL; /* as above */
1315
1316 else if (m->partitions[PARTITION_USR].found) {
1317
1318 /* Invalidate secondary arch /usr/ if we found the primary arch */
1319 m->partitions[PARTITION_USR_SECONDARY].found = false;
1320 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
1321
1322 } else if (m->partitions[PARTITION_USR_VERITY].found)
1323 return -EADDRNOTAVAIL; /* as above */
1324
1325 else if (m->partitions[PARTITION_USR_SECONDARY].found) {
1326
1327 /* Upgrade secondary arch to primary */
1328 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1329 zero(m->partitions[PARTITION_USR_SECONDARY]);
1330 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1331 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
1332
1333 } else if (m->partitions[PARTITION_USR_SECONDARY_VERITY].found)
1334 return -EADDRNOTAVAIL; /* as above */
1335
1336 else if ((flags & DISSECT_IMAGE_GENERIC_ROOT) &&
1337 (!verity || !verity->root_hash)) {
1338
1339 /* OK, we found nothing usable, then check if there's a single generic one distro, and use
1340 * that. If the root hash was set however, then we won't fall back to a generic node, because
1341 * the root hash decides. */
1342
1343 /* If we didn't find a properly marked root partition, but we did find a single suitable
1344 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1345 if (multiple_generic)
1346 return -ENOTUNIQ;
1347
1348 /* If we didn't find a generic node, then we can't fix this up either */
1349 if (generic_node) {
1350 _cleanup_free_ char *o = NULL;
1351 const char *options;
1352
1353 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
1354 if (options) {
1355 o = strdup(options);
1356 if (!o)
1357 return -ENOMEM;
1358 }
1359
1360 assert(generic_nr >= 0);
1361 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1362 .found = true,
1363 .rw = generic_rw,
1364 .growfs = generic_growfs,
1365 .partno = generic_nr,
1366 .architecture = _ARCHITECTURE_INVALID,
1367 .node = TAKE_PTR(generic_node),
1368 .uuid = generic_uuid,
1369 .mount_options = TAKE_PTR(o),
1370 };
1371 }
1372 }
1373
1374 /* 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 */
1375 if (FLAGS_SET(flags, DISSECT_IMAGE_REQUIRE_ROOT) &&
1376 !(m->partitions[PARTITION_ROOT].found || (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1377 return -ENXIO;
1378
1379 /* Refuse if we found a verity partition for /usr but no matching file system partition */
1380 if (!m->partitions[PARTITION_USR].found && m->partitions[PARTITION_USR_VERITY].found)
1381 return -EADDRNOTAVAIL;
1382
1383 /* Combinations of verity /usr with verity-less root is OK, but the reverse is not */
1384 if (m->partitions[PARTITION_ROOT_VERITY].found && m->partitions[PARTITION_USR].found && !m->partitions[PARTITION_USR_VERITY].found)
1385 return -EADDRNOTAVAIL;
1386
1387 if (verity && verity->root_hash) {
1388 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1389 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1390 return -EADDRNOTAVAIL;
1391
1392 /* If we found a verity setup, then the root partition is necessarily read-only. */
1393 m->partitions[PARTITION_ROOT].rw = false;
1394 m->verity_ready = true;
1395 }
1396
1397 if (verity->designator == PARTITION_USR) {
1398 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1399 return -EADDRNOTAVAIL;
1400
1401 m->partitions[PARTITION_USR].rw = false;
1402 m->verity_ready = true;
1403 }
1404 }
1405
1406 blkid_free_probe(b);
1407 b = NULL;
1408
1409 /* Fill in file system types if we don't know them yet. */
1410 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1411 DissectedPartition *p = m->partitions + i;
1412
1413 if (!p->found)
1414 continue;
1415
1416 if (!p->fstype && p->node) {
1417 r = probe_filesystem(p->node, &p->fstype);
1418 if (r < 0 && r != -EUCLEAN)
1419 return r;
1420 }
1421
1422 if (streq_ptr(p->fstype, "crypto_LUKS"))
1423 m->encrypted = true;
1424
1425 if (p->fstype && fstype_is_ro(p->fstype))
1426 p->rw = false;
1427
1428 if (!p->rw)
1429 p->growfs = false;
1430 }
1431
1432 *ret = TAKE_PTR(m);
1433 return 0;
1434 #else
1435 return -EOPNOTSUPP;
1436 #endif
1437 }
1438
1439 DissectedImage* dissected_image_unref(DissectedImage *m) {
1440 if (!m)
1441 return NULL;
1442
1443 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
1444 dissected_partition_done(m->partitions + i);
1445
1446 free(m->image_name);
1447 free(m->hostname);
1448 strv_free(m->machine_info);
1449 strv_free(m->os_release);
1450 strv_free(m->extension_release);
1451
1452 return mfree(m);
1453 }
1454
1455 static int is_loop_device(const char *path) {
1456 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
1457 struct stat st;
1458
1459 assert(path);
1460
1461 if (stat(path, &st) < 0)
1462 return -errno;
1463
1464 if (!S_ISBLK(st.st_mode))
1465 return -ENOTBLK;
1466
1467 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
1468 if (access(s, F_OK) < 0) {
1469 if (errno != ENOENT)
1470 return -errno;
1471
1472 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1473 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
1474 if (access(s, F_OK) < 0)
1475 return errno == ENOENT ? false : -errno;
1476 }
1477
1478 return true;
1479 }
1480
1481 static int run_fsck(const char *node, const char *fstype) {
1482 int r, exit_status;
1483 pid_t pid;
1484
1485 assert(node);
1486 assert(fstype);
1487
1488 r = fsck_exists(fstype);
1489 if (r < 0) {
1490 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1491 return 0;
1492 }
1493 if (r == 0) {
1494 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
1495 return 0;
1496 }
1497
1498 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
1499 if (r < 0)
1500 return log_debug_errno(r, "Failed to fork off fsck: %m");
1501 if (r == 0) {
1502 /* Child */
1503 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
1504 log_open();
1505 log_debug_errno(errno, "Failed to execl() fsck: %m");
1506 _exit(FSCK_OPERATIONAL_ERROR);
1507 }
1508
1509 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1510 if (exit_status < 0)
1511 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1512
1513 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1514 log_debug("fsck failed with exit status %i.", exit_status);
1515
1516 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1517 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1518
1519 log_debug("Ignoring fsck error.");
1520 }
1521
1522 return 0;
1523 }
1524
1525 static int fs_grow(const char *node_path, const char *mount_path) {
1526 _cleanup_close_ int mount_fd = -1, node_fd = -1;
1527 uint64_t size, newsize;
1528 int r;
1529
1530 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1531 if (node_fd < 0)
1532 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
1533
1534 if (ioctl(node_fd, BLKGETSIZE64, &size) != 0)
1535 return log_debug_errno(errno, "Failed to get block device size of %s: %m", node_path);
1536
1537 mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1538 if (mount_fd < 0)
1539 return log_debug_errno(errno, "Failed to open mountd file system %s: %m", mount_path);
1540
1541 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", mount_path, size);
1542 r = resize_fs(mount_fd, size, &newsize);
1543 if (r < 0)
1544 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", mount_path, size);
1545
1546 if (newsize == size)
1547 log_debug("Successfully resized \"%s\" to %s bytes.",
1548 mount_path, FORMAT_BYTES(newsize));
1549 else {
1550 assert(newsize < size);
1551 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
1552 mount_path, FORMAT_BYTES(newsize), size - newsize);
1553 }
1554
1555 return 0;
1556 }
1557
1558 static int mount_partition(
1559 DissectedPartition *m,
1560 const char *where,
1561 const char *directory,
1562 uid_t uid_shift,
1563 uid_t uid_range,
1564 DissectImageFlags flags) {
1565
1566 _cleanup_free_ char *chased = NULL, *options = NULL;
1567 const char *p, *node, *fstype;
1568 bool rw, remap_uid_gid = false;
1569 int r;
1570
1571 assert(m);
1572 assert(where);
1573
1574 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1575 node = m->decrypted_node ?: m->node;
1576 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
1577
1578 if (!m->found || !node)
1579 return 0;
1580 if (!fstype)
1581 return -EAFNOSUPPORT;
1582
1583 /* 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. */
1584 if (streq(fstype, "crypto_LUKS"))
1585 return -EUNATCH;
1586
1587 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
1588
1589 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1590 r = run_fsck(node, fstype);
1591 if (r < 0)
1592 return r;
1593 }
1594
1595 if (directory) {
1596 /* Automatically create missing mount points inside the image, if necessary. */
1597 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1598 if (r < 0 && r != -EROFS)
1599 return r;
1600
1601 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
1602 if (r < 0)
1603 return r;
1604
1605 p = chased;
1606 } else {
1607 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1608 * image (as the branch above does) but the host hierarchy, and the created directory might
1609 * survive our mount in the host hierarchy hence. */
1610 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1611 r = mkdir_p(where, 0755);
1612 if (r < 0)
1613 return r;
1614 }
1615
1616 p = where;
1617 }
1618
1619 /* If requested, turn on discard support. */
1620 if (fstype_can_discard(fstype) &&
1621 ((flags & DISSECT_IMAGE_DISCARD) ||
1622 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
1623 options = strdup("discard");
1624 if (!options)
1625 return -ENOMEM;
1626 }
1627
1628 if (uid_is_valid(uid_shift) && uid_shift != 0) {
1629
1630 if (fstype_can_uid_gid(fstype)) {
1631 _cleanup_free_ char *uid_option = NULL;
1632
1633 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1634 return -ENOMEM;
1635
1636 if (!strextend_with_separator(&options, ",", uid_option))
1637 return -ENOMEM;
1638 } else if (FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED))
1639 remap_uid_gid = true;
1640 }
1641
1642 if (!isempty(m->mount_options))
1643 if (!strextend_with_separator(&options, ",", m->mount_options))
1644 return -ENOMEM;
1645
1646 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1647 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1648 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1649 * from the upper file system still get propagated through to the underlying file system,
1650 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1651 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1652 * carry a per file system table here.
1653 *
1654 * Note that this means that we might not be able to mount corrupted file systems as read-only
1655 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1656 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1657 * mount options for loopback devices this is the right choice, since otherwise using the same
1658 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1659 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1660 * access that actually modifies stuff work on such image files. Or to say this differently: if
1661 * people want their file systems to be fixed up they should just open them in writable mode, where
1662 * all these problems don't exist. */
1663 if (!rw && STRPTR_IN_SET(fstype, "ext3", "ext4", "xfs", "btrfs"))
1664 if (!strextend_with_separator(&options, ",", "norecovery"))
1665 return -ENOMEM;
1666
1667 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
1668 if (r < 0)
1669 return r;
1670
1671 if (rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS))
1672 (void) fs_grow(node, p);
1673
1674 if (remap_uid_gid) {
1675 r = remount_idmap(p, uid_shift, uid_range);
1676 if (r < 0)
1677 return r;
1678 }
1679
1680 return 1;
1681 }
1682
1683 static int mount_root_tmpfs(const char *where, uid_t uid_shift, DissectImageFlags flags) {
1684 _cleanup_free_ char *options = NULL;
1685 int r;
1686
1687 assert(where);
1688
1689 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1690
1691 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1692 r = mkdir_p(where, 0755);
1693 if (r < 0)
1694 return r;
1695 }
1696
1697 if (uid_is_valid(uid_shift)) {
1698 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1699 return -ENOMEM;
1700 }
1701
1702 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
1703 if (r < 0)
1704 return r;
1705
1706 return 1;
1707 }
1708
1709 int dissected_image_mount(
1710 DissectedImage *m,
1711 const char *where,
1712 uid_t uid_shift,
1713 uid_t uid_range,
1714 DissectImageFlags flags) {
1715
1716 int r, xbootldr_mounted;
1717
1718 assert(m);
1719 assert(where);
1720
1721 /* Returns:
1722 *
1723 * -ENXIO → No root partition found
1724 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1725 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1726 * -EUCLEAN → fsck for file system failed
1727 * -EBUSY → File system already mounted/used elsewhere (kernel)
1728 * -EAFNOSUPPORT → File system type not supported or not known
1729 */
1730
1731 if (!(m->partitions[PARTITION_ROOT].found ||
1732 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1733 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
1734
1735 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1736
1737 /* First mount the root fs. If there's none we use a tmpfs. */
1738 if (m->partitions[PARTITION_ROOT].found)
1739 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, flags);
1740 else
1741 r = mount_root_tmpfs(where, uid_shift, flags);
1742 if (r < 0)
1743 return r;
1744
1745 /* For us mounting root always means mounting /usr as well */
1746 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, flags);
1747 if (r < 0)
1748 return r;
1749
1750 if ((flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
1751 /* If either one of the validation flags are set, ensure that the image qualifies
1752 * as one or the other (or both). */
1753 bool ok = false;
1754
1755 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
1756 r = path_is_os_tree(where);
1757 if (r < 0)
1758 return r;
1759 if (r > 0)
1760 ok = true;
1761 }
1762 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT)) {
1763 r = path_is_extension_tree(where, m->image_name);
1764 if (r < 0)
1765 return r;
1766 if (r > 0)
1767 ok = true;
1768 }
1769
1770 if (!ok)
1771 return -ENOMEDIUM;
1772 }
1773 }
1774
1775 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
1776 return 0;
1777
1778 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, flags);
1779 if (r < 0)
1780 return r;
1781
1782 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, flags);
1783 if (r < 0)
1784 return r;
1785
1786 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, flags);
1787 if (r < 0)
1788 return r;
1789
1790 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, flags);
1791 if (r < 0)
1792 return r;
1793
1794 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, flags);
1795 if (xbootldr_mounted < 0)
1796 return xbootldr_mounted;
1797
1798 if (m->partitions[PARTITION_ESP].found) {
1799 int esp_done = false;
1800
1801 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1802 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1803
1804 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1805 if (r < 0) {
1806 if (r != -ENOENT)
1807 return r;
1808
1809 /* /efi doesn't exist. Let's see if /boot is suitable then */
1810
1811 if (!xbootldr_mounted) {
1812 _cleanup_free_ char *p = NULL;
1813
1814 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1815 if (r < 0) {
1816 if (r != -ENOENT)
1817 return r;
1818 } else if (dir_is_empty(p) > 0) {
1819 /* It exists and is an empty directory. Let's mount the ESP there. */
1820 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, uid_range, flags);
1821 if (r < 0)
1822 return r;
1823
1824 esp_done = true;
1825 }
1826 }
1827 }
1828
1829 if (!esp_done) {
1830 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1831
1832 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, uid_range, flags);
1833 if (r < 0)
1834 return r;
1835 }
1836 }
1837
1838 return 0;
1839 }
1840
1841 int dissected_image_mount_and_warn(
1842 DissectedImage *m,
1843 const char *where,
1844 uid_t uid_shift,
1845 uid_t uid_range,
1846 DissectImageFlags flags) {
1847
1848 int r;
1849
1850 assert(m);
1851 assert(where);
1852
1853 r = dissected_image_mount(m, where, uid_shift, uid_range, flags);
1854 if (r == -ENXIO)
1855 return log_error_errno(r, "Not root file system found in image.");
1856 if (r == -EMEDIUMTYPE)
1857 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
1858 if (r == -EUNATCH)
1859 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1860 if (r == -EUCLEAN)
1861 return log_error_errno(r, "File system check on image failed.");
1862 if (r == -EBUSY)
1863 return log_error_errno(r, "File system already mounted elsewhere.");
1864 if (r == -EAFNOSUPPORT)
1865 return log_error_errno(r, "File system type not supported or not known.");
1866 if (r < 0)
1867 return log_error_errno(r, "Failed to mount image: %m");
1868
1869 return r;
1870 }
1871
1872 #if HAVE_LIBCRYPTSETUP
1873 typedef struct DecryptedPartition {
1874 struct crypt_device *device;
1875 char *name;
1876 bool relinquished;
1877 } DecryptedPartition;
1878
1879 struct DecryptedImage {
1880 DecryptedPartition *decrypted;
1881 size_t n_decrypted;
1882 };
1883 #endif
1884
1885 DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
1886 #if HAVE_LIBCRYPTSETUP
1887 int r;
1888
1889 if (!d)
1890 return NULL;
1891
1892 for (size_t i = 0; i < d->n_decrypted; i++) {
1893 DecryptedPartition *p = d->decrypted + i;
1894
1895 if (p->device && p->name && !p->relinquished) {
1896 r = sym_crypt_deactivate_by_name(p->device, p->name, 0);
1897 if (r < 0)
1898 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1899 }
1900
1901 if (p->device)
1902 sym_crypt_free(p->device);
1903 free(p->name);
1904 }
1905
1906 free(d->decrypted);
1907 free(d);
1908 #endif
1909 return NULL;
1910 }
1911
1912 #if HAVE_LIBCRYPTSETUP
1913
1914 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1915 _cleanup_free_ char *name = NULL, *node = NULL;
1916 const char *base;
1917
1918 assert(original_node);
1919 assert(suffix);
1920 assert(ret_name);
1921 assert(ret_node);
1922
1923 base = strrchr(original_node, '/');
1924 if (!base)
1925 base = original_node;
1926 else
1927 base++;
1928 if (isempty(base))
1929 return -EINVAL;
1930
1931 name = strjoin(base, suffix);
1932 if (!name)
1933 return -ENOMEM;
1934 if (!filename_is_valid(name))
1935 return -EINVAL;
1936
1937 node = path_join(sym_crypt_get_dir(), name);
1938 if (!node)
1939 return -ENOMEM;
1940
1941 *ret_name = TAKE_PTR(name);
1942 *ret_node = TAKE_PTR(node);
1943
1944 return 0;
1945 }
1946
1947 static int decrypt_partition(
1948 DissectedPartition *m,
1949 const char *passphrase,
1950 DissectImageFlags flags,
1951 DecryptedImage *d) {
1952
1953 _cleanup_free_ char *node = NULL, *name = NULL;
1954 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
1955 int r;
1956
1957 assert(m);
1958 assert(d);
1959
1960 if (!m->found || !m->node || !m->fstype)
1961 return 0;
1962
1963 if (!streq(m->fstype, "crypto_LUKS"))
1964 return 0;
1965
1966 if (!passphrase)
1967 return -ENOKEY;
1968
1969 r = dlopen_cryptsetup();
1970 if (r < 0)
1971 return r;
1972
1973 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1974 if (r < 0)
1975 return r;
1976
1977 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
1978 return -ENOMEM;
1979
1980 r = sym_crypt_init(&cd, m->node);
1981 if (r < 0)
1982 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
1983
1984 cryptsetup_enable_logging(cd);
1985
1986 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
1987 if (r < 0)
1988 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
1989
1990 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1991 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1992 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
1993 if (r < 0) {
1994 log_debug_errno(r, "Failed to activate LUKS device: %m");
1995 return r == -EPERM ? -EKEYREJECTED : r;
1996 }
1997
1998 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1999 .name = TAKE_PTR(name),
2000 .device = TAKE_PTR(cd),
2001 };
2002
2003 m->decrypted_node = TAKE_PTR(node);
2004
2005 return 0;
2006 }
2007
2008 static int verity_can_reuse(
2009 const VeritySettings *verity,
2010 const char *name,
2011 struct crypt_device **ret_cd) {
2012
2013 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2014 _cleanup_free_ char *root_hash_existing = NULL;
2015 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2016 struct crypt_params_verity crypt_params = {};
2017 size_t root_hash_existing_size;
2018 int r;
2019
2020 assert(verity);
2021 assert(name);
2022 assert(ret_cd);
2023
2024 r = sym_crypt_init_by_name(&cd, name);
2025 if (r < 0)
2026 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
2027
2028 cryptsetup_enable_logging(cd);
2029
2030 r = sym_crypt_get_verity_info(cd, &crypt_params);
2031 if (r < 0)
2032 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
2033
2034 root_hash_existing_size = verity->root_hash_size;
2035 root_hash_existing = malloc0(root_hash_existing_size);
2036 if (!root_hash_existing)
2037 return -ENOMEM;
2038
2039 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
2040 if (r < 0)
2041 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
2042 if (verity->root_hash_size != root_hash_existing_size ||
2043 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
2044 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
2045
2046 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2047 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2048 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2049 * signing for the new one, and vice versa. */
2050 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
2051 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
2052 #endif
2053
2054 *ret_cd = TAKE_PTR(cd);
2055 return 0;
2056 }
2057
2058 static inline char* dm_deferred_remove_clean(char *name) {
2059 if (!name)
2060 return NULL;
2061
2062 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
2063 return mfree(name);
2064 }
2065 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
2066
2067 static int verity_partition(
2068 PartitionDesignator designator,
2069 DissectedPartition *m,
2070 DissectedPartition *v,
2071 const VeritySettings *verity,
2072 DissectImageFlags flags,
2073 DecryptedImage *d) {
2074
2075 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2076 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
2077 _cleanup_free_ char *node = NULL, *name = NULL;
2078 int r;
2079
2080 assert(m);
2081 assert(v || (verity && verity->data_path));
2082
2083 if (!verity || !verity->root_hash)
2084 return 0;
2085 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2086 (verity->designator == designator)))
2087 return 0;
2088
2089 if (!m->found || !m->node || !m->fstype)
2090 return 0;
2091 if (!verity->data_path) {
2092 if (!v->found || !v->node || !v->fstype)
2093 return 0;
2094
2095 if (!streq(v->fstype, "DM_verity_hash"))
2096 return 0;
2097 }
2098
2099 r = dlopen_cryptsetup();
2100 if (r < 0)
2101 return r;
2102
2103 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2104 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2105 _cleanup_free_ char *root_hash_encoded = NULL;
2106
2107 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
2108 if (!root_hash_encoded)
2109 return -ENOMEM;
2110
2111 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2112 } else
2113 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
2114 if (r < 0)
2115 return r;
2116
2117 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
2118 if (r < 0)
2119 return r;
2120
2121 cryptsetup_enable_logging(cd);
2122
2123 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
2124 if (r < 0)
2125 return r;
2126
2127 r = sym_crypt_set_data_device(cd, m->node);
2128 if (r < 0)
2129 return r;
2130
2131 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2132 return -ENOMEM;
2133
2134 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2135 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2136 * retry a few times before giving up. */
2137 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
2138 if (verity->root_hash_sig) {
2139 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2140 r = sym_crypt_activate_by_signed_key(
2141 cd,
2142 name,
2143 verity->root_hash,
2144 verity->root_hash_size,
2145 verity->root_hash_sig,
2146 verity->root_hash_sig_size,
2147 CRYPT_ACTIVATE_READONLY);
2148 #else
2149 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2150 "Activation of verity device with signature requested, but not supported by %s due to missing crypt_activate_by_signed_key().", program_invocation_short_name);
2151 #endif
2152 } else
2153 r = sym_crypt_activate_by_volume_key(
2154 cd,
2155 name,
2156 verity->root_hash,
2157 verity->root_hash_size,
2158 CRYPT_ACTIVATE_READONLY);
2159 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2160 * There's no way to distinguish this situation from a genuine error due to invalid
2161 * parameters, so immediately fall back to activating the device with a unique name.
2162 * Improvements in libcrypsetup can ensure this never happens:
2163 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2164 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2165 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2166 if (!IN_SET(r,
2167 0, /* Success */
2168 -EEXIST, /* Volume is already open and ready to be used */
2169 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
2170 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
2171 return r;
2172 if (IN_SET(r, -EEXIST, -EBUSY)) {
2173 struct crypt_device *existing_cd = NULL;
2174
2175 if (!restore_deferred_remove){
2176 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2177 r = dm_deferred_remove_cancel(name);
2178 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
2179 if (r < 0 && r != -ENXIO)
2180 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
2181 if (r == 0) {
2182 restore_deferred_remove = strdup(name);
2183 if (!restore_deferred_remove)
2184 return -ENOMEM;
2185 }
2186 }
2187
2188 r = verity_can_reuse(verity, name, &existing_cd);
2189 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2190 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2191 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2192 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
2193 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
2194 if (r == 0) {
2195 /* devmapper might say that the device exists, but the devlink might not yet have been
2196 * created. Check and wait for the udev event in that case. */
2197 r = device_wait_for_devlink(node, "block", usec_add(now(CLOCK_MONOTONIC), 100 * USEC_PER_MSEC), NULL);
2198 /* Fallback to activation with a unique device if it's taking too long */
2199 if (r == -ETIMEDOUT)
2200 break;
2201 if (r < 0)
2202 return r;
2203
2204 if (cd)
2205 sym_crypt_free(cd);
2206 cd = existing_cd;
2207 }
2208 }
2209 if (r == 0)
2210 break;
2211
2212 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
2213 (void) usleep(2 * USEC_PER_MSEC);
2214 }
2215
2216 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
2217 * Fall back to activating it with a unique device name. */
2218 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2219 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2220
2221 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2222 restore_deferred_remove = mfree(restore_deferred_remove);
2223
2224 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2225 .name = TAKE_PTR(name),
2226 .device = TAKE_PTR(cd),
2227 };
2228
2229 m->decrypted_node = TAKE_PTR(node);
2230
2231 return 0;
2232 }
2233 #endif
2234
2235 int dissected_image_decrypt(
2236 DissectedImage *m,
2237 const char *passphrase,
2238 const VeritySettings *verity,
2239 DissectImageFlags flags,
2240 DecryptedImage **ret) {
2241
2242 #if HAVE_LIBCRYPTSETUP
2243 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2244 int r;
2245 #endif
2246
2247 assert(m);
2248 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
2249
2250 /* Returns:
2251 *
2252 * = 0 → There was nothing to decrypt
2253 * > 0 → Decrypted successfully
2254 * -ENOKEY → There's something to decrypt but no key was supplied
2255 * -EKEYREJECTED → Passed key was not correct
2256 */
2257
2258 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
2259 return -EINVAL;
2260
2261 if (!m->encrypted && !m->verity_ready) {
2262 *ret = NULL;
2263 return 0;
2264 }
2265
2266 #if HAVE_LIBCRYPTSETUP
2267 d = new0(DecryptedImage, 1);
2268 if (!d)
2269 return -ENOMEM;
2270
2271 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
2272 DissectedPartition *p = m->partitions + i;
2273 PartitionDesignator k;
2274
2275 if (!p->found)
2276 continue;
2277
2278 r = decrypt_partition(p, passphrase, flags, d);
2279 if (r < 0)
2280 return r;
2281
2282 k = PARTITION_VERITY_OF(i);
2283 if (k >= 0) {
2284 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
2285 if (r < 0)
2286 return r;
2287 }
2288
2289 if (!p->decrypted_fstype && p->decrypted_node) {
2290 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
2291 if (r < 0 && r != -EUCLEAN)
2292 return r;
2293 }
2294 }
2295
2296 *ret = TAKE_PTR(d);
2297
2298 return 1;
2299 #else
2300 return -EOPNOTSUPP;
2301 #endif
2302 }
2303
2304 int dissected_image_decrypt_interactively(
2305 DissectedImage *m,
2306 const char *passphrase,
2307 const VeritySettings *verity,
2308 DissectImageFlags flags,
2309 DecryptedImage **ret) {
2310
2311 _cleanup_strv_free_erase_ char **z = NULL;
2312 int n = 3, r;
2313
2314 if (passphrase)
2315 n--;
2316
2317 for (;;) {
2318 r = dissected_image_decrypt(m, passphrase, verity, flags, ret);
2319 if (r >= 0)
2320 return r;
2321 if (r == -EKEYREJECTED)
2322 log_error_errno(r, "Incorrect passphrase, try again!");
2323 else if (r != -ENOKEY)
2324 return log_error_errno(r, "Failed to decrypt image: %m");
2325
2326 if (--n < 0)
2327 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
2328 "Too many retries.");
2329
2330 z = strv_free(z);
2331
2332 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY, 0, &z);
2333 if (r < 0)
2334 return log_error_errno(r, "Failed to query for passphrase: %m");
2335
2336 passphrase = z[0];
2337 }
2338 }
2339
2340 int decrypted_image_relinquish(DecryptedImage *d) {
2341 assert(d);
2342
2343 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2344 * boolean so that we don't clean it up ourselves either anymore */
2345
2346 #if HAVE_LIBCRYPTSETUP
2347 int r;
2348
2349 for (size_t i = 0; i < d->n_decrypted; i++) {
2350 DecryptedPartition *p = d->decrypted + i;
2351
2352 if (p->relinquished)
2353 continue;
2354
2355 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
2356 if (r < 0)
2357 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
2358
2359 p->relinquished = true;
2360 }
2361 #endif
2362
2363 return 0;
2364 }
2365
2366 static char *build_auxiliary_path(const char *image, const char *suffix) {
2367 const char *e;
2368 char *n;
2369
2370 assert(image);
2371 assert(suffix);
2372
2373 e = endswith(image, ".raw");
2374 if (!e)
2375 return strjoin(e, suffix);
2376
2377 n = new(char, e - image + strlen(suffix) + 1);
2378 if (!n)
2379 return NULL;
2380
2381 strcpy(mempcpy(n, image, e - image), suffix);
2382 return n;
2383 }
2384
2385 void verity_settings_done(VeritySettings *v) {
2386 assert(v);
2387
2388 v->root_hash = mfree(v->root_hash);
2389 v->root_hash_size = 0;
2390
2391 v->root_hash_sig = mfree(v->root_hash_sig);
2392 v->root_hash_sig_size = 0;
2393
2394 v->data_path = mfree(v->data_path);
2395 }
2396
2397 int verity_settings_load(
2398 VeritySettings *verity,
2399 const char *image,
2400 const char *root_hash_path,
2401 const char *root_hash_sig_path) {
2402
2403 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2404 size_t root_hash_size = 0, root_hash_sig_size = 0;
2405 _cleanup_free_ char *verity_data_path = NULL;
2406 PartitionDesignator designator;
2407 int r;
2408
2409 assert(verity);
2410 assert(image);
2411 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
2412
2413 /* If we are asked to load the root hash for a device node, exit early */
2414 if (is_device_path(image))
2415 return 0;
2416
2417 designator = verity->designator;
2418
2419 /* We only fill in what isn't already filled in */
2420
2421 if (!verity->root_hash) {
2422 _cleanup_free_ char *text = NULL;
2423
2424 if (root_hash_path) {
2425 /* If explicitly specified it takes precedence */
2426 r = read_one_line_file(root_hash_path, &text);
2427 if (r < 0)
2428 return r;
2429
2430 if (designator < 0)
2431 designator = PARTITION_ROOT;
2432 } else {
2433 /* Otherwise look for xattr and separate file, and first for the data for root and if
2434 * that doesn't exist for /usr */
2435
2436 if (designator < 0 || designator == PARTITION_ROOT) {
2437 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
2438 if (r < 0) {
2439 _cleanup_free_ char *p = NULL;
2440
2441 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2442 return r;
2443
2444 p = build_auxiliary_path(image, ".roothash");
2445 if (!p)
2446 return -ENOMEM;
2447
2448 r = read_one_line_file(p, &text);
2449 if (r < 0 && r != -ENOENT)
2450 return r;
2451 }
2452
2453 if (text)
2454 designator = PARTITION_ROOT;
2455 }
2456
2457 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2458 /* So in the "roothash" xattr/file name above the "root" of course primarily
2459 * refers to the root of the Verity Merkle tree. But coincidentally it also
2460 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2461 * two distinct concepts called "root". Taking benefit of this happy
2462 * coincidence we call the file with the root hash for the /usr/ file system
2463 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2464 * confusing. We thus drop the reference to the root of the Merkle tree, and
2465 * just indicate which file system it's about. */
2466 r = getxattr_malloc(image, "user.verity.usrhash", &text, true);
2467 if (r < 0) {
2468 _cleanup_free_ char *p = NULL;
2469
2470 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2471 return r;
2472
2473 p = build_auxiliary_path(image, ".usrhash");
2474 if (!p)
2475 return -ENOMEM;
2476
2477 r = read_one_line_file(p, &text);
2478 if (r < 0 && r != -ENOENT)
2479 return r;
2480 }
2481
2482 if (text)
2483 designator = PARTITION_USR;
2484 }
2485 }
2486
2487 if (text) {
2488 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
2489 if (r < 0)
2490 return r;
2491 if (root_hash_size < sizeof(sd_id128_t))
2492 return -EINVAL;
2493 }
2494 }
2495
2496 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
2497 if (root_hash_sig_path) {
2498 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
2499 if (r < 0 && r != -ENOENT)
2500 return r;
2501
2502 if (designator < 0)
2503 designator = PARTITION_ROOT;
2504 } else {
2505 if (designator < 0 || designator == PARTITION_ROOT) {
2506 _cleanup_free_ char *p = NULL;
2507
2508 /* Follow naming convention recommended by the relevant RFC:
2509 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2510 p = build_auxiliary_path(image, ".roothash.p7s");
2511 if (!p)
2512 return -ENOMEM;
2513
2514 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
2515 if (r < 0 && r != -ENOENT)
2516 return r;
2517 if (r >= 0)
2518 designator = PARTITION_ROOT;
2519 }
2520
2521 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2522 _cleanup_free_ char *p = NULL;
2523
2524 p = build_auxiliary_path(image, ".usrhash.p7s");
2525 if (!p)
2526 return -ENOMEM;
2527
2528 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
2529 if (r < 0 && r != -ENOENT)
2530 return r;
2531 if (r >= 0)
2532 designator = PARTITION_USR;
2533 }
2534 }
2535
2536 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
2537 return -EINVAL;
2538 }
2539
2540 if (!verity->data_path) {
2541 _cleanup_free_ char *p = NULL;
2542
2543 p = build_auxiliary_path(image, ".verity");
2544 if (!p)
2545 return -ENOMEM;
2546
2547 if (access(p, F_OK) < 0) {
2548 if (errno != ENOENT)
2549 return -errno;
2550 } else
2551 verity_data_path = TAKE_PTR(p);
2552 }
2553
2554 if (root_hash) {
2555 verity->root_hash = TAKE_PTR(root_hash);
2556 verity->root_hash_size = root_hash_size;
2557 }
2558
2559 if (root_hash_sig) {
2560 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2561 verity->root_hash_sig_size = root_hash_sig_size;
2562 }
2563
2564 if (verity_data_path)
2565 verity->data_path = TAKE_PTR(verity_data_path);
2566
2567 if (verity->designator < 0)
2568 verity->designator = designator;
2569
2570 return 1;
2571 }
2572
2573 int dissected_image_acquire_metadata(DissectedImage *m) {
2574
2575 enum {
2576 META_HOSTNAME,
2577 META_MACHINE_ID,
2578 META_MACHINE_INFO,
2579 META_OS_RELEASE,
2580 META_EXTENSION_RELEASE,
2581 _META_MAX,
2582 };
2583
2584 static const char *const paths[_META_MAX] = {
2585 [META_HOSTNAME] = "/etc/hostname\0",
2586 [META_MACHINE_ID] = "/etc/machine-id\0",
2587 [META_MACHINE_INFO] = "/etc/machine-info\0",
2588 [META_OS_RELEASE] = ("/etc/os-release\0"
2589 "/usr/lib/os-release\0"),
2590 [META_EXTENSION_RELEASE] = "extension-release\0", /* Used only for logging. */
2591 };
2592
2593 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **extension_release = NULL;
2594 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
2595 _cleanup_(rmdir_and_freep) char *t = NULL;
2596 _cleanup_(sigkill_waitp) pid_t child = 0;
2597 sd_id128_t machine_id = SD_ID128_NULL;
2598 _cleanup_free_ char *hostname = NULL;
2599 unsigned n_meta_initialized = 0;
2600 int fds[2 * _META_MAX], r, v;
2601 ssize_t n;
2602
2603 BLOCK_SIGNALS(SIGCHLD);
2604
2605 assert(m);
2606
2607 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++) {
2608 if (!paths[n_meta_initialized]) {
2609 fds[2*n_meta_initialized] = fds[2*n_meta_initialized+1] = -1;
2610 continue;
2611 }
2612
2613 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2614 r = -errno;
2615 goto finish;
2616 }
2617 }
2618
2619 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2620 if (r < 0)
2621 goto finish;
2622
2623 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2624 r = -errno;
2625 goto finish;
2626 }
2627
2628 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
2629 if (r < 0)
2630 goto finish;
2631 if (r == 0) {
2632 error_pipe[0] = safe_close(error_pipe[0]);
2633
2634 r = dissected_image_mount(
2635 m,
2636 t,
2637 UID_INVALID,
2638 UID_INVALID,
2639 DISSECT_IMAGE_READ_ONLY|
2640 DISSECT_IMAGE_MOUNT_ROOT_ONLY|
2641 DISSECT_IMAGE_VALIDATE_OS|
2642 DISSECT_IMAGE_VALIDATE_OS_EXT|
2643 DISSECT_IMAGE_USR_NO_ROOT);
2644 if (r < 0) {
2645 /* Let parent know the error */
2646 (void) write(error_pipe[1], &r, sizeof(r));
2647
2648 log_debug_errno(r, "Failed to mount dissected image: %m");
2649 _exit(EXIT_FAILURE);
2650 }
2651
2652 for (unsigned k = 0; k < _META_MAX; k++) {
2653 _cleanup_close_ int fd = -ENOENT;
2654 const char *p;
2655
2656 if (!paths[k])
2657 continue;
2658
2659 fds[2*k] = safe_close(fds[2*k]);
2660
2661 if (k == META_EXTENSION_RELEASE) {
2662 /* As per the os-release spec, if the image is an extension it will have a file
2663 * named after the image name in extension-release.d/ - we use the image name
2664 * and try to resolve it with the extension-release helpers, as sometimes
2665 * the image names are mangled on deployment and do not match anymore.
2666 * Unlike other paths this is not fixed, and the image name
2667 * can be mangled on deployment, so by calling into the helper
2668 * we allow a fallback that matches on the first extension-release
2669 * file found in the directory, if one named after the image cannot
2670 * be found first. */
2671 r = open_extension_release(t, m->image_name, NULL, &fd);
2672 if (r < 0)
2673 fd = r; /* Propagate the error. */
2674 } else
2675 NULSTR_FOREACH(p, paths[k]) {
2676 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
2677 if (fd >= 0)
2678 break;
2679 }
2680 if (fd < 0) {
2681 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
2682 fds[2*k+1] = safe_close(fds[2*k+1]);
2683 continue;
2684 }
2685
2686 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
2687 if (r < 0) {
2688 (void) write(error_pipe[1], &r, sizeof(r));
2689 _exit(EXIT_FAILURE);
2690 }
2691
2692 fds[2*k+1] = safe_close(fds[2*k+1]);
2693 }
2694
2695 _exit(EXIT_SUCCESS);
2696 }
2697
2698 error_pipe[1] = safe_close(error_pipe[1]);
2699
2700 for (unsigned k = 0; k < _META_MAX; k++) {
2701 _cleanup_fclose_ FILE *f = NULL;
2702
2703 if (!paths[k])
2704 continue;
2705
2706 fds[2*k+1] = safe_close(fds[2*k+1]);
2707
2708 f = take_fdopen(&fds[2*k], "r");
2709 if (!f) {
2710 r = -errno;
2711 goto finish;
2712 }
2713
2714 switch (k) {
2715
2716 case META_HOSTNAME:
2717 r = read_etc_hostname_stream(f, &hostname);
2718 if (r < 0)
2719 log_debug_errno(r, "Failed to read /etc/hostname: %m");
2720
2721 break;
2722
2723 case META_MACHINE_ID: {
2724 _cleanup_free_ char *line = NULL;
2725
2726 r = read_line(f, LONG_LINE_MAX, &line);
2727 if (r < 0)
2728 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
2729 else if (r == 33) {
2730 r = sd_id128_from_string(line, &machine_id);
2731 if (r < 0)
2732 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
2733 } else if (r == 0)
2734 log_debug("/etc/machine-id file is empty.");
2735 else if (streq(line, "uninitialized"))
2736 log_debug("/etc/machine-id file is uninitialized (likely aborted first boot).");
2737 else
2738 log_debug("/etc/machine-id has unexpected length %i.", r);
2739
2740 break;
2741 }
2742
2743 case META_MACHINE_INFO:
2744 r = load_env_file_pairs(f, "machine-info", &machine_info);
2745 if (r < 0)
2746 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
2747
2748 break;
2749
2750 case META_OS_RELEASE:
2751 r = load_env_file_pairs(f, "os-release", &os_release);
2752 if (r < 0)
2753 log_debug_errno(r, "Failed to read OS release file: %m");
2754
2755 break;
2756
2757 case META_EXTENSION_RELEASE:
2758 r = load_env_file_pairs(f, "extension-release", &extension_release);
2759 if (r < 0)
2760 log_debug_errno(r, "Failed to read extension release file: %m");
2761
2762 break;
2763 }
2764 }
2765
2766 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
2767 child = 0;
2768 if (r < 0)
2769 return r;
2770
2771 n = read(error_pipe[0], &v, sizeof(v));
2772 if (n < 0)
2773 return -errno;
2774 if (n == sizeof(v))
2775 return v; /* propagate error sent to us from child */
2776 if (n != 0)
2777 return -EIO;
2778
2779 if (r != EXIT_SUCCESS)
2780 return -EPROTO;
2781
2782 free_and_replace(m->hostname, hostname);
2783 m->machine_id = machine_id;
2784 strv_free_and_replace(m->machine_info, machine_info);
2785 strv_free_and_replace(m->os_release, os_release);
2786 strv_free_and_replace(m->extension_release, extension_release);
2787
2788 finish:
2789 for (unsigned k = 0; k < n_meta_initialized; k++)
2790 safe_close_pair(fds + 2*k);
2791
2792 return r;
2793 }
2794
2795 int dissect_image_and_warn(
2796 int fd,
2797 const char *name,
2798 const VeritySettings *verity,
2799 const MountOptions *mount_options,
2800 uint64_t diskseq,
2801 uint64_t uevent_seqnum_not_before,
2802 usec_t timestamp_not_before,
2803 DissectImageFlags flags,
2804 DissectedImage **ret) {
2805
2806 _cleanup_free_ char *buffer = NULL;
2807 int r;
2808
2809 if (!name) {
2810 r = fd_get_path(fd, &buffer);
2811 if (r < 0)
2812 return r;
2813
2814 name = buffer;
2815 }
2816
2817 r = dissect_image(fd, verity, mount_options, diskseq, uevent_seqnum_not_before, timestamp_not_before, flags, ret);
2818 switch (r) {
2819
2820 case -EOPNOTSUPP:
2821 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
2822
2823 case -ENOPKG:
2824 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
2825
2826 case -EADDRNOTAVAIL:
2827 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
2828
2829 case -ENOTUNIQ:
2830 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
2831
2832 case -ENXIO:
2833 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
2834
2835 case -EPROTONOSUPPORT:
2836 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
2837
2838 default:
2839 if (r < 0)
2840 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
2841
2842 return r;
2843 }
2844 }
2845
2846 bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
2847 assert(image);
2848
2849 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
2850 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
2851 * images we only check the partition type.
2852 *
2853 * This call is used to decide whether to suppress or show a verity column in tabular output of the
2854 * image. */
2855
2856 if (image->single_file_system)
2857 return partition_designator == PARTITION_ROOT && image->has_verity;
2858
2859 return PARTITION_VERITY_OF(partition_designator) >= 0;
2860 }
2861
2862 bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
2863 PartitionDesignator k;
2864
2865 assert(image);
2866
2867 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
2868 * works for the root partition, for others only if the associated verity partition was found. */
2869
2870 if (!image->verity_ready)
2871 return false;
2872
2873 if (image->single_file_system)
2874 return partition_designator == PARTITION_ROOT;
2875
2876 k = PARTITION_VERITY_OF(partition_designator);
2877 return k >= 0 && image->partitions[k].found;
2878 }
2879
2880 MountOptions* mount_options_free_all(MountOptions *options) {
2881 MountOptions *m;
2882
2883 while ((m = options)) {
2884 LIST_REMOVE(mount_options, options, m);
2885 free(m->options);
2886 free(m);
2887 }
2888
2889 return NULL;
2890 }
2891
2892 const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
2893 const MountOptions *m;
2894
2895 LIST_FOREACH(mount_options, m, options)
2896 if (designator == m->partition_designator && !isempty(m->options))
2897 return m->options;
2898
2899 return NULL;
2900 }
2901
2902 int mount_image_privately_interactively(
2903 const char *image,
2904 DissectImageFlags flags,
2905 char **ret_directory,
2906 LoopDevice **ret_loop_device,
2907 DecryptedImage **ret_decrypted_image) {
2908
2909 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2910 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2911 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2912 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2913 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
2914 _cleanup_free_ char *temp = NULL;
2915 int r;
2916
2917 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2918 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2919 * easily. */
2920
2921 assert(image);
2922 assert(ret_directory);
2923 assert(ret_loop_device);
2924 assert(ret_decrypted_image);
2925
2926 r = verity_settings_load(&verity, image, NULL, NULL);
2927 if (r < 0)
2928 return log_error_errno(r, "Failed to load root hash data: %m");
2929
2930 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
2931 if (r < 0)
2932 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
2933
2934 r = loop_device_make_by_path(
2935 image,
2936 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
2937 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2938 &d);
2939 if (r < 0)
2940 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
2941
2942 r = dissect_image_and_warn(d->fd, image, &verity, NULL, d->diskseq, d->uevent_seqnum_not_before, d->timestamp_not_before, flags, &dissected_image);
2943 if (r < 0)
2944 return r;
2945
2946 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags, &decrypted_image);
2947 if (r < 0)
2948 return r;
2949
2950 r = detach_mount_namespace();
2951 if (r < 0)
2952 return log_error_errno(r, "Failed to detach mount namespace: %m");
2953
2954 r = mkdir_p(temp, 0700);
2955 if (r < 0)
2956 return log_error_errno(r, "Failed to create mount point: %m");
2957
2958 created_dir = TAKE_PTR(temp);
2959
2960 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, UID_INVALID, flags);
2961 if (r < 0)
2962 return r;
2963
2964 if (decrypted_image) {
2965 r = decrypted_image_relinquish(decrypted_image);
2966 if (r < 0)
2967 return log_error_errno(r, "Failed to relinquish DM devices: %m");
2968 }
2969
2970 loop_device_relinquish(d);
2971
2972 *ret_directory = TAKE_PTR(created_dir);
2973 *ret_loop_device = TAKE_PTR(d);
2974 *ret_decrypted_image = TAKE_PTR(decrypted_image);
2975
2976 return 0;
2977 }
2978
2979 static const char *const partition_designator_table[] = {
2980 [PARTITION_ROOT] = "root",
2981 [PARTITION_ROOT_SECONDARY] = "root-secondary",
2982 [PARTITION_USR] = "usr",
2983 [PARTITION_USR_SECONDARY] = "usr-secondary",
2984 [PARTITION_HOME] = "home",
2985 [PARTITION_SRV] = "srv",
2986 [PARTITION_ESP] = "esp",
2987 [PARTITION_XBOOTLDR] = "xbootldr",
2988 [PARTITION_SWAP] = "swap",
2989 [PARTITION_ROOT_VERITY] = "root-verity",
2990 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
2991 [PARTITION_USR_VERITY] = "usr-verity",
2992 [PARTITION_USR_SECONDARY_VERITY] = "usr-secondary-verity",
2993 [PARTITION_TMP] = "tmp",
2994 [PARTITION_VAR] = "var",
2995 };
2996
2997 int verity_dissect_and_mount(
2998 const char *src,
2999 const char *dest,
3000 const MountOptions *options,
3001 const char *required_host_os_release_id,
3002 const char *required_host_os_release_version_id,
3003 const char *required_host_os_release_sysext_level) {
3004
3005 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
3006 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
3007 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3008 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3009 DissectImageFlags dissect_image_flags;
3010 int r;
3011
3012 assert(src);
3013 assert(dest);
3014
3015 r = verity_settings_load(&verity, src, NULL, NULL);
3016 if (r < 0)
3017 return log_debug_errno(r, "Failed to load root hash: %m");
3018
3019 dissect_image_flags = verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0;
3020
3021 r = loop_device_make_by_path(
3022 src,
3023 -1,
3024 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
3025 &loop_device);
3026 if (r < 0)
3027 return log_debug_errno(r, "Failed to create loop device for image: %m");
3028
3029 r = dissect_image(
3030 loop_device->fd,
3031 &verity,
3032 options,
3033 loop_device->diskseq,
3034 loop_device->uevent_seqnum_not_before,
3035 loop_device->timestamp_not_before,
3036 dissect_image_flags,
3037 &dissected_image);
3038 /* No partition table? Might be a single-filesystem image, try again */
3039 if (!verity.data_path && r == -ENOPKG)
3040 r = dissect_image(
3041 loop_device->fd,
3042 &verity,
3043 options,
3044 loop_device->diskseq,
3045 loop_device->uevent_seqnum_not_before,
3046 loop_device->timestamp_not_before,
3047 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
3048 &dissected_image);
3049 if (r < 0)
3050 return log_debug_errno(r, "Failed to dissect image: %m");
3051
3052 r = dissected_image_decrypt(
3053 dissected_image,
3054 NULL,
3055 &verity,
3056 dissect_image_flags,
3057 &decrypted_image);
3058 if (r < 0)
3059 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
3060
3061 r = mkdir_p_label(dest, 0755);
3062 if (r < 0)
3063 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
3064 r = umount_recursive(dest, 0);
3065 if (r < 0)
3066 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
3067
3068 r = dissected_image_mount(dissected_image, dest, UID_INVALID, UID_INVALID, dissect_image_flags);
3069 if (r < 0)
3070 return log_debug_errno(r, "Failed to mount image: %m");
3071
3072 /* If we got os-release values from the caller, then we need to match them with the image's
3073 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3074 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3075 * available, or else fallback to VERSION_ID. */
3076 if (required_host_os_release_id &&
3077 (required_host_os_release_version_id || required_host_os_release_sysext_level)) {
3078 _cleanup_strv_free_ char **extension_release = NULL;
3079
3080 r = load_extension_release_pairs(dest, dissected_image->image_name, &extension_release);
3081 if (r < 0)
3082 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
3083
3084 r = extension_release_validate(
3085 dissected_image->image_name,
3086 required_host_os_release_id,
3087 required_host_os_release_version_id,
3088 required_host_os_release_sysext_level,
3089 extension_release);
3090 if (r == 0)
3091 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
3092 if (r < 0)
3093 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
3094 }
3095
3096 if (decrypted_image) {
3097 r = decrypted_image_relinquish(decrypted_image);
3098 if (r < 0)
3099 return log_debug_errno(r, "Failed to relinquish decrypted image: %m");
3100 }
3101
3102 loop_device_relinquish(loop_device);
3103
3104 return 0;
3105 }
3106
3107 DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);