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