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