]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
loop-util: LOOP_CLR_FD is async, don't retry to reuse a device right after issuing it
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
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"
8c1be37e 26#include "dissect-image.h"
a709a315 27#include "dm-util.h"
686d13b9 28#include "env-file.h"
18b5886e 29#include "fd-util.h"
78ebe980 30#include "fileio.h"
2eedfd2d 31#include "fs-util.h"
cf32c486 32#include "fsck-util.h"
8c1be37e 33#include "gpt.h"
78ebe980 34#include "hexdecoct.h"
3b925504
LP
35#include "hostname-util.h"
36#include "id128-util.h"
6aa05ebd 37#include "mkdir.h"
8c1be37e 38#include "mount-util.h"
e4de7287 39#include "mountpoint-util.h"
6aa05ebd 40#include "namespace-util.h"
d8b4d14d 41#include "nulstr-util.h"
d58ad743 42#include "os-util.h"
8c1be37e 43#include "path-util.h"
3b925504
LP
44#include "process-util.h"
45#include "raw-clone.h"
46#include "signal-util.h"
8c1be37e 47#include "stat-util.h"
18b5886e 48#include "stdio-util.h"
8c1be37e
LP
49#include "string-table.h"
50#include "string-util.h"
2eedfd2d 51#include "strv.h"
e4de7287 52#include "tmpfile-util.h"
a8040b6d 53#include "udev-util.h"
2d3a5a73 54#include "user-util.h"
41488e1f 55#include "xattr-util.h"
8c1be37e 56
28e2641a
FF
57/* how many times to wait for the device nodes to appear */
58#define N_DEVICE_NODE_LIST_ATTEMPTS 10
59
c34b75a1 60int probe_filesystem(const char *node, char **ret_fstype) {
7cc84b2c 61 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
5238e957 62 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
7cc84b2c
ZJS
63 * different error otherwise. */
64
349cc4a5 65#if HAVE_BLKID
8e766630 66 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
18b5886e
LP
67 const char *fstype;
68 int r;
69
995fa2e5 70 errno = 0;
18b5886e
LP
71 b = blkid_new_probe_from_filename(node);
72 if (!b)
66855de7 73 return errno_or_else(ENOMEM);
18b5886e
LP
74
75 blkid_probe_enable_superblocks(b, 1);
76 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
77
78 errno = 0;
79 r = blkid_do_safeprobe(b);
7cc84b2c
ZJS
80 if (r == 1) {
81 log_debug("No type detected on partition %s", node);
18b5886e
LP
82 goto not_found;
83 }
58dfbfbd
LP
84 if (r == -2)
85 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
86 "Results ambiguous for partition %s", node);
b382db9f 87 if (r != 0)
66855de7 88 return errno_or_else(EIO);
18b5886e
LP
89
90 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
91
92 if (fstype) {
93 char *t;
94
95 t = strdup(fstype);
96 if (!t)
97 return -ENOMEM;
98
99 *ret_fstype = t;
100 return 1;
101 }
102
103not_found:
104 *ret_fstype = NULL;
105 return 0;
d1c536f5
ZJS
106#else
107 return -EOPNOTSUPP;
a75e27eb 108#endif
d1c536f5 109}
18b5886e 110
40c10d3f 111#if HAVE_BLKID
cde942f6
JPRV
112/* Detect RPMB and Boot partitions, which are not listed by blkid.
113 * See https://github.com/systemd/systemd/issues/5806. */
3c1f2cee 114static bool device_is_mmc_special_partition(sd_device *d) {
aae22eb3
LP
115 const char *sysname;
116
f70e7f70
LP
117 assert(d);
118
3c1f2cee
YW
119 if (sd_device_get_sysname(d, &sysname) < 0)
120 return false;
121
122 return startswith(sysname, "mmcblk") &&
0cfa78dd 123 (endswith(sysname, "rpmb") || endswith(sysname, "boot0") || endswith(sysname, "boot1"));
cde942f6
JPRV
124}
125
3c1f2cee 126static bool device_is_block(sd_device *d) {
aae22eb3
LP
127 const char *ss;
128
f70e7f70
LP
129 assert(d);
130
3c1f2cee 131 if (sd_device_get_subsystem(d, &ss) < 0)
aae22eb3
LP
132 return false;
133
134 return streq(ss, "block");
135}
ea887be0
ZJS
136
137static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
138 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
139 int r;
140
f70e7f70
LP
141 assert(d);
142 assert(ret);
143
ea887be0
ZJS
144 r = sd_device_enumerator_new(&e);
145 if (r < 0)
146 return r;
147
148 r = sd_device_enumerator_allow_uninitialized(e);
149 if (r < 0)
150 return r;
151
152 r = sd_device_enumerator_add_match_parent(e, d);
153 if (r < 0)
154 return r;
155
156 *ret = TAKE_PTR(e);
157 return 0;
158}
159
ea887be0
ZJS
160static int wait_for_partitions_to_appear(
161 int fd,
162 sd_device *d,
163 unsigned num_partitions,
052eaf5c 164 DissectImageFlags flags,
ea887be0
ZJS
165 sd_device_enumerator **ret_enumerator) {
166
167 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
168 sd_device *q;
169 unsigned n;
170 int r;
171
f70e7f70
LP
172 assert(fd >= 0);
173 assert(d);
174 assert(ret_enumerator);
175
ea887be0
ZJS
176 r = enumerator_for_parent(d, &e);
177 if (r < 0)
178 return r;
179
180 /* Count the partitions enumerated by the kernel */
181 n = 0;
182 FOREACH_DEVICE(e, q) {
183 if (sd_device_get_devnum(q, NULL) < 0)
184 continue;
185 if (!device_is_block(q))
186 continue;
187 if (device_is_mmc_special_partition(q))
188 continue;
189
052eaf5c 190 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
1b47436e 191 r = device_wait_for_initialization(q, "block", USEC_INFINITY, NULL);
052eaf5c
LP
192 if (r < 0)
193 return r;
194 }
a8040b6d 195
ea887be0
ZJS
196 n++;
197 }
198
199 if (n == num_partitions + 1) {
200 *ret_enumerator = TAKE_PTR(e);
201 return 0; /* success! */
202 }
203 if (n > num_partitions + 1)
204 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
205 "blkid and kernel partition lists do not match.");
206
207 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
208 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
209 * call that waits until probing is complete. */
210
211 for (unsigned j = 0; ; j++) {
212 if (j++ > 20)
213 return -EBUSY;
214
215 if (ioctl(fd, BLKRRPART, 0) >= 0)
216 break;
217 r = -errno;
218 if (r == -EINVAL) {
834c15ec
LP
219 /* If we are running on a block device that has partition scanning off, return an
220 * explicit recognizable error about this, so that callers can generate a proper
221 * message explaining the situation. */
ea887be0 222
834c15ec
LP
223 r = blockdev_partscan_enabled(fd);
224 if (r < 0)
225 return r;
226 if (r == 0)
d7a0f1f4 227 return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
834c15ec 228 "Device is a loop device and partition scanning is off!");
10c1b188 229
834c15ec 230 return -EINVAL; /* original error */
ea887be0
ZJS
231 }
232 if (r != -EBUSY)
233 return r;
234
235 /* If something else has the device open, such as an udev rule, the ioctl will return
236 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
237 * and try again.
238 *
239 * This is really something they should fix in the kernel! */
240 (void) usleep(50 * USEC_PER_MSEC);
241
242 }
243
244 return -EAGAIN; /* no success yet, try again */
245}
246
247static int loop_wait_for_partitions_to_appear(
248 int fd,
249 sd_device *d,
250 unsigned num_partitions,
052eaf5c 251 DissectImageFlags flags,
ea887be0 252 sd_device_enumerator **ret_enumerator) {
a8040b6d 253 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
ea887be0
ZJS
254 int r;
255
f70e7f70
LP
256 assert(fd >= 0);
257 assert(d);
258 assert(ret_enumerator);
259
b887c8b8
ZJS
260 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions);
261
052eaf5c 262 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
1b47436e 263 r = device_wait_for_initialization(d, "block", USEC_INFINITY, &device);
052eaf5c
LP
264 if (r < 0)
265 return r;
266 } else
267 device = sd_device_ref(d);
a8040b6d 268
ea887be0 269 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
052eaf5c 270 r = wait_for_partitions_to_appear(fd, device, num_partitions, flags, ret_enumerator);
ea887be0
ZJS
271 if (r != -EAGAIN)
272 return r;
273 }
274
275 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO),
276 "Kernel partitions dit not appear within %d attempts",
277 N_DEVICE_NODE_LIST_ATTEMPTS);
278}
279
0f7c9a3d
LP
280static void check_partition_flags(
281 const char *node,
282 unsigned long long pflags,
283 unsigned long long supported) {
284
285 assert(node);
286
287 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
288 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
289
290 if (pflags == 0)
291 return;
292
293 /* If there are other bits set, then log about it, to make things discoverable */
294 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
295 unsigned long long bit = 1ULL << i;
296 if (!FLAGS_SET(pflags, bit))
297 continue;
298
299 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
300 }
301}
302
40c10d3f 303#endif
aae22eb3 304
4526113f
LP
305int dissect_image(
306 int fd,
89e62e0b 307 const VeritySettings *verity,
18d73705 308 const MountOptions *mount_options,
4526113f
LP
309 DissectImageFlags flags,
310 DissectedImage **ret) {
8c1be37e 311
349cc4a5 312#if HAVE_BLKID
aee36b4e
LP
313 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL,
314 usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
3c1f2cee 315 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
8c1be37e 316 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
3c1f2cee 317 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
8c1be37e 318 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
8e766630 319 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
8c1be37e 320 _cleanup_free_ char *generic_node = NULL;
be30ad41 321 sd_id128_t generic_uuid = SD_ID128_NULL;
9b6deb03 322 const char *pttype = NULL;
8c1be37e
LP
323 blkid_partlist pl;
324 int r, generic_nr;
325 struct stat st;
3c1f2cee 326 sd_device *q;
8c1be37e
LP
327
328 assert(fd >= 0);
329 assert(ret);
89e62e0b 330 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
e7cbe5cb 331 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
8c1be37e
LP
332
333 /* Probes a disk image, and returns information about what it found in *ret.
334 *
4623e8e6
LP
335 * Returns -ENOPKG if no suitable partition table or file system could be found.
336 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
337
89e62e0b 338 if (verity && verity->root_hash) {
aee36b4e
LP
339 sd_id128_t fsuuid, vuuid;
340
341 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
342 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
343 * the final 128bit. */
4623e8e6 344
89e62e0b 345 if (verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
346 return -EINVAL;
347
aee36b4e
LP
348 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
349 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
4623e8e6 350
aee36b4e 351 if (sd_id128_is_null(fsuuid))
4623e8e6 352 return -EINVAL;
aee36b4e 353 if (sd_id128_is_null(vuuid))
4623e8e6 354 return -EINVAL;
aee36b4e
LP
355
356 /* If the verity data declares it's for the /usr partition, then search for that, in all
357 * other cases assume it's for the root partition. */
358 if (verity->designator == PARTITION_USR) {
359 usr_uuid = fsuuid;
360 usr_verity_uuid = vuuid;
361 } else {
362 root_uuid = fsuuid;
363 root_verity_uuid = vuuid;
364 }
4623e8e6 365 }
8c1be37e
LP
366
367 if (fstat(fd, &st) < 0)
368 return -errno;
369
370 if (!S_ISBLK(st.st_mode))
371 return -ENOTBLK;
372
373 b = blkid_new_probe();
374 if (!b)
375 return -ENOMEM;
376
377 errno = 0;
378 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f 379 if (r != 0)
66855de7 380 return errno_or_else(ENOMEM);
8c1be37e 381
9b6deb03
LP
382 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
383 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
384 blkid_probe_enable_superblocks(b, 1);
385 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
386 }
387
8c1be37e
LP
388 blkid_probe_enable_partitions(b, 1);
389 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
390
391 errno = 0;
392 r = blkid_do_safeprobe(b);
59ba6d0c
LP
393 if (IN_SET(r, -2, 1))
394 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
b382db9f 395 if (r != 0)
66855de7 396 return errno_or_else(EIO);
8c1be37e
LP
397
398 m = new0(DissectedImage, 1);
399 if (!m)
400 return -ENOMEM;
401
b887c8b8
ZJS
402 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
403 if (r < 0)
404 return r;
405
e7cbe5cb
LB
406 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
407 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) ||
408 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
9b6deb03 409 const char *usage = NULL;
8c1be37e 410
aee36b4e
LP
411 /* If flags permit this, also allow using non-partitioned single-filesystem images */
412
9b6deb03
LP
413 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
414 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
18d73705
LB
415 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
416 const char *fstype = NULL, *options = NULL;
8c1be37e 417
9b6deb03
LP
418 /* OK, we have found a file system, that's our root partition then. */
419 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 420
9b6deb03
LP
421 if (fstype) {
422 t = strdup(fstype);
423 if (!t)
424 return -ENOMEM;
425 }
426
54b22b26
LP
427 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
428 if (r < 0)
429 return r;
8c1be37e 430
e7cbe5cb 431 m->single_file_system = true;
aee36b4e 432 m->verity = verity && verity->root_hash && verity->data_path && (verity->designator < 0 || verity->designator == PARTITION_ROOT);
89e62e0b 433 m->can_verity = verity && verity->data_path;
e7cbe5cb 434
f5215bc8 435 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
436 if (options) {
437 o = strdup(options);
438 if (!o)
439 return -ENOMEM;
440 }
441
9b6deb03
LP
442 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
443 .found = true,
e7cbe5cb 444 .rw = !m->verity,
9b6deb03
LP
445 .partno = -1,
446 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
447 .fstype = TAKE_PTR(t),
448 .node = TAKE_PTR(n),
18d73705 449 .mount_options = TAKE_PTR(o),
9b6deb03 450 };
8c1be37e 451
4db1879a 452 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
18b5886e 453
b1806441
LB
454 /* Even on a single partition we need to wait for udev to create the
455 * /dev/block/X:Y symlink to /dev/loopZ */
456 r = loop_wait_for_partitions_to_appear(fd, d, 0, flags, &e);
457 if (r < 0)
458 return r;
1cc6c93a 459 *ret = TAKE_PTR(m);
8c1be37e 460
9b6deb03
LP
461 return 0;
462 }
8c1be37e
LP
463 }
464
465 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
466 if (!pttype)
467 return -ENOPKG;
468
469 is_gpt = streq_ptr(pttype, "gpt");
470 is_mbr = streq_ptr(pttype, "dos");
471
9b6deb03 472 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
473 return -ENOPKG;
474
475 errno = 0;
476 pl = blkid_probe_get_partitions(b);
b382db9f 477 if (!pl)
66855de7 478 return errno_or_else(ENOMEM);
8c1be37e 479
052eaf5c 480 r = loop_wait_for_partitions_to_appear(fd, d, blkid_partlist_numof_partitions(pl), flags, &e);
ea887be0
ZJS
481 if (r < 0)
482 return r;
8c1be37e 483
8437c059 484 FOREACH_DEVICE(e, q) {
9b6deb03 485 unsigned long long pflags;
8c1be37e 486 blkid_partition pp;
cde942f6 487 const char *node;
8c1be37e
LP
488 dev_t qn;
489 int nr;
490
3c1f2cee
YW
491 r = sd_device_get_devnum(q, &qn);
492 if (r < 0)
8c1be37e
LP
493 continue;
494
495 if (st.st_rdev == qn)
496 continue;
497
aae22eb3
LP
498 if (!device_is_block(q))
499 continue;
500
cde942f6 501 if (device_is_mmc_special_partition(q))
7be1420f
LP
502 continue;
503
3c1f2cee
YW
504 r = sd_device_get_devname(q, &node);
505 if (r < 0)
8c1be37e
LP
506 continue;
507
508 pp = blkid_partlist_devno_to_partition(pl, qn);
509 if (!pp)
510 continue;
511
9b6deb03 512 pflags = blkid_partition_get_flags(pp);
8c1be37e
LP
513
514 nr = blkid_partition_get_partno(pp);
515 if (nr < 0)
516 continue;
517
518 if (is_gpt) {
569a0e42
LP
519 PartitionDesignator designator = _PARTITION_DESIGNATOR_INVALID;
520 int architecture = _ARCHITECTURE_INVALID;
4623e8e6
LP
521 const char *stype, *sid, *fstype = NULL;
522 sd_id128_t type_id, id;
8c1be37e
LP
523 bool rw = true;
524
4623e8e6
LP
525 sid = blkid_partition_get_uuid(pp);
526 if (!sid)
527 continue;
528 if (sd_id128_from_string(sid, &id) < 0)
529 continue;
530
8c1be37e
LP
531 stype = blkid_partition_get_type_string(pp);
532 if (!stype)
533 continue;
8c1be37e
LP
534 if (sd_id128_from_string(stype, &type_id) < 0)
535 continue;
536
537 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347 538
0f7c9a3d
LP
539 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
540
a48dd347
LP
541 if (pflags & GPT_FLAG_NO_AUTO)
542 continue;
543
8c1be37e 544 designator = PARTITION_HOME;
9b6deb03 545 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 546
8c1be37e 547 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347 548
0f7c9a3d
LP
549 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
550
a48dd347
LP
551 if (pflags & GPT_FLAG_NO_AUTO)
552 continue;
553
8c1be37e 554 designator = PARTITION_SRV;
9b6deb03 555 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 556
8c1be37e 557 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347 558
aee36b4e
LP
559 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is
560 * not defined there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
561 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
562 * Partitions"). */
a48dd347
LP
563
564 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
565 continue;
566
8c1be37e
LP
567 designator = PARTITION_ESP;
568 fstype = "vfat";
a8c47660
LP
569
570 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
571
0f7c9a3d
LP
572 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
573
a8c47660
LP
574 if (pflags & GPT_FLAG_NO_AUTO)
575 continue;
576
577 designator = PARTITION_XBOOTLDR;
578 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
579 }
580#ifdef GPT_ROOT_NATIVE
581 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 582
0f7c9a3d
LP
583 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
584
a48dd347
LP
585 if (pflags & GPT_FLAG_NO_AUTO)
586 continue;
587
4623e8e6
LP
588 /* If a root ID is specified, ignore everything but the root id */
589 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
590 continue;
591
8c1be37e
LP
592 designator = PARTITION_ROOT;
593 architecture = native_architecture();
9b6deb03 594 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 595
4f8b86e3 596 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 597
0f7c9a3d
LP
598 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
599
a48dd347
LP
600 if (pflags & GPT_FLAG_NO_AUTO)
601 continue;
602
4623e8e6
LP
603 m->can_verity = true;
604
605 /* Ignore verity unless a root hash is specified */
aee36b4e 606 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
4623e8e6
LP
607 continue;
608
609 designator = PARTITION_ROOT_VERITY;
610 fstype = "DM_verity_hash";
611 architecture = native_architecture();
612 rw = false;
613 }
614#endif
8c1be37e
LP
615#ifdef GPT_ROOT_SECONDARY
616 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 617
0f7c9a3d
LP
618 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
619
a48dd347
LP
620 if (pflags & GPT_FLAG_NO_AUTO)
621 continue;
622
4623e8e6
LP
623 /* If a root ID is specified, ignore everything but the root id */
624 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
625 continue;
626
8c1be37e
LP
627 designator = PARTITION_ROOT_SECONDARY;
628 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 629 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 630
4f8b86e3 631 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347 632
0f7c9a3d
LP
633 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
634
a48dd347
LP
635 if (pflags & GPT_FLAG_NO_AUTO)
636 continue;
637
4623e8e6
LP
638 m->can_verity = true;
639
640 /* Ignore verity unless root has is specified */
aee36b4e 641 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
4623e8e6
LP
642 continue;
643
644 designator = PARTITION_ROOT_SECONDARY_VERITY;
645 fstype = "DM_verity_hash";
646 architecture = SECONDARY_ARCHITECTURE;
647 rw = false;
648 }
aee36b4e
LP
649#endif
650#ifdef GPT_USR_NATIVE
651 else if (sd_id128_equal(type_id, GPT_USR_NATIVE)) {
652
653 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
654
655 if (pflags & GPT_FLAG_NO_AUTO)
656 continue;
657
658 /* If a usr ID is specified, ignore everything but the usr id */
659 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
660 continue;
661
662 designator = PARTITION_USR;
663 architecture = native_architecture();
664 rw = !(pflags & GPT_FLAG_READ_ONLY);
665
666 } else if (sd_id128_equal(type_id, GPT_USR_NATIVE_VERITY)) {
667
668 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
669
670 if (pflags & GPT_FLAG_NO_AUTO)
671 continue;
672
673 m->can_verity = true;
674
675 /* Ignore verity unless a usr hash is specified */
676 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
677 continue;
678
679 designator = PARTITION_USR_VERITY;
680 fstype = "DM_verity_hash";
681 architecture = native_architecture();
682 rw = false;
683 }
684#endif
685#ifdef GPT_USR_SECONDARY
686 else if (sd_id128_equal(type_id, GPT_USR_SECONDARY)) {
687
688 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
689
690 if (pflags & GPT_FLAG_NO_AUTO)
691 continue;
692
693 /* If a usr ID is specified, ignore everything but the usr id */
694 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
695 continue;
696
697 designator = PARTITION_USR_SECONDARY;
698 architecture = SECONDARY_ARCHITECTURE;
699 rw = !(pflags & GPT_FLAG_READ_ONLY);
700
701 } else if (sd_id128_equal(type_id, GPT_USR_SECONDARY_VERITY)) {
702
703 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
704
705 if (pflags & GPT_FLAG_NO_AUTO)
706 continue;
707
708 m->can_verity = true;
709
710 /* Ignore verity unless usr has is specified */
711 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
712 continue;
713
714 designator = PARTITION_USR_SECONDARY_VERITY;
715 fstype = "DM_verity_hash";
716 architecture = SECONDARY_ARCHITECTURE;
717 rw = false;
718 }
8c1be37e
LP
719#endif
720 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347 721
0f7c9a3d
LP
722 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
723
a48dd347
LP
724 if (pflags & GPT_FLAG_NO_AUTO)
725 continue;
726
8c1be37e
LP
727 designator = PARTITION_SWAP;
728 fstype = "swap";
aee36b4e 729
8c1be37e
LP
730 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
731
0f7c9a3d
LP
732 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
733
a48dd347
LP
734 if (pflags & GPT_FLAG_NO_AUTO)
735 continue;
736
8c1be37e
LP
737 if (generic_node)
738 multiple_generic = true;
739 else {
740 generic_nr = nr;
9b6deb03 741 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
be30ad41 742 generic_uuid = id;
8c1be37e
LP
743 generic_node = strdup(node);
744 if (!generic_node)
745 return -ENOMEM;
746 }
d4dffb85
LP
747
748 } else if (sd_id128_equal(type_id, GPT_TMP)) {
749
0f7c9a3d
LP
750 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
751
d4dffb85
LP
752 if (pflags & GPT_FLAG_NO_AUTO)
753 continue;
754
755 designator = PARTITION_TMP;
756 rw = !(pflags & GPT_FLAG_READ_ONLY);
757
758 } else if (sd_id128_equal(type_id, GPT_VAR)) {
759
0f7c9a3d
LP
760 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
761
d4dffb85
LP
762 if (pflags & GPT_FLAG_NO_AUTO)
763 continue;
764
765 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
766 sd_id128_t var_uuid;
767
768 /* For /var we insist that the uuid of the partition matches the
769 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
770 * ID. Why? Unlike the other partitions /var is inherently
771 * installation specific, hence we need to be careful not to mount it
772 * in the wrong installation. By hashing the partition UUID from
773 * /etc/machine-id we can securely bind the partition to the
774 * installation. */
775
776 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
777 if (r < 0)
778 return r;
779
780 if (!sd_id128_equal(var_uuid, id)) {
781 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
782 continue;
783 }
784 }
785
786 designator = PARTITION_VAR;
787 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
788 }
789
790 if (designator != _PARTITION_DESIGNATOR_INVALID) {
18d73705
LB
791 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
792 const char *options = NULL;
8c1be37e
LP
793
794 /* First one wins */
795 if (m->partitions[designator].found)
796 continue;
797
798 if (fstype) {
799 t = strdup(fstype);
800 if (!t)
801 return -ENOMEM;
802 }
803
804 n = strdup(node);
805 if (!n)
806 return -ENOMEM;
807
f5215bc8 808 options = mount_options_from_designator(mount_options, designator);
18d73705
LB
809 if (options) {
810 o = strdup(options);
811 if (!o)
812 return -ENOMEM;
813 }
814
8c1be37e
LP
815 m->partitions[designator] = (DissectedPartition) {
816 .found = true,
817 .partno = nr,
818 .rw = rw,
819 .architecture = architecture,
1cc6c93a
YW
820 .node = TAKE_PTR(n),
821 .fstype = TAKE_PTR(t),
be30ad41 822 .uuid = id,
18d73705 823 .mount_options = TAKE_PTR(o),
8c1be37e 824 };
8c1be37e
LP
825 }
826
827 } else if (is_mbr) {
828
a8c47660 829 switch (blkid_partition_get_type(pp)) {
8c1be37e 830
a8c47660
LP
831 case 0x83: /* Linux partition */
832
833 if (pflags != 0x80) /* Bootable flag */
834 continue;
8c1be37e 835
a8c47660
LP
836 if (generic_node)
837 multiple_generic = true;
838 else {
839 generic_nr = nr;
840 generic_rw = true;
841 generic_node = strdup(node);
842 if (!generic_node)
843 return -ENOMEM;
844 }
845
846 break;
847
848 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
18d73705 849 _cleanup_free_ char *n = NULL, *o = NULL;
a8c47660 850 sd_id128_t id = SD_ID128_NULL;
18d73705 851 const char *sid, *options = NULL;
a8c47660
LP
852
853 /* First one wins */
854 if (m->partitions[PARTITION_XBOOTLDR].found)
855 continue;
856
857 sid = blkid_partition_get_uuid(pp);
858 if (sid)
859 (void) sd_id128_from_string(sid, &id);
860
861 n = strdup(node);
862 if (!n)
8c1be37e 863 return -ENOMEM;
a8c47660 864
f5215bc8 865 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
18d73705
LB
866 if (options) {
867 o = strdup(options);
868 if (!o)
869 return -ENOMEM;
870 }
871
a8c47660
LP
872 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
873 .found = true,
874 .partno = nr,
875 .rw = true,
876 .architecture = _ARCHITECTURE_INVALID,
877 .node = TAKE_PTR(n),
878 .uuid = id,
18d73705 879 .mount_options = TAKE_PTR(o),
a8c47660
LP
880 };
881
882 break;
883 }}
8c1be37e
LP
884 }
885 }
886
74cb2db9
LP
887 if (m->partitions[PARTITION_ROOT].found) {
888 /* If we found the primary arch, then invalidate the secondary arch to avoid any ambiguities,
889 * since we never want to mount the secondary arch in this case. */
890 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
891 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
aee36b4e
LP
892 m->partitions[PARTITION_USR_SECONDARY].found = false;
893 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
74cb2db9 894 } else {
8c1be37e
LP
895 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
896 * either, then check if there's a single generic one, and use that. */
897
4623e8e6 898 if (m->partitions[PARTITION_ROOT_VERITY].found)
e0f9e7bd 899 return -EADDRNOTAVAIL;
4623e8e6 900
aee36b4e
LP
901 /* We didn't find a primary architecture root, but we found a primary architecture /usr? Refuse that for now. */
902 if (m->partitions[PARTITION_USR].found || m->partitions[PARTITION_USR_VERITY].found)
903 return -EADDRNOTAVAIL;
904
8c1be37e 905 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
aee36b4e 906 /* Upgrade secondary arch to first */
8c1be37e
LP
907 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
908 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
4623e8e6
LP
909 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
910 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
911
aee36b4e
LP
912 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
913 zero(m->partitions[PARTITION_USR_SECONDARY]);
914 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
915 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
916
e0f9e7bd 917 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
18d73705
LB
918 _cleanup_free_ char *o = NULL;
919 const char *options = NULL;
e0f9e7bd 920
2aed63f4
ZJS
921 /* If the root hash was set, then we won't fall back to a generic node, because the
922 * root hash decides. */
89e62e0b 923 if (verity && verity->root_hash)
e0f9e7bd 924 return -EADDRNOTAVAIL;
8c1be37e 925
e0f9e7bd
LP
926 /* If we didn't find a generic node, then we can't fix this up either */
927 if (!generic_node)
928 return -ENXIO;
929
930 /* If we didn't find a properly marked root partition, but we did find a single suitable
931 * generic Linux partition, then use this as root partition, if the caller asked for it. */
8c1be37e
LP
932 if (multiple_generic)
933 return -ENOTUNIQ;
934
f5215bc8 935 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
936 if (options) {
937 o = strdup(options);
938 if (!o)
939 return -ENOMEM;
940 }
941
8c1be37e
LP
942 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
943 .found = true,
944 .rw = generic_rw,
945 .partno = generic_nr,
946 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 947 .node = TAKE_PTR(generic_node),
be30ad41 948 .uuid = generic_uuid,
18d73705 949 .mount_options = TAKE_PTR(o),
8c1be37e 950 };
e0f9e7bd 951 }
8c1be37e
LP
952 }
953
aee36b4e
LP
954 /* Refuse if we found a verity partition for /usr but no matching file system partition */
955 if (!m->partitions[PARTITION_USR].found && m->partitions[PARTITION_USR_VERITY].found)
956 return -EADDRNOTAVAIL;
957
958 /* Combinations of verity /usr with verity-less root is OK, but the reverse is not */
c848516f 959 if (m->partitions[PARTITION_ROOT_VERITY].found && m->partitions[PARTITION_USR].found && !m->partitions[PARTITION_USR_VERITY].found)
aee36b4e
LP
960 return -EADDRNOTAVAIL;
961
89e62e0b 962 if (verity && verity->root_hash) {
aee36b4e
LP
963 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
964 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
965 return -EADDRNOTAVAIL;
966
967 /* If we found a verity setup, then the root partition is necessarily read-only. */
968 m->partitions[PARTITION_ROOT].rw = false;
969 m->verity = true;
970 }
4623e8e6 971
aee36b4e
LP
972 if (verity->designator == PARTITION_USR) {
973 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
974 return -EADDRNOTAVAIL;
4623e8e6 975
aee36b4e
LP
976 m->partitions[PARTITION_USR].rw = false;
977 m->verity = true;
978 }
4623e8e6
LP
979 }
980
18b5886e
LP
981 blkid_free_probe(b);
982 b = NULL;
983
8c1be37e 984 /* Fill in file system types if we don't know them yet. */
569a0e42 985 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 986 DissectedPartition *p = m->partitions + i;
8c1be37e 987
18b5886e 988 if (!p->found)
8c1be37e
LP
989 continue;
990
18b5886e
LP
991 if (!p->fstype && p->node) {
992 r = probe_filesystem(p->node, &p->fstype);
7cc84b2c 993 if (r < 0 && r != -EUCLEAN)
18b5886e 994 return r;
8c1be37e
LP
995 }
996
18b5886e
LP
997 if (streq_ptr(p->fstype, "crypto_LUKS"))
998 m->encrypted = true;
896f937f
LP
999
1000 if (p->fstype && fstype_is_ro(p->fstype))
1001 p->rw = false;
8c1be37e
LP
1002 }
1003
1cc6c93a 1004 *ret = TAKE_PTR(m);
8c1be37e
LP
1005 return 0;
1006#else
1007 return -EOPNOTSUPP;
1008#endif
1009}
1010
1011DissectedImage* dissected_image_unref(DissectedImage *m) {
8c1be37e
LP
1012 if (!m)
1013 return NULL;
1014
569a0e42 1015 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
8c1be37e
LP
1016 free(m->partitions[i].fstype);
1017 free(m->partitions[i].node);
18b5886e
LP
1018 free(m->partitions[i].decrypted_fstype);
1019 free(m->partitions[i].decrypted_node);
18d73705 1020 free(m->partitions[i].mount_options);
8c1be37e
LP
1021 }
1022
3b925504
LP
1023 free(m->hostname);
1024 strv_free(m->machine_info);
1025 strv_free(m->os_release);
1026
5fecf46d 1027 return mfree(m);
8c1be37e
LP
1028}
1029
18b5886e 1030static int is_loop_device(const char *path) {
553e15f2 1031 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
1032 struct stat st;
1033
1034 assert(path);
1035
1036 if (stat(path, &st) < 0)
1037 return -errno;
1038
1039 if (!S_ISBLK(st.st_mode))
1040 return -ENOTBLK;
1041
553e15f2 1042 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
1043 if (access(s, F_OK) < 0) {
1044 if (errno != ENOENT)
1045 return -errno;
1046
1047 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 1048 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
1049 if (access(s, F_OK) < 0)
1050 return errno == ENOENT ? false : -errno;
1051 }
1052
1053 return true;
1054}
1055
cf32c486
LP
1056static int run_fsck(const char *node, const char *fstype) {
1057 int r, exit_status;
1058 pid_t pid;
1059
1060 assert(node);
1061 assert(fstype);
1062
1063 r = fsck_exists(fstype);
1064 if (r < 0) {
1065 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1066 return 0;
1067 }
1068 if (r == 0) {
1069 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
1070 return 0;
1071 }
1072
1073 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
1074 if (r < 0)
1075 return log_debug_errno(r, "Failed to fork off fsck: %m");
1076 if (r == 0) {
1077 /* Child */
1078 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
1079 log_debug_errno(errno, "Failed to execl() fsck: %m");
1080 _exit(FSCK_OPERATIONAL_ERROR);
1081 }
1082
1083 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1084 if (exit_status < 0)
1085 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1086
1087 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1088 log_debug("fsck failed with exit status %i.", exit_status);
1089
1090 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1091 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1092
1093 log_debug("Ignoring fsck error.");
1094 }
1095
1096 return 0;
1097}
1098
18b5886e
LP
1099static int mount_partition(
1100 DissectedPartition *m,
1101 const char *where,
1102 const char *directory,
2d3a5a73 1103 uid_t uid_shift,
18b5886e
LP
1104 DissectImageFlags flags) {
1105
2d3a5a73
LP
1106 _cleanup_free_ char *chased = NULL, *options = NULL;
1107 const char *p, *node, *fstype;
8c1be37e 1108 bool rw;
2eedfd2d 1109 int r;
8c1be37e
LP
1110
1111 assert(m);
1112 assert(where);
1113
4dc28665 1114 /* Use decrypted node and matching fstype if available, otherwise use the original device */
18b5886e 1115 node = m->decrypted_node ?: m->node;
4dc28665 1116 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
18b5886e 1117
4dc28665 1118 if (!m->found || !node)
8c1be37e 1119 return 0;
4dc28665
LP
1120 if (!fstype)
1121 return -EAFNOSUPPORT;
8c1be37e 1122
fa45d12c 1123 /* 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 1124 if (streq(fstype, "crypto_LUKS"))
fa45d12c 1125 return -EUNATCH;
18b5886e
LP
1126
1127 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
8c1be37e 1128
cf32c486
LP
1129 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1130 r = run_fsck(node, fstype);
1131 if (r < 0)
1132 return r;
1133 }
1134
2eedfd2d 1135 if (directory) {
1f0f82f1
LP
1136 if (!FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY)) {
1137 /* Automatically create missing mount points, if necessary. */
1138 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1139 if (r < 0)
1140 return r;
1141 }
1142
a5648b80 1143 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2eedfd2d
LP
1144 if (r < 0)
1145 return r;
1146
1147 p = chased;
1148 } else
8c1be37e
LP
1149 p = where;
1150
18b5886e 1151 /* If requested, turn on discard support. */
154d2269 1152 if (fstype_can_discard(fstype) &&
18b5886e 1153 ((flags & DISSECT_IMAGE_DISCARD) ||
3afda7c7 1154 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
2d3a5a73
LP
1155 options = strdup("discard");
1156 if (!options)
1157 return -ENOMEM;
1158 }
1159
1160 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
1161 _cleanup_free_ char *uid_option = NULL;
1162
1163 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1164 return -ENOMEM;
1165
1166 if (!strextend_with_separator(&options, ",", uid_option, NULL))
1167 return -ENOMEM;
1168 }
8c1be37e 1169
18d73705
LB
1170 if (!isempty(m->mount_options))
1171 if (!strextend_with_separator(&options, ",", m->mount_options, NULL))
1172 return -ENOMEM;
1173
5c05f062
LP
1174 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1175 r = mkdir_p(p, 0755);
1176 if (r < 0)
1177 return r;
1178 }
1179
511a8cfe 1180 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
d9223c07
LP
1181 if (r < 0)
1182 return r;
1183
1184 return 1;
8c1be37e
LP
1185}
1186
2d3a5a73 1187int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1f0f82f1 1188 int r, xbootldr_mounted;
8c1be37e
LP
1189
1190 assert(m);
1191 assert(where);
1192
fa45d12c
LP
1193 /* Returns:
1194 *
1195 * -ENXIO → No root partition found
1196 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release file found
1197 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1198 * -EUCLEAN → fsck for file system failed
1199 * -EBUSY → File system already mounted/used elsewhere (kernel)
4dc28665 1200 * -EAFNOSUPPORT → File system type not supported or not known
fa45d12c
LP
1201 */
1202
8c1be37e
LP
1203 if (!m->partitions[PARTITION_ROOT].found)
1204 return -ENXIO;
1205
2d3a5a73
LP
1206 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1207 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
1208 if (r < 0)
1209 return r;
aee36b4e
LP
1210 }
1211
1212 /* Mask DISSECT_IMAGE_MKDIR for all subdirs: the idea is that only the top-level mount point is
1213 * created if needed, but the image itself not modified. */
1214 flags &= ~DISSECT_IMAGE_MKDIR;
1215
1216 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1217 /* For us mounting root always means mounting /usr as well */
1218 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, flags);
1219 if (r < 0)
1220 return r;
03bcb6d4
LP
1221
1222 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
1223 r = path_is_os_tree(where);
1224 if (r < 0)
1225 return r;
1226 if (r == 0)
1227 return -EMEDIUMTYPE;
1228 }
2d3a5a73
LP
1229 }
1230
705727fd 1231 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 1232 return 0;
8c1be37e 1233
2d3a5a73 1234 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
8c1be37e
LP
1235 if (r < 0)
1236 return r;
1237
2d3a5a73 1238 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
8c1be37e
LP
1239 if (r < 0)
1240 return r;
1241
d4dffb85
LP
1242 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, flags);
1243 if (r < 0)
1244 return r;
1245
1246 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, flags);
1247 if (r < 0)
1248 return r;
1249
1f0f82f1
LP
1250 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, flags);
1251 if (xbootldr_mounted < 0)
1252 return xbootldr_mounted;
d9223c07 1253
8c1be37e 1254 if (m->partitions[PARTITION_ESP].found) {
1f0f82f1
LP
1255 int esp_done = false;
1256
d9223c07
LP
1257 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1258 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
8c1be37e 1259
a5648b80 1260 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1f0f82f1
LP
1261 if (r < 0) {
1262 if (r != -ENOENT)
d9223c07 1263 return r;
8c1be37e 1264
1f0f82f1
LP
1265 /* /efi doesn't exist. Let's see if /boot is suitable then */
1266
1267 if (!xbootldr_mounted) {
1268 _cleanup_free_ char *p = NULL;
2eedfd2d 1269
1f0f82f1
LP
1270 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1271 if (r < 0) {
1272 if (r != -ENOENT)
1273 return r;
1274 } else if (dir_is_empty(p) > 0) {
1275 /* It exists and is an empty directory. Let's mount the ESP there. */
1276 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, flags);
1277 if (r < 0)
1278 return r;
1279
1280 esp_done = true;
1281 }
2eedfd2d 1282 }
8c1be37e 1283 }
1f0f82f1
LP
1284
1285 if (!esp_done) {
1286 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1287
1288 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, flags);
1289 if (r < 0)
1290 return r;
1291 }
8c1be37e
LP
1292 }
1293
1294 return 0;
1295}
1296
af187ab2
LP
1297int dissected_image_mount_and_warn(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1298 int r;
1299
1300 assert(m);
1301 assert(where);
1302
1303 r = dissected_image_mount(m, where, uid_shift, flags);
1304 if (r == -ENXIO)
1305 return log_error_errno(r, "Not root file system found in image.");
1306 if (r == -EMEDIUMTYPE)
1307 return log_error_errno(r, "No suitable os-release file in image found.");
1308 if (r == -EUNATCH)
1309 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1310 if (r == -EUCLEAN)
1311 return log_error_errno(r, "File system check on image failed.");
1312 if (r == -EBUSY)
1313 return log_error_errno(r, "File system already mounted elsewhere.");
4dc28665
LP
1314 if (r == -EAFNOSUPPORT)
1315 return log_error_errno(r, "File system type not supported or not known.");
af187ab2
LP
1316 if (r < 0)
1317 return log_error_errno(r, "Failed to mount image: %m");
1318
1319 return r;
1320}
1321
349cc4a5 1322#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1323typedef struct DecryptedPartition {
1324 struct crypt_device *device;
1325 char *name;
1326 bool relinquished;
1327} DecryptedPartition;
1328
1329struct DecryptedImage {
1330 DecryptedPartition *decrypted;
1331 size_t n_decrypted;
1332 size_t n_allocated;
1333};
1334#endif
1335
1336DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
349cc4a5 1337#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1338 size_t i;
1339 int r;
1340
1341 if (!d)
1342 return NULL;
1343
1344 for (i = 0; i < d->n_decrypted; i++) {
1345 DecryptedPartition *p = d->decrypted + i;
1346
1347 if (p->device && p->name && !p->relinquished) {
0d12936d 1348 r = sym_crypt_deactivate_by_name(p->device, p->name, 0);
18b5886e
LP
1349 if (r < 0)
1350 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1351 }
1352
1353 if (p->device)
0d12936d 1354 sym_crypt_free(p->device);
18b5886e
LP
1355 free(p->name);
1356 }
1357
1358 free(d);
1359#endif
1360 return NULL;
1361}
1362
349cc4a5 1363#if HAVE_LIBCRYPTSETUP
4623e8e6
LP
1364
1365static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1366 _cleanup_free_ char *name = NULL, *node = NULL;
1367 const char *base;
1368
1369 assert(original_node);
1370 assert(suffix);
1371 assert(ret_name);
1372 assert(ret_node);
1373
1374 base = strrchr(original_node, '/');
1375 if (!base)
ac1f3ad0
LB
1376 base = original_node;
1377 else
1378 base++;
4623e8e6
LP
1379 if (isempty(base))
1380 return -EINVAL;
1381
1382 name = strjoin(base, suffix);
1383 if (!name)
1384 return -ENOMEM;
1385 if (!filename_is_valid(name))
1386 return -EINVAL;
1387
0d12936d 1388 node = path_join(sym_crypt_get_dir(), name);
4623e8e6
LP
1389 if (!node)
1390 return -ENOMEM;
1391
1cc6c93a
YW
1392 *ret_name = TAKE_PTR(name);
1393 *ret_node = TAKE_PTR(node);
4623e8e6 1394
4623e8e6
LP
1395 return 0;
1396}
1397
18b5886e
LP
1398static int decrypt_partition(
1399 DissectedPartition *m,
1400 const char *passphrase,
1401 DissectImageFlags flags,
1402 DecryptedImage *d) {
1403
1404 _cleanup_free_ char *node = NULL, *name = NULL;
0d12936d 1405 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
18b5886e
LP
1406 int r;
1407
1408 assert(m);
1409 assert(d);
1410
1411 if (!m->found || !m->node || !m->fstype)
1412 return 0;
1413
1414 if (!streq(m->fstype, "crypto_LUKS"))
1415 return 0;
1416
bdd73ac5
ZJS
1417 if (!passphrase)
1418 return -ENOKEY;
1419
0d12936d
LP
1420 r = dlopen_cryptsetup();
1421 if (r < 0)
1422 return r;
1423
4623e8e6
LP
1424 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1425 if (r < 0)
1426 return r;
18b5886e
LP
1427
1428 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1429 return -ENOMEM;
1430
0d12936d 1431 r = sym_crypt_init(&cd, m->node);
18b5886e 1432 if (r < 0)
715cbb81 1433 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 1434
efc3b12f 1435 cryptsetup_enable_logging(cd);
1887032f 1436
0d12936d 1437 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
1438 if (r < 0)
1439 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e 1440
0d12936d
LP
1441 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1442 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1443 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 1444 if (r < 0) {
715cbb81 1445 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 1446 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 1447 }
18b5886e 1448
94344385
LP
1449 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1450 .name = TAKE_PTR(name),
1451 .device = TAKE_PTR(cd),
1452 };
18b5886e 1453
1cc6c93a 1454 m->decrypted_node = TAKE_PTR(node);
18b5886e
LP
1455
1456 return 0;
4623e8e6
LP
1457}
1458
89e62e0b
LP
1459static int verity_can_reuse(
1460 const VeritySettings *verity,
1461 const char *name,
1462 struct crypt_device **ret_cd) {
1463
ac1f3ad0
LB
1464 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1465 _cleanup_free_ char *root_hash_existing = NULL;
0d12936d 1466 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1467 struct crypt_params_verity crypt_params = {};
89e62e0b 1468 size_t root_hash_existing_size;
ac1f3ad0
LB
1469 int r;
1470
89e62e0b
LP
1471 assert(verity);
1472 assert(name);
ac1f3ad0
LB
1473 assert(ret_cd);
1474
0d12936d 1475 r = sym_crypt_init_by_name(&cd, name);
ac1f3ad0
LB
1476 if (r < 0)
1477 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
0d12936d
LP
1478
1479 r = sym_crypt_get_verity_info(cd, &crypt_params);
ac1f3ad0
LB
1480 if (r < 0)
1481 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
0d12936d 1482
89e62e0b
LP
1483 root_hash_existing_size = verity->root_hash_size;
1484 root_hash_existing = malloc0(root_hash_existing_size);
ac1f3ad0
LB
1485 if (!root_hash_existing)
1486 return -ENOMEM;
0d12936d
LP
1487
1488 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
ac1f3ad0
LB
1489 if (r < 0)
1490 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
89e62e0b
LP
1491 if (verity->root_hash_size != root_hash_existing_size ||
1492 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
ac1f3ad0 1493 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
89e62e0b 1494
ac1f3ad0 1495#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
1496 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1497 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1498 * signing for the new one, and viceversa. */
1499 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
ac1f3ad0
LB
1500 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1501#endif
1502
1503 *ret_cd = TAKE_PTR(cd);
1504 return 0;
1505}
1506
1507static inline void dm_deferred_remove_clean(char *name) {
1508 if (!name)
1509 return;
0d12936d
LP
1510
1511 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
ac1f3ad0
LB
1512 free(name);
1513}
1514DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1515
4623e8e6 1516static int verity_partition(
aee36b4e 1517 PartitionDesignator designator,
4623e8e6
LP
1518 DissectedPartition *m,
1519 DissectedPartition *v,
89e62e0b 1520 const VeritySettings *verity,
4623e8e6
LP
1521 DissectImageFlags flags,
1522 DecryptedImage *d) {
1523
0d12936d 1524 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1525 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
89e62e0b 1526 _cleanup_free_ char *node = NULL, *name = NULL;
4623e8e6
LP
1527 int r;
1528
1529 assert(m);
89e62e0b 1530 assert(v || (verity && verity->data_path));
4623e8e6 1531
89e62e0b 1532 if (!verity || !verity->root_hash)
4623e8e6 1533 return 0;
aee36b4e
LP
1534 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
1535 (verity->designator == designator)))
1536 return 0;
4623e8e6
LP
1537
1538 if (!m->found || !m->node || !m->fstype)
1539 return 0;
89e62e0b 1540 if (!verity->data_path) {
e7cbe5cb
LB
1541 if (!v->found || !v->node || !v->fstype)
1542 return 0;
4623e8e6 1543
e7cbe5cb
LB
1544 if (!streq(v->fstype, "DM_verity_hash"))
1545 return 0;
1546 }
4623e8e6 1547
0d12936d
LP
1548 r = dlopen_cryptsetup();
1549 if (r < 0)
1550 return r;
1551
ac1f3ad0
LB
1552 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
1553 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1554 _cleanup_free_ char *root_hash_encoded = NULL;
0d12936d 1555
89e62e0b 1556 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
ac1f3ad0
LB
1557 if (!root_hash_encoded)
1558 return -ENOMEM;
aee36b4e 1559
ac1f3ad0
LB
1560 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
1561 } else
1562 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
4623e8e6
LP
1563 if (r < 0)
1564 return r;
1565
89e62e0b 1566 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
4623e8e6
LP
1567 if (r < 0)
1568 return r;
1569
efc3b12f 1570 cryptsetup_enable_logging(cd);
1887032f 1571
0d12936d 1572 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
4623e8e6 1573 if (r < 0)
294bd454 1574 return r;
4623e8e6 1575
0d12936d 1576 r = sym_crypt_set_data_device(cd, m->node);
4623e8e6 1577 if (r < 0)
294bd454 1578 return r;
4623e8e6 1579
ac1f3ad0
LB
1580 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1581 return -ENOMEM;
1582
1583 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1584 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1585 * retry a few times before giving up. */
1586 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
89e62e0b 1587 if (verity->root_hash_sig) {
c2923fdc 1588#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
1589 r = sym_crypt_activate_by_signed_key(
1590 cd,
1591 name,
1592 verity->root_hash,
1593 verity->root_hash_size,
1594 verity->root_hash_sig,
1595 verity->root_hash_sig_size,
1596 CRYPT_ACTIVATE_READONLY);
ac1f3ad0 1597#else
22043172
LP
1598 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1599 "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
1600#endif
1601 } else
89e62e0b
LP
1602 r = sym_crypt_activate_by_volume_key(
1603 cd,
1604 name,
1605 verity->root_hash,
1606 verity->root_hash_size,
1607 CRYPT_ACTIVATE_READONLY);
ac1f3ad0
LB
1608 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1609 * There's no way to distinguish this situation from a genuine error due to invalid
2aed63f4 1610 * parameters, so immediately fall back to activating the device with a unique name.
89e62e0b
LP
1611 * Improvements in libcrypsetup can ensure this never happens:
1612 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
ac1f3ad0 1613 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 1614 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10 1615 if (!IN_SET(r,
22043172 1616 0, /* Success */
9ecb5c10 1617 -EEXIST, /* Volume is already open and ready to be used */
22043172
LP
1618 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
1619 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
ac1f3ad0 1620 return r;
9ecb5c10 1621 if (IN_SET(r, -EEXIST, -EBUSY)) {
ac1f3ad0 1622 struct crypt_device *existing_cd = NULL;
c2923fdc 1623
ac1f3ad0
LB
1624 if (!restore_deferred_remove){
1625 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1626 r = dm_deferred_remove_cancel(name);
9ecb5c10
LB
1627 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
1628 if (r < 0 && r != -ENXIO)
ac1f3ad0 1629 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
9ecb5c10
LB
1630 if (r == 0) {
1631 restore_deferred_remove = strdup(name);
1632 if (!restore_deferred_remove)
1633 return -ENOMEM;
1634 }
ac1f3ad0 1635 }
c2923fdc 1636
89e62e0b 1637 r = verity_can_reuse(verity, name, &existing_cd);
ac1f3ad0
LB
1638 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1639 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 1640 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10 1641 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
ac1f3ad0
LB
1642 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
1643 if (r == 0) {
c419b6f0
LB
1644 /* devmapper might say that the device exists, but the devlink might not yet have been
1645 * created. Check and wait for the udev event in that case. */
1646 r = device_wait_for_devlink(node, "block", 100 * USEC_PER_MSEC, NULL);
1647 /* Fallback to activation with a unique device if it's taking too long */
1648 if (r == -ETIMEDOUT)
1649 break;
1650 if (r < 0)
1651 return r;
1652
ac1f3ad0 1653 if (cd)
0d12936d 1654 sym_crypt_free(cd);
ac1f3ad0
LB
1655 cd = existing_cd;
1656 }
c2923fdc 1657 }
ac1f3ad0
LB
1658 if (r == 0)
1659 break;
ecab4c47
LB
1660
1661 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
1662 (void) usleep(2 * USEC_PER_MSEC);
ac1f3ad0
LB
1663 }
1664
ac1f3ad0
LB
1665 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1666 * Fall back to activating it with a unique device name. */
1667 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 1668 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
ac1f3ad0
LB
1669
1670 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1671 restore_deferred_remove = mfree(restore_deferred_remove);
4623e8e6 1672
94344385
LP
1673 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1674 .name = TAKE_PTR(name),
1675 .device = TAKE_PTR(cd),
1676 };
4623e8e6 1677
1cc6c93a 1678 m->decrypted_node = TAKE_PTR(node);
4623e8e6
LP
1679
1680 return 0;
18b5886e
LP
1681}
1682#endif
1683
1684int dissected_image_decrypt(
1685 DissectedImage *m,
1686 const char *passphrase,
89e62e0b 1687 const VeritySettings *verity,
18b5886e
LP
1688 DissectImageFlags flags,
1689 DecryptedImage **ret) {
1690
349cc4a5 1691#if HAVE_LIBCRYPTSETUP
49b5b3b4 1692 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
1693 int r;
1694#endif
1695
1696 assert(m);
89e62e0b 1697 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
18b5886e
LP
1698
1699 /* Returns:
1700 *
1701 * = 0 → There was nothing to decrypt
1702 * > 0 → Decrypted successfully
d1c536f5 1703 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
1704 * -EKEYREJECTED → Passed key was not correct
1705 */
1706
89e62e0b 1707 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
1708 return -EINVAL;
1709
1710 if (!m->encrypted && !m->verity) {
18b5886e
LP
1711 *ret = NULL;
1712 return 0;
1713 }
1714
349cc4a5 1715#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1716 d = new0(DecryptedImage, 1);
1717 if (!d)
1718 return -ENOMEM;
1719
569a0e42 1720 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 1721 DissectedPartition *p = m->partitions + i;
22043172 1722 PartitionDesignator k;
18b5886e
LP
1723
1724 if (!p->found)
1725 continue;
1726
1727 r = decrypt_partition(p, passphrase, flags, d);
1728 if (r < 0)
1729 return r;
1730
4623e8e6
LP
1731 k = PARTITION_VERITY_OF(i);
1732 if (k >= 0) {
aee36b4e 1733 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
4623e8e6
LP
1734 if (r < 0)
1735 return r;
1736 }
1737
18b5886e
LP
1738 if (!p->decrypted_fstype && p->decrypted_node) {
1739 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 1740 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
1741 return r;
1742 }
1743 }
1744
1cc6c93a 1745 *ret = TAKE_PTR(d);
18b5886e
LP
1746
1747 return 1;
1748#else
1749 return -EOPNOTSUPP;
1750#endif
1751}
1752
1753int dissected_image_decrypt_interactively(
1754 DissectedImage *m,
1755 const char *passphrase,
89e62e0b 1756 const VeritySettings *verity,
18b5886e
LP
1757 DissectImageFlags flags,
1758 DecryptedImage **ret) {
1759
1760 _cleanup_strv_free_erase_ char **z = NULL;
1761 int n = 3, r;
1762
1763 if (passphrase)
1764 n--;
1765
1766 for (;;) {
89e62e0b 1767 r = dissected_image_decrypt(m, passphrase, verity, flags, ret);
18b5886e
LP
1768 if (r >= 0)
1769 return r;
1770 if (r == -EKEYREJECTED)
1771 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
1772 else if (r != -ENOKEY)
1773 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 1774
baaa35ad
ZJS
1775 if (--n < 0)
1776 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1777 "Too many retries.");
18b5886e
LP
1778
1779 z = strv_free(z);
1780
a1c111c2 1781 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
18b5886e
LP
1782 if (r < 0)
1783 return log_error_errno(r, "Failed to query for passphrase: %m");
1784
1785 passphrase = z[0];
1786 }
1787}
1788
18b5886e
LP
1789int decrypted_image_relinquish(DecryptedImage *d) {
1790
349cc4a5 1791#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1792 size_t i;
1793 int r;
1794#endif
1795
1796 assert(d);
1797
1798 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1799 * that we don't clean it up ourselves either anymore */
1800
349cc4a5 1801#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1802 for (i = 0; i < d->n_decrypted; i++) {
1803 DecryptedPartition *p = d->decrypted + i;
1804
1805 if (p->relinquished)
1806 continue;
1807
0d12936d 1808 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
1809 if (r < 0)
1810 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1811
1812 p->relinquished = true;
1813 }
1814#endif
1815
1816 return 0;
1817}
1818
89e62e0b
LP
1819static char *build_auxiliary_path(const char *image, const char *suffix) {
1820 const char *e;
1821 char *n;
1822
1823 assert(image);
1824 assert(suffix);
1825
1826 e = endswith(image, ".raw");
1827 if (!e)
1828 return strjoin(e, suffix);
1829
1830 n = new(char, e - image + strlen(suffix) + 1);
1831 if (!n)
1832 return NULL;
1833
1834 strcpy(mempcpy(n, image, e - image), suffix);
1835 return n;
1836}
1837
1838void verity_settings_done(VeritySettings *v) {
1839 assert(v);
1840
1841 v->root_hash = mfree(v->root_hash);
1842 v->root_hash_size = 0;
1843
1844 v->root_hash_sig = mfree(v->root_hash_sig);
1845 v->root_hash_sig_size = 0;
1846
1847 v->data_path = mfree(v->data_path);
1848}
1849
1850int verity_settings_load(
1851 VeritySettings *verity,
f5ea63a5
LP
1852 const char *image,
1853 const char *root_hash_path,
89e62e0b
LP
1854 const char *root_hash_sig_path) {
1855
1856 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
1857 size_t root_hash_size = 0, root_hash_sig_size = 0;
1858 _cleanup_free_ char *verity_data_path = NULL;
aee36b4e 1859 PartitionDesignator designator;
78ebe980
LP
1860 int r;
1861
89e62e0b 1862 assert(verity);
78ebe980 1863 assert(image);
aee36b4e 1864 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
78ebe980 1865
89e62e0b
LP
1866 /* If we are asked to load the root hash for a device node, exit early */
1867 if (is_device_path(image))
78ebe980 1868 return 0;
78ebe980 1869
aee36b4e
LP
1870 designator = verity->designator;
1871
89e62e0b 1872 /* We only fill in what isn't already filled in */
c2923fdc 1873
89e62e0b 1874 if (!verity->root_hash) {
e7cbe5cb 1875 _cleanup_free_ char *text = NULL;
e7cbe5cb 1876
0389f4fa 1877 if (root_hash_path) {
aee36b4e 1878 /* If explicitly specified it takes precedence */
0389f4fa
LB
1879 r = read_one_line_file(root_hash_path, &text);
1880 if (r < 0)
e7cbe5cb 1881 return r;
aee36b4e
LP
1882
1883 if (designator < 0)
1884 designator = PARTITION_ROOT;
0389f4fa 1885 } else {
aee36b4e
LP
1886 /* Otherwise look for xattr and separate file, and first for the data for root and if
1887 * that doesn't exist for /usr */
0389f4fa 1888
aee36b4e
LP
1889 if (designator < 0 || designator == PARTITION_ROOT) {
1890 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1891 if (r < 0) {
1892 _cleanup_free_ char *p = NULL;
78ebe980 1893
aee36b4e
LP
1894 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
1895 return r;
e7cbe5cb 1896
aee36b4e
LP
1897 p = build_auxiliary_path(image, ".roothash");
1898 if (!p)
1899 return -ENOMEM;
1900
1901 r = read_one_line_file(p, &text);
1902 if (r < 0 && r != -ENOENT)
1903 return r;
1904 }
1905
1906 if (text)
1907 designator = PARTITION_ROOT;
1908 }
1909
1910 if (!text && (designator < 0 || designator == PARTITION_USR)) {
1911 /* So in the "roothash" xattr/file name above the "root" of course primarily
1912 * refers to the root of the Verity Merkle tree. But coincidentally it also
1913 * is the hash for the *root* file system, i.e. the "root" neatly refers to
1914 * two distinct concepts called "root". Taking benefit of this happy
1915 * coincidence we call the file with the root hash for the /usr/ file system
1916 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
1917 * confusing. We thus drop the reference to the root of the Merkle tree, and
1918 * just indicate which file system it's about. */
1919 r = getxattr_malloc(image, "user.verity.usrhash", &text, true);
1920 if (r < 0) {
1921 _cleanup_free_ char *p = NULL;
1922
1923 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
1924 return r;
1925
1926 p = build_auxiliary_path(image, ".usrhash");
1927 if (!p)
1928 return -ENOMEM;
1929
1930 r = read_one_line_file(p, &text);
1931 if (r < 0 && r != -ENOENT)
1932 return r;
1933 }
1934
1935 if (text)
1936 designator = PARTITION_USR;
0389f4fa 1937 }
e7cbe5cb
LB
1938 }
1939
1940 if (text) {
89e62e0b 1941 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
e7cbe5cb
LB
1942 if (r < 0)
1943 return r;
89e62e0b 1944 if (root_hash_size < sizeof(sd_id128_t))
e7cbe5cb
LB
1945 return -EINVAL;
1946 }
1947 }
1948
aee36b4e
LP
1949 if (verity->root_hash && !verity->root_hash_sig) {
1950 if (root_hash_sig_path) {
1951 r = read_full_file_full(AT_FDCWD, root_hash_sig_path, 0, (char**) &root_hash_sig, &root_hash_sig_size);
1952 if (r < 0 && r != -ENOENT)
1953 return r;
1954
1955 if (designator < 0)
1956 designator = PARTITION_ROOT;
1957 } else {
1958 if (designator < 0 || designator == PARTITION_ROOT) {
1959 _cleanup_free_ char *p = NULL;
1960
1961 /* Follow naming convention recommended by the relevant RFC:
1962 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1963 p = build_auxiliary_path(image, ".roothash.p7s");
1964 if (!p)
1965 return -ENOMEM;
89e62e0b 1966
7025fa8b 1967 r = read_full_file_full(AT_FDCWD, p, 0, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
1968 if (r < 0 && r != -ENOENT)
1969 return r;
1970 if (r >= 0)
1971 designator = PARTITION_ROOT;
1972 }
1973
1974 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
1975 _cleanup_free_ char *p = NULL;
1976
1977 p = build_auxiliary_path(image, ".usrhash.p7s");
1978 if (!p)
1979 return -ENOMEM;
89e62e0b 1980
7025fa8b 1981 r = read_full_file_full(AT_FDCWD, p, 0, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
1982 if (r < 0 && r != -ENOENT)
1983 return r;
1984 if (r >= 0)
1985 designator = PARTITION_USR;
1986 }
89e62e0b
LP
1987 }
1988
aee36b4e 1989 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
89e62e0b
LP
1990 return -EINVAL;
1991 }
1992
1993 if (!verity->data_path) {
1994 _cleanup_free_ char *p = NULL;
1995
1996 p = build_auxiliary_path(image, ".verity");
1997 if (!p)
1998 return -ENOMEM;
1999
2000 if (access(p, F_OK) < 0) {
2001 if (errno != ENOENT)
2002 return -errno;
2003 } else
2004 verity_data_path = TAKE_PTR(p);
2005 }
2006
2007 if (root_hash) {
2008 verity->root_hash = TAKE_PTR(root_hash);
2009 verity->root_hash_size = root_hash_size;
2010 }
2011
2012 if (root_hash_sig) {
2013 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2014 verity->root_hash_sig_size = root_hash_sig_size;
e7cbe5cb 2015 }
89e62e0b
LP
2016
2017 if (verity_data_path)
2018 verity->data_path = TAKE_PTR(verity_data_path);
78ebe980 2019
aee36b4e
LP
2020 if (verity->designator < 0)
2021 verity->designator = designator;
2022
78ebe980
LP
2023 return 1;
2024}
2025
3b925504
LP
2026int dissected_image_acquire_metadata(DissectedImage *m) {
2027
2028 enum {
2029 META_HOSTNAME,
2030 META_MACHINE_ID,
2031 META_MACHINE_INFO,
2032 META_OS_RELEASE,
2033 _META_MAX,
2034 };
2035
2036 static const char *const paths[_META_MAX] = {
2037 [META_HOSTNAME] = "/etc/hostname\0",
2038 [META_MACHINE_ID] = "/etc/machine-id\0",
2039 [META_MACHINE_INFO] = "/etc/machine-info\0",
d4dffb85
LP
2040 [META_OS_RELEASE] = "/etc/os-release\0"
2041 "/usr/lib/os-release\0",
3b925504
LP
2042 };
2043
2044 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
af8219d5 2045 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
3b925504
LP
2046 _cleanup_(rmdir_and_freep) char *t = NULL;
2047 _cleanup_(sigkill_waitp) pid_t child = 0;
2048 sd_id128_t machine_id = SD_ID128_NULL;
2049 _cleanup_free_ char *hostname = NULL;
2050 unsigned n_meta_initialized = 0, k;
af8219d5
LP
2051 int fds[2 * _META_MAX], r, v;
2052 ssize_t n;
3b925504
LP
2053
2054 BLOCK_SIGNALS(SIGCHLD);
2055
2056 assert(m);
2057
2058 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
2059 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2060 r = -errno;
2061 goto finish;
2062 }
2063
2064 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2065 if (r < 0)
2066 goto finish;
2067
af8219d5
LP
2068 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2069 r = -errno;
2070 goto finish;
2071 }
2072
e2047ba9 2073 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 2074 if (r < 0)
3b925504 2075 goto finish;
be39f6ee 2076 if (r == 0) {
af8219d5
LP
2077 error_pipe[0] = safe_close(error_pipe[0]);
2078
03bcb6d4 2079 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
429d4e41 2080 if (r < 0) {
af8219d5
LP
2081 /* Let parent know the error */
2082 (void) write(error_pipe[1], &r, sizeof(r));
2083
429d4e41 2084 log_debug_errno(r, "Failed to mount dissected image: %m");
3b925504 2085 _exit(EXIT_FAILURE);
429d4e41 2086 }
3b925504
LP
2087
2088 for (k = 0; k < _META_MAX; k++) {
37e44c3f 2089 _cleanup_close_ int fd = -ENOENT;
3b925504
LP
2090 const char *p;
2091
2092 fds[2*k] = safe_close(fds[2*k]);
2093
2094 NULSTR_FOREACH(p, paths[k]) {
36952d19 2095 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3b925504
LP
2096 if (fd >= 0)
2097 break;
2098 }
36952d19
LP
2099 if (fd < 0) {
2100 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
37e44c3f 2101 fds[2*k+1] = safe_close(fds[2*k+1]);
3b925504 2102 continue;
36952d19 2103 }
3b925504
LP
2104
2105 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
af8219d5
LP
2106 if (r < 0) {
2107 (void) write(error_pipe[1], &r, sizeof(r));
3b925504 2108 _exit(EXIT_FAILURE);
af8219d5 2109 }
3b925504
LP
2110
2111 fds[2*k+1] = safe_close(fds[2*k+1]);
2112 }
2113
2114 _exit(EXIT_SUCCESS);
2115 }
2116
af8219d5
LP
2117 error_pipe[1] = safe_close(error_pipe[1]);
2118
3b925504
LP
2119 for (k = 0; k < _META_MAX; k++) {
2120 _cleanup_fclose_ FILE *f = NULL;
2121
2122 fds[2*k+1] = safe_close(fds[2*k+1]);
2123
4fa744a3 2124 f = take_fdopen(&fds[2*k], "r");
3b925504
LP
2125 if (!f) {
2126 r = -errno;
2127 goto finish;
2128 }
2129
3b925504
LP
2130 switch (k) {
2131
2132 case META_HOSTNAME:
2133 r = read_etc_hostname_stream(f, &hostname);
2134 if (r < 0)
2135 log_debug_errno(r, "Failed to read /etc/hostname: %m");
2136
2137 break;
2138
2139 case META_MACHINE_ID: {
2140 _cleanup_free_ char *line = NULL;
2141
2142 r = read_line(f, LONG_LINE_MAX, &line);
2143 if (r < 0)
2144 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
2145 else if (r == 33) {
2146 r = sd_id128_from_string(line, &machine_id);
2147 if (r < 0)
2148 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
2149 } else if (r == 0)
2150 log_debug("/etc/machine-id file is empty.");
ab763cb2
HS
2151 else if (streq(line, "uninitialized"))
2152 log_debug("/etc/machine-id file is uninitialized (likely aborted first boot).");
3b925504
LP
2153 else
2154 log_debug("/etc/machine-id has unexpected length %i.", r);
2155
2156 break;
2157 }
2158
2159 case META_MACHINE_INFO:
aa8fbc74 2160 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504
LP
2161 if (r < 0)
2162 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
2163
2164 break;
2165
2166 case META_OS_RELEASE:
aa8fbc74 2167 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504
LP
2168 if (r < 0)
2169 log_debug_errno(r, "Failed to read OS release file: %m");
2170
2171 break;
2172 }
2173 }
2174
2e87a1fd 2175 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 2176 child = 0;
2e87a1fd 2177 if (r < 0)
af8219d5
LP
2178 return r;
2179
2180 n = read(error_pipe[0], &v, sizeof(v));
2181 if (n < 0)
2182 return -errno;
2183 if (n == sizeof(v))
2184 return v; /* propagate error sent to us from child */
2185 if (n != 0)
2186 return -EIO;
2187
2e87a1fd
LP
2188 if (r != EXIT_SUCCESS)
2189 return -EPROTO;
3b925504
LP
2190
2191 free_and_replace(m->hostname, hostname);
2192 m->machine_id = machine_id;
2193 strv_free_and_replace(m->machine_info, machine_info);
2194 strv_free_and_replace(m->os_release, os_release);
2195
2196finish:
2197 for (k = 0; k < n_meta_initialized; k++)
2198 safe_close_pair(fds + 2*k);
2199
2200 return r;
2201}
2202
4526113f
LP
2203int dissect_image_and_warn(
2204 int fd,
2205 const char *name,
89e62e0b 2206 const VeritySettings *verity,
18d73705 2207 const MountOptions *mount_options,
4526113f
LP
2208 DissectImageFlags flags,
2209 DissectedImage **ret) {
2210
2211 _cleanup_free_ char *buffer = NULL;
2212 int r;
2213
2214 if (!name) {
2215 r = fd_get_path(fd, &buffer);
2216 if (r < 0)
2217 return r;
2218
2219 name = buffer;
2220 }
2221
89e62e0b 2222 r = dissect_image(fd, verity, mount_options, flags, ret);
4526113f
LP
2223 switch (r) {
2224
2225 case -EOPNOTSUPP:
2226 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
2227
2228 case -ENOPKG:
2229 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
2230
2231 case -EADDRNOTAVAIL:
2232 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
2233
2234 case -ENOTUNIQ:
2235 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
2236
2237 case -ENXIO:
2238 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
2239
2240 case -EPROTONOSUPPORT:
2241 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
2242
2243 default:
2244 if (r < 0)
2245 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
2246
2247 return r;
2248 }
2249}
2250
569a0e42 2251bool dissected_image_can_do_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
e7cbe5cb
LB
2252 if (image->single_file_system)
2253 return partition_designator == PARTITION_ROOT && image->can_verity;
2254
2255 return PARTITION_VERITY_OF(partition_designator) >= 0;
2256}
2257
569a0e42 2258bool dissected_image_has_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
e7cbe5cb
LB
2259 int k;
2260
2261 if (image->single_file_system)
2262 return partition_designator == PARTITION_ROOT && image->verity;
2263
2264 k = PARTITION_VERITY_OF(partition_designator);
2265 return k >= 0 && image->partitions[k].found;
2266}
2267
18d73705
LB
2268MountOptions* mount_options_free_all(MountOptions *options) {
2269 MountOptions *m;
2270
2271 while ((m = options)) {
2272 LIST_REMOVE(mount_options, options, m);
2273 free(m->options);
2274 free(m);
2275 }
2276
2277 return NULL;
2278}
2279
569a0e42 2280const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
f5215bc8 2281 const MountOptions *m;
18d73705 2282
f5215bc8 2283 LIST_FOREACH(mount_options, m, options)
9ece6444 2284 if (designator == m->partition_designator && !isempty(m->options))
18d73705 2285 return m->options;
6aa05ebd 2286
18d73705
LB
2287 return NULL;
2288}
2289
6aa05ebd
LP
2290int mount_image_privately_interactively(
2291 const char *image,
2292 DissectImageFlags flags,
2293 char **ret_directory,
2294 LoopDevice **ret_loop_device,
2295 DecryptedImage **ret_decrypted_image) {
2296
2297 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2298 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2299 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2300 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
2301 _cleanup_free_ char *temp = NULL;
2302 int r;
2303
2304 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2305 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2306 * easily. */
2307
2308 assert(image);
2309 assert(ret_directory);
2310 assert(ret_loop_device);
2311 assert(ret_decrypted_image);
2312
2313 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
2314 if (r < 0)
2315 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
2316
2317 r = loop_device_make_by_path(
2318 image,
2319 FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY) ? O_RDONLY : O_RDWR,
2320 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2321 &d);
2322 if (r < 0)
2323 return log_error_errno(r, "Failed to set up loopback device: %m");
2324
89e62e0b 2325 r = dissect_image_and_warn(d->fd, image, NULL, NULL, flags, &dissected_image);
6aa05ebd
LP
2326 if (r < 0)
2327 return r;
2328
89e62e0b 2329 r = dissected_image_decrypt_interactively(dissected_image, NULL, NULL, flags, &decrypted_image);
6aa05ebd
LP
2330 if (r < 0)
2331 return r;
2332
2333 r = detach_mount_namespace();
2334 if (r < 0)
2335 return log_error_errno(r, "Failed to detach mount namespace: %m");
2336
2337 r = mkdir_p(temp, 0700);
2338 if (r < 0)
2339 return log_error_errno(r, "Failed to create mount point: %m");
2340
2341 created_dir = TAKE_PTR(temp);
2342
af187ab2 2343 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, flags);
6aa05ebd 2344 if (r < 0)
af187ab2 2345 return r;
6aa05ebd
LP
2346
2347 if (decrypted_image) {
2348 r = decrypted_image_relinquish(decrypted_image);
2349 if (r < 0)
2350 return log_error_errno(r, "Failed to relinquish DM devices: %m");
2351 }
2352
2353 loop_device_relinquish(d);
2354
2355 *ret_directory = TAKE_PTR(created_dir);
2356 *ret_loop_device = TAKE_PTR(d);
2357 *ret_decrypted_image = TAKE_PTR(decrypted_image);
2358
2359 return 0;
2360}
2361
8c1be37e
LP
2362static const char *const partition_designator_table[] = {
2363 [PARTITION_ROOT] = "root",
2364 [PARTITION_ROOT_SECONDARY] = "root-secondary",
aee36b4e
LP
2365 [PARTITION_USR] = "usr",
2366 [PARTITION_USR_SECONDARY] = "usr-secondary",
8c1be37e
LP
2367 [PARTITION_HOME] = "home",
2368 [PARTITION_SRV] = "srv",
2369 [PARTITION_ESP] = "esp",
a8c47660 2370 [PARTITION_XBOOTLDR] = "xbootldr",
8c1be37e 2371 [PARTITION_SWAP] = "swap",
4623e8e6
LP
2372 [PARTITION_ROOT_VERITY] = "root-verity",
2373 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
aee36b4e
LP
2374 [PARTITION_USR_VERITY] = "usr-verity",
2375 [PARTITION_USR_SECONDARY_VERITY] = "usr-secondary-verity",
d4dffb85
LP
2376 [PARTITION_TMP] = "tmp",
2377 [PARTITION_VAR] = "var",
8c1be37e
LP
2378};
2379
569a0e42 2380DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);