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