]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
dissect: pick up gpt partition flags
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
8c1be37e 2
10c1b188
LP
3#if HAVE_VALGRIND_MEMCHECK_H
4#include <valgrind/memcheck.h>
5#endif
6
01234e1f
YW
7#include <linux/dm-ioctl.h>
8#include <linux/loop.h>
19df770f 9#include <sys/file.h>
8c1be37e 10#include <sys/mount.h>
3b925504
LP
11#include <sys/prctl.h>
12#include <sys/wait.h>
f5ea63a5 13#include <sysexits.h>
8c1be37e 14
c2fa92e7
LP
15#if HAVE_OPENSSL
16#include <openssl/err.h>
17#include <openssl/pem.h>
18#include <openssl/x509.h>
19#endif
20
3c1f2cee 21#include "sd-device.h"
dccca82b
LP
22#include "sd-id128.h"
23
8c1be37e 24#include "architecture.h"
18b5886e 25#include "ask-password-api.h"
8c1be37e 26#include "blkid-util.h"
18c528e9 27#include "blockdev-util.h"
f4351959 28#include "chase-symlinks.h"
c2fa92e7 29#include "conf-files.h"
28db6fbf 30#include "constants.h"
3b925504 31#include "copy.h"
1e2f3230 32#include "cryptsetup-util.h"
553e15f2 33#include "device-nodes.h"
8437c059 34#include "device-util.h"
f7725647 35#include "devnum-util.h"
7718ac97 36#include "discover-image.h"
8c1be37e 37#include "dissect-image.h"
a709a315 38#include "dm-util.h"
686d13b9 39#include "env-file.h"
88b3300f 40#include "env-util.h"
93f59701 41#include "extension-release.h"
18b5886e 42#include "fd-util.h"
78ebe980 43#include "fileio.h"
2eedfd2d 44#include "fs-util.h"
cf32c486 45#include "fsck-util.h"
8c1be37e 46#include "gpt.h"
78ebe980 47#include "hexdecoct.h"
e2054217 48#include "hostname-setup.h"
3b925504 49#include "id128-util.h"
593fe6c0 50#include "import-util.h"
a4e0d617 51#include "io-util.h"
35cd0ba5 52#include "mkdir-label.h"
8c1be37e 53#include "mount-util.h"
e4de7287 54#include "mountpoint-util.h"
6aa05ebd 55#include "namespace-util.h"
d8b4d14d 56#include "nulstr-util.h"
c2fa92e7 57#include "openssl-util.h"
d58ad743 58#include "os-util.h"
8c1be37e 59#include "path-util.h"
3b925504
LP
60#include "process-util.h"
61#include "raw-clone.h"
81939d9d 62#include "resize-fs.h"
3b925504 63#include "signal-util.h"
8c1be37e 64#include "stat-util.h"
18b5886e 65#include "stdio-util.h"
8c1be37e
LP
66#include "string-table.h"
67#include "string-util.h"
2eedfd2d 68#include "strv.h"
e4de7287 69#include "tmpfile-util.h"
a8040b6d 70#include "udev-util.h"
2d3a5a73 71#include "user-util.h"
41488e1f 72#include "xattr-util.h"
8c1be37e 73
28e2641a
FF
74/* how many times to wait for the device nodes to appear */
75#define N_DEVICE_NODE_LIST_ATTEMPTS 10
76
c80c9079
LP
77int probe_filesystem_full(
78 int fd,
79 const char *path,
80 uint64_t offset,
81 uint64_t size,
82 char **ret_fstype) {
83
7cc84b2c 84 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
c80c9079 85 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
7cc84b2c
ZJS
86 * different error otherwise. */
87
349cc4a5 88#if HAVE_BLKID
8e766630 89 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
d2c6e79d
YW
90 _cleanup_free_ char *path_by_fd = NULL;
91 _cleanup_close_ int fd_close = -1;
18b5886e
LP
92 const char *fstype;
93 int r;
94
d2c6e79d
YW
95 assert(fd >= 0 || path);
96 assert(ret_fstype);
97
98 if (fd < 0) {
99 fd_close = open(path, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
100 if (fd_close < 0)
101 return -errno;
102
103 fd = fd_close;
104 }
105
106 if (!path) {
107 r = fd_get_path(fd, &path_by_fd);
108 if (r < 0)
109 return r;
110
111 path = path_by_fd;
112 }
113
c80c9079
LP
114 if (size == 0) /* empty size? nothing found! */
115 goto not_found;
116
d2c6e79d 117 b = blkid_new_probe();
18b5886e 118 if (!b)
d2c6e79d
YW
119 return -ENOMEM;
120
121 errno = 0;
c80c9079
LP
122 r = blkid_probe_set_device(
123 b,
124 fd,
125 offset,
126 size == UINT64_MAX ? 0 : size); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
d2c6e79d 127 if (r != 0)
66855de7 128 return errno_or_else(ENOMEM);
18b5886e
LP
129
130 blkid_probe_enable_superblocks(b, 1);
131 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
132
133 errno = 0;
134 r = blkid_do_safeprobe(b);
2e3944b8 135 if (r == _BLKID_SAFEPROBE_NOT_FOUND)
18b5886e 136 goto not_found;
2e3944b8 137 if (r == _BLKID_SAFEPROBE_AMBIGUOUS)
58dfbfbd 138 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
d2c6e79d 139 "Results ambiguous for partition %s", path);
2e3944b8 140 if (r == _BLKID_SAFEPROBE_ERROR)
d2c6e79d 141 return log_debug_errno(errno_or_else(EIO), "Failed to probe partition %s: %m", path);
18b5886e 142
2e3944b8
LP
143 assert(r == _BLKID_SAFEPROBE_FOUND);
144
18b5886e
LP
145 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
146
147 if (fstype) {
148 char *t;
149
d2c6e79d 150 log_debug("Probed fstype '%s' on partition %s.", fstype, path);
1cefb9a6 151
18b5886e
LP
152 t = strdup(fstype);
153 if (!t)
154 return -ENOMEM;
155
156 *ret_fstype = t;
157 return 1;
158 }
159
160not_found:
d2c6e79d 161 log_debug("No type detected on partition %s", path);
18b5886e
LP
162 *ret_fstype = NULL;
163 return 0;
d1c536f5
ZJS
164#else
165 return -EOPNOTSUPP;
a75e27eb 166#endif
d1c536f5 167}
18b5886e 168
40c10d3f 169#if HAVE_BLKID
c80c9079 170static int dissected_image_probe_filesystems(DissectedImage *m, int fd) {
698bb074
YW
171 int r;
172
173 assert(m);
174
175 /* Fill in file system types if we don't know them yet. */
176
177 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
178 DissectedPartition *p = m->partitions + i;
179
180 if (!p->found)
181 continue;
182
c80c9079
LP
183 if (!p->fstype) {
184 /* If we have an fd referring to the partition block device, use that. Otherwise go
185 * via the whole block device or backing regular file, and read via offset. */
186 if (p->mount_node_fd >= 0)
187 r = probe_filesystem_full(p->mount_node_fd, p->node, 0, UINT64_MAX, &p->fstype);
188 else
189 r = probe_filesystem_full(fd, p->node, p->offset, p->size, &p->fstype);
190 if (r < 0)
698bb074
YW
191 return r;
192 }
193
194 if (streq_ptr(p->fstype, "crypto_LUKS"))
195 m->encrypted = true;
196
197 if (p->fstype && fstype_is_ro(p->fstype))
198 p->rw = false;
199
200 if (!p->rw)
201 p->growfs = false;
202 }
203
204 return 0;
205}
206
0f7c9a3d
LP
207static void check_partition_flags(
208 const char *node,
209 unsigned long long pflags,
210 unsigned long long supported) {
211
212 assert(node);
213
214 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
92e72028
ZJS
215 pflags &= ~(supported |
216 SD_GPT_FLAG_REQUIRED_PARTITION |
217 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL |
218 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE);
0f7c9a3d
LP
219
220 if (pflags == 0)
221 return;
222
223 /* If there are other bits set, then log about it, to make things discoverable */
224 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
225 unsigned long long bit = 1ULL << i;
226 if (!FLAGS_SET(pflags, bit))
227 continue;
228
229 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
230 }
231}
1b010ae7 232#endif
0f7c9a3d 233
00e29505
YW
234#if HAVE_BLKID
235static int dissected_image_new(const char *path, DissectedImage **ret) {
236 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
237 _cleanup_free_ char *name = NULL;
238 int r;
239
240 assert(ret);
241
242 if (path) {
243 _cleanup_free_ char *filename = NULL;
244
245 r = path_extract_filename(path, &filename);
246 if (r < 0)
247 return r;
248
249 r = raw_strip_suffixes(filename, &name);
250 if (r < 0)
251 return r;
252
253 if (!image_name_is_valid(name)) {
254 log_debug("Image name %s is not valid, ignoring.", strna(name));
255 name = mfree(name);
256 }
257 }
258
259 m = new(DissectedImage, 1);
260 if (!m)
261 return -ENOMEM;
262
263 *m = (DissectedImage) {
264 .has_init_system = -1,
265 .image_name = TAKE_PTR(name),
266 };
267
babd5b08
YW
268 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
269 m->partitions[i] = DISSECTED_PARTITION_NULL;
270
00e29505
YW
271 *ret = TAKE_PTR(m);
272 return 0;
273}
274#endif
275
234c2e16 276static void dissected_partition_done(DissectedPartition *p) {
1b010ae7 277 assert(p);
786e3a52 278
1b010ae7
LP
279 free(p->fstype);
280 free(p->node);
281 free(p->label);
282 free(p->decrypted_fstype);
283 free(p->decrypted_node);
284 free(p->mount_options);
f7725647 285 safe_close(p->mount_node_fd);
786e3a52 286
babd5b08 287 *p = DISSECTED_PARTITION_NULL;
1b010ae7 288}
786e3a52 289
1b010ae7 290#if HAVE_BLKID
1b010ae7
LP
291static int make_partition_devname(
292 const char *whole_devname,
293 int nr,
294 char **ret) {
786e3a52 295
1b010ae7 296 bool need_p;
786e3a52 297
1b010ae7
LP
298 assert(whole_devname);
299 assert(nr > 0);
aae22eb3 300
1b010ae7
LP
301 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition device
302 * name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole block device
303 * node name ends in a digit, then suffix a 'p', followed by the partition number. Otherwise, just
304 * suffix the partition number without any 'p'. */
4ba86848 305
1b010ae7
LP
306 if (isempty(whole_devname)) /* Make sure there *is* a last char */
307 return -EINVAL;
08fe0a53 308
ff25d338 309 need_p = ascii_isdigit(whole_devname[strlen(whole_devname)-1]); /* Last char a digit? */
08fe0a53 310
1b010ae7 311 return asprintf(ret, "%s%s%i", whole_devname, need_p ? "p" : "", nr);
08fe0a53
LP
312}
313
f7725647
YW
314static int open_partition(const char *node, bool is_partition, const LoopDevice *loop) {
315 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
316 _cleanup_close_ int fd = -1;
317 dev_t devnum;
318 int r;
319
320 assert(node);
321 assert(loop);
322
323 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
324 if (fd < 0)
325 return -errno;
326
327 /* Check if the block device is a child of (or equivalent to) the originally provided one. */
328 r = block_device_new_from_fd(fd, is_partition ? BLOCK_DEVICE_LOOKUP_WHOLE_DISK : 0, &dev);
329 if (r < 0)
330 return r;
331
332 r = sd_device_get_devnum(dev, &devnum);
333 if (r < 0)
334 return r;
335
336 if (loop->devno != devnum)
337 return -ENXIO;
338
339 /* Also check diskseq. */
340 if (loop->diskseq > 0) {
341 uint64_t diskseq;
342
343 r = fd_get_diskseq(fd, &diskseq);
344 if (r < 0)
345 return r;
346
347 if (loop->diskseq != diskseq)
348 return -ENXIO;
349 }
350
351 log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR ", diskseq=%" PRIu64 ").",
352 node, fd, DEVNUM_FORMAT_VAL(loop->devno), loop->diskseq);
353 return TAKE_FD(fd);
354}
355
22e932f4
DDM
356static int compare_arch(Architecture a, Architecture b) {
357 if (a == b)
358 return 0;
359
360 if (a == native_architecture())
361 return 1;
362
363 if (b == native_architecture())
364 return -1;
365
366#ifdef ARCHITECTURE_SECONDARY
367 if (a == ARCHITECTURE_SECONDARY)
368 return 1;
369
370 if (b == ARCHITECTURE_SECONDARY)
371 return -1;
372#endif
373
374 return 0;
375}
376
08f14be4
YW
377static int dissect_image(
378 DissectedImage *m,
4526113f 379 int fd,
0b214aa0 380 const char *devname,
89e62e0b 381 const VeritySettings *verity,
18d73705 382 const MountOptions *mount_options,
08f14be4 383 DissectImageFlags flags) {
8c1be37e 384
62ea0ed0 385 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL;
62ea0ed0 386 sd_id128_t usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
1f8fb21c 387 bool is_gpt, is_mbr, multiple_generic = false,
de98f631
LP
388 generic_rw = false, /* initialize to appease gcc */
389 generic_growfs = false;
8e766630 390 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
8c1be37e 391 _cleanup_free_ char *generic_node = NULL;
be30ad41 392 sd_id128_t generic_uuid = SD_ID128_NULL;
b387778c 393 const char *pttype = NULL, *sptuuid = NULL;
8c1be37e 394 blkid_partlist pl;
1f8fb21c 395 int r, generic_nr = -1, n_partitions;
8c1be37e 396
08f14be4 397 assert(m);
8c1be37e 398 assert(fd >= 0);
0b214aa0 399 assert(devname);
a0bff7ea 400 assert(!verity || verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
89e62e0b 401 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
a0bff7ea
LP
402 assert(!verity || verity->root_hash_sig || verity->root_hash_sig_size == 0);
403 assert(!verity || (verity->root_hash || !verity->root_hash_sig));
e7cbe5cb 404 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
8c1be37e
LP
405
406 /* Probes a disk image, and returns information about what it found in *ret.
407 *
4623e8e6 408 * Returns -ENOPKG if no suitable partition table or file system could be found.
2679f407
LP
409 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
410 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
411 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that */
4623e8e6 412
89e62e0b 413 if (verity && verity->root_hash) {
aee36b4e
LP
414 sd_id128_t fsuuid, vuuid;
415
416 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
417 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
418 * the final 128bit. */
4623e8e6 419
89e62e0b 420 if (verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
421 return -EINVAL;
422
aee36b4e
LP
423 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
424 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
4623e8e6 425
aee36b4e 426 if (sd_id128_is_null(fsuuid))
4623e8e6 427 return -EINVAL;
aee36b4e 428 if (sd_id128_is_null(vuuid))
4623e8e6 429 return -EINVAL;
aee36b4e
LP
430
431 /* If the verity data declares it's for the /usr partition, then search for that, in all
432 * other cases assume it's for the root partition. */
433 if (verity->designator == PARTITION_USR) {
434 usr_uuid = fsuuid;
435 usr_verity_uuid = vuuid;
436 } else {
437 root_uuid = fsuuid;
438 root_verity_uuid = vuuid;
439 }
4623e8e6 440 }
8c1be37e 441
8c1be37e
LP
442 b = blkid_new_probe();
443 if (!b)
444 return -ENOMEM;
445
446 errno = 0;
447 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f 448 if (r != 0)
66855de7 449 return errno_or_else(ENOMEM);
8c1be37e 450
9b6deb03
LP
451 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
452 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
453 blkid_probe_enable_superblocks(b, 1);
b387778c 454 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE|BLKID_SUBLKS_UUID);
9b6deb03
LP
455 }
456
8c1be37e
LP
457 blkid_probe_enable_partitions(b, 1);
458 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
459
460 errno = 0;
461 r = blkid_do_safeprobe(b);
2e3944b8 462 if (r == _BLKID_SAFEPROBE_ERROR)
66855de7 463 return errno_or_else(EIO);
2e3944b8
LP
464 if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
465 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
466
467 assert(r == _BLKID_SAFEPROBE_FOUND);
8c1be37e 468
e7cbe5cb 469 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
4b5de5dd 470 (flags & DISSECT_IMAGE_GENERIC_ROOT)) ||
e7cbe5cb 471 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
9b6deb03 472 const char *usage = NULL;
8c1be37e 473
aee36b4e
LP
474 /* If flags permit this, also allow using non-partitioned single-filesystem images */
475
9b6deb03
LP
476 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
477 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
18d73705 478 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
b387778c 479 const char *fstype = NULL, *options = NULL, *suuid = NULL;
f7725647 480 _cleanup_close_ int mount_node_fd = -1;
b387778c 481 sd_id128_t uuid = SD_ID128_NULL;
f7725647 482
73d88b80 483 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
f7725647
YW
484 mount_node_fd = open_partition(devname, /* is_partition = */ false, m->loop);
485 if (mount_node_fd < 0)
486 return mount_node_fd;
487 }
8c1be37e 488
9b6deb03
LP
489 /* OK, we have found a file system, that's our root partition then. */
490 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
b387778c 491 (void) blkid_probe_lookup_value(b, "UUID", &suuid, NULL);
8c1be37e 492
9b6deb03
LP
493 if (fstype) {
494 t = strdup(fstype);
495 if (!t)
496 return -ENOMEM;
497 }
498
b387778c
LP
499 if (suuid) {
500 /* blkid will return FAT's serial number as UUID, hence it is quite possible
501 * that parsing this will fail. We'll ignore the ID, since it's just too
502 * short to be useful as tru identifier. */
503 r = sd_id128_from_string(suuid, &uuid);
504 if (r < 0)
505 log_debug_errno(r, "Failed to parse file system UUID '%s', ignoring: %m", suuid);
506 }
507
6c544d14
LP
508 n = strdup(devname);
509 if (!n)
510 return -ENOMEM;
511
e7cbe5cb 512 m->single_file_system = true;
c3c88d67
LP
513 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
514
515 m->has_verity = verity && verity->data_path;
516 m->verity_ready = m->has_verity &&
517 verity->root_hash &&
518 (verity->designator < 0 || verity->designator == PARTITION_ROOT);
e7cbe5cb 519
8ee9615e
LP
520 m->has_verity_sig = false; /* signature not embedded, must be specified */
521 m->verity_sig_ready = m->verity_ready &&
522 verity->root_hash_sig;
523
b387778c
LP
524 m->image_uuid = uuid;
525
f5215bc8 526 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
527 if (options) {
528 o = strdup(options);
529 if (!o)
530 return -ENOMEM;
531 }
532
9b6deb03
LP
533 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
534 .found = true,
e0d53d52 535 .rw = !m->verity_ready && !fstype_is_ro(fstype),
9b6deb03
LP
536 .partno = -1,
537 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
538 .fstype = TAKE_PTR(t),
539 .node = TAKE_PTR(n),
18d73705 540 .mount_options = TAKE_PTR(o),
f7725647 541 .mount_node_fd = TAKE_FD(mount_node_fd),
88b3300f
LP
542 .offset = 0,
543 .size = UINT64_MAX,
9b6deb03 544 };
8c1be37e 545
9b6deb03
LP
546 return 0;
547 }
8c1be37e
LP
548 }
549
550 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
551 if (!pttype)
552 return -ENOPKG;
553
554 is_gpt = streq_ptr(pttype, "gpt");
555 is_mbr = streq_ptr(pttype, "dos");
556
9b6deb03 557 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
558 return -ENOPKG;
559
0903fd26
LP
560 /* We support external verity data partitions only if the image has no partition table */
561 if (verity && verity->data_path)
562 return -EBADR;
563
73d88b80 564 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
08f14be4
YW
565 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
566 * do partition scanning. */
567 r = blockdev_partscan_enabled(fd);
568 if (r < 0)
569 return r;
570 if (r == 0)
571 return -EPROTONOSUPPORT;
572 }
4ba86848 573
b387778c
LP
574 (void) blkid_probe_lookup_value(b, "PTUUID", &sptuuid, NULL);
575 if (sptuuid) {
576 r = sd_id128_from_string(sptuuid, &m->image_uuid);
577 if (r < 0)
578 log_debug_errno(r, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid);
579 }
580
8c1be37e
LP
581 errno = 0;
582 pl = blkid_probe_get_partitions(b);
b382db9f 583 if (!pl)
66855de7 584 return errno_or_else(ENOMEM);
8c1be37e 585
4ba86848
LP
586 errno = 0;
587 n_partitions = blkid_partlist_numof_partitions(pl);
588 if (n_partitions < 0)
589 return errno_or_else(EIO);
8c1be37e 590
4ba86848 591 for (int i = 0; i < n_partitions; i++) {
1b010ae7 592 _cleanup_free_ char *node = NULL;
9b6deb03 593 unsigned long long pflags;
88b3300f 594 blkid_loff_t start, size;
8c1be37e 595 blkid_partition pp;
8c1be37e
LP
596 int nr;
597
4ba86848
LP
598 errno = 0;
599 pp = blkid_partlist_get_partition(pl, i);
600 if (!pp)
601 return errno_or_else(EIO);
aae22eb3 602
9b6deb03 603 pflags = blkid_partition_get_flags(pp);
8c1be37e 604
4ba86848 605 errno = 0;
8c1be37e
LP
606 nr = blkid_partition_get_partno(pp);
607 if (nr < 0)
4ba86848 608 return errno_or_else(EIO);
8c1be37e 609
88b3300f
LP
610 errno = 0;
611 start = blkid_partition_get_start(pp);
612 if (start < 0)
613 return errno_or_else(EIO);
614
615 assert((uint64_t) start < UINT64_MAX/512);
616
617 errno = 0;
618 size = blkid_partition_get_size(pp);
619 if (size < 0)
620 return errno_or_else(EIO);
621
622 assert((uint64_t) size < UINT64_MAX/512);
623
1b010ae7
LP
624 r = make_partition_devname(devname, nr, &node);
625 if (r < 0)
626 return r;
627
628 /* So here's the thing: after the main ("whole") block device popped up it might take a while
629 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
630 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
631 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
632 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
633 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
634 * also good as the outcome is the same: the partition block device exists, and we can use
635 * it.
636 *
637 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
638 * partition already existent. */
639
73d88b80 640 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
08f14be4
YW
641 r = block_device_add_partition(fd, node, nr, (uint64_t) start * 512, (uint64_t) size * 512);
642 if (r < 0) {
643 if (r != -EBUSY)
644 return log_debug_errno(r, "BLKPG_ADD_PARTITION failed: %m");
1b010ae7 645
08f14be4
YW
646 log_debug_errno(r, "Kernel was quicker than us in adding partition %i.", nr);
647 } else
648 log_debug("We were quicker than kernel in adding partition %i.", nr);
649 }
1b010ae7 650
8c1be37e 651 if (is_gpt) {
e3b9a5ff 652 const char *fstype = NULL, *label;
4623e8e6 653 sd_id128_t type_id, id;
22e932f4 654 GptPartitionType type;
de98f631 655 bool rw = true, growfs = false;
8c1be37e 656
e3b9a5ff
LP
657 r = blkid_partition_get_uuid_id128(pp, &id);
658 if (r < 0) {
659 log_debug_errno(r, "Failed to read partition UUID, ignoring: %m");
4623e8e6 660 continue;
e3b9a5ff 661 }
4623e8e6 662
e3b9a5ff
LP
663 r = blkid_partition_get_type_id128(pp, &type_id);
664 if (r < 0) {
665 log_debug_errno(r, "Failed to read partition type UUID, ignoring: %m");
8c1be37e 666 continue;
e3b9a5ff 667 }
8c1be37e 668
22e932f4
DDM
669 type = gpt_partition_type_from_uuid(type_id);
670
08fe0a53
LP
671 label = blkid_partition_get_name(pp); /* libblkid returns NULL here if empty */
672
fb3921b8
LP
673 if (IN_SET(type.designator,
674 PARTITION_HOME,
675 PARTITION_SRV,
676 PARTITION_XBOOTLDR,
677 PARTITION_TMP)) {
a48dd347 678
92e72028
ZJS
679 check_partition_flags(node, pflags,
680 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
0f7c9a3d 681
92e72028 682 if (pflags & SD_GPT_FLAG_NO_AUTO)
a48dd347
LP
683 continue;
684
92e72028
ZJS
685 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
686 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
aee36b4e 687
22e932f4 688 } else if (type.designator == PARTITION_ESP) {
a48dd347 689
92e72028
ZJS
690 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
691 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
aee36b4e
LP
692 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
693 * Partitions"). */
a48dd347 694
92e72028 695 if (pflags & SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
a48dd347
LP
696 continue;
697
8c1be37e 698 fstype = "vfat";
a8c47660 699
22e932f4 700 } else if (type.designator == PARTITION_ROOT) {
4623e8e6 701
92e72028
ZJS
702 check_partition_flags(node, pflags,
703 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
0f7c9a3d 704
92e72028 705 if (pflags & SD_GPT_FLAG_NO_AUTO)
a48dd347
LP
706 continue;
707
4623e8e6
LP
708 /* If a root ID is specified, ignore everything but the root id */
709 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
710 continue;
711
92e72028
ZJS
712 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
713 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
aee36b4e 714
22e932f4 715 } else if (type.designator == PARTITION_ROOT_VERITY) {
4623e8e6 716
92e72028
ZJS
717 check_partition_flags(node, pflags,
718 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
0f7c9a3d 719
92e72028 720 if (pflags & SD_GPT_FLAG_NO_AUTO)
a48dd347
LP
721 continue;
722
c3c88d67 723 m->has_verity = true;
4623e8e6 724
8ee9615e
LP
725 /* If no verity configuration is specified, then don't do verity */
726 if (!verity)
727 continue;
728 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
729 continue;
730
731 /* If root hash is specified, then ignore everything but the root id */
732 if (!sd_id128_is_null(root_verity_uuid) && !sd_id128_equal(root_verity_uuid, id))
4623e8e6
LP
733 continue;
734
4623e8e6 735 fstype = "DM_verity_hash";
4623e8e6 736 rw = false;
8ee9615e 737
22e932f4 738 } else if (type.designator == PARTITION_ROOT_VERITY_SIG) {
8ee9615e 739
92e72028
ZJS
740 check_partition_flags(node, pflags,
741 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
8ee9615e 742
92e72028 743 if (pflags & SD_GPT_FLAG_NO_AUTO)
8ee9615e
LP
744 continue;
745
746 m->has_verity_sig = true;
747
8ee9615e
LP
748 if (!verity)
749 continue;
750 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
751 continue;
8ee9615e 752
8ee9615e 753 fstype = "verity_hash_signature";
4623e8e6 754 rw = false;
8ee9615e 755
22e932f4 756 } else if (type.designator == PARTITION_USR) {
aee36b4e 757
92e72028
ZJS
758 check_partition_flags(node, pflags,
759 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
aee36b4e 760
92e72028 761 if (pflags & SD_GPT_FLAG_NO_AUTO)
aee36b4e
LP
762 continue;
763
764 /* If a usr ID is specified, ignore everything but the usr id */
765 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
766 continue;
767
92e72028
ZJS
768 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
769 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
aee36b4e 770
22e932f4 771 } else if (type.designator == PARTITION_USR_VERITY) {
aee36b4e 772
92e72028
ZJS
773 check_partition_flags(node, pflags,
774 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
aee36b4e 775
92e72028 776 if (pflags & SD_GPT_FLAG_NO_AUTO)
aee36b4e
LP
777 continue;
778
c3c88d67 779 m->has_verity = true;
aee36b4e 780
8ee9615e
LP
781 if (!verity)
782 continue;
783 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
784 continue;
785
786 /* If usr hash is specified, then ignore everything but the usr id */
787 if (!sd_id128_is_null(usr_verity_uuid) && !sd_id128_equal(usr_verity_uuid, id))
aee36b4e
LP
788 continue;
789
aee36b4e 790 fstype = "DM_verity_hash";
aee36b4e 791 rw = false;
8ee9615e 792
22e932f4 793 } else if (type.designator == PARTITION_USR_VERITY_SIG) {
8ee9615e 794
92e72028
ZJS
795 check_partition_flags(node, pflags,
796 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
8ee9615e 797
92e72028 798 if (pflags & SD_GPT_FLAG_NO_AUTO)
8ee9615e
LP
799 continue;
800
801 m->has_verity_sig = true;
802
8ee9615e
LP
803 if (!verity)
804 continue;
805 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
806 continue;
8ee9615e 807
8ee9615e 808 fstype = "verity_hash_signature";
aee36b4e 809 rw = false;
8ee9615e 810
22e932f4 811 } else if (type.designator == PARTITION_SWAP) {
a48dd347 812
92e72028 813 check_partition_flags(node, pflags, SD_GPT_FLAG_NO_AUTO);
0f7c9a3d 814
92e72028 815 if (pflags & SD_GPT_FLAG_NO_AUTO)
a48dd347
LP
816 continue;
817
df4524cb
LP
818 fstype = "swap";
819
df655bf3
DDM
820 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
821 } else if (sd_id128_equal(type.uuid, SD_GPT_LINUX_GENERIC)) {
8c1be37e 822
92e72028
ZJS
823 check_partition_flags(node, pflags,
824 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
0f7c9a3d 825
92e72028 826 if (pflags & SD_GPT_FLAG_NO_AUTO)
a48dd347
LP
827 continue;
828
8c1be37e
LP
829 if (generic_node)
830 multiple_generic = true;
831 else {
832 generic_nr = nr;
92e72028
ZJS
833 generic_rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
834 generic_growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
be30ad41 835 generic_uuid = id;
8c1be37e
LP
836 generic_node = strdup(node);
837 if (!generic_node)
838 return -ENOMEM;
839 }
d4dffb85 840
22e932f4 841 } else if (type.designator == PARTITION_VAR) {
d4dffb85 842
92e72028
ZJS
843 check_partition_flags(node, pflags,
844 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
0f7c9a3d 845
92e72028 846 if (pflags & SD_GPT_FLAG_NO_AUTO)
d4dffb85
LP
847 continue;
848
849 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
850 sd_id128_t var_uuid;
851
852 /* For /var we insist that the uuid of the partition matches the
853 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
854 * ID. Why? Unlike the other partitions /var is inherently
855 * installation specific, hence we need to be careful not to mount it
856 * in the wrong installation. By hashing the partition UUID from
857 * /etc/machine-id we can securely bind the partition to the
858 * installation. */
859
92e72028 860 r = sd_id128_get_machine_app_specific(SD_GPT_VAR, &var_uuid);
d4dffb85
LP
861 if (r < 0)
862 return r;
863
864 if (!sd_id128_equal(var_uuid, id)) {
a52efa81
YW
865 log_debug("Found a /var/ partition, but its UUID didn't match our expectations "
866 "(found: " SD_ID128_UUID_FORMAT_STR ", expected: " SD_ID128_UUID_FORMAT_STR "), ignoring.",
867 SD_ID128_FORMAT_VAL(id), SD_ID128_FORMAT_VAL(var_uuid));
d4dffb85
LP
868 continue;
869 }
870 }
871
92e72028
ZJS
872 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
873 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
8c1be37e
LP
874 }
875
22e932f4 876 if (type.designator != _PARTITION_DESIGNATOR_INVALID) {
0fb5036f 877 _cleanup_free_ char *t = NULL, *o = NULL, *l = NULL;
f7725647 878 _cleanup_close_ int mount_node_fd = -1;
18d73705 879 const char *options = NULL;
8c1be37e 880
22e932f4 881 if (m->partitions[type.designator].found) {
08fe0a53
LP
882 /* For most partition types the first one we see wins. Except for the
883 * rootfs and /usr, where we do a version compare of the label, and
884 * let the newest version win. This permits a simple A/B versioning
885 * scheme in OS images. */
886
22e932f4
DDM
887 if (compare_arch(type.arch, m->partitions[type.designator].architecture) <= 0)
888 continue;
889
890 if (!partition_designator_is_versioned(type.designator) ||
891 strverscmp_improved(m->partitions[type.designator].label, label) >= 0)
08fe0a53
LP
892 continue;
893
22e932f4 894 dissected_partition_done(m->partitions + type.designator);
08fe0a53 895 }
8c1be37e 896
73d88b80 897 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES) &&
f52261a0 898 type.designator != PARTITION_SWAP) {
f7725647
YW
899 mount_node_fd = open_partition(node, /* is_partition = */ true, m->loop);
900 if (mount_node_fd < 0)
901 return mount_node_fd;
902 }
903
8c1be37e
LP
904 if (fstype) {
905 t = strdup(fstype);
906 if (!t)
907 return -ENOMEM;
908 }
909
08fe0a53
LP
910 if (label) {
911 l = strdup(label);
912 if (!l)
913 return -ENOMEM;
914 }
915
22e932f4 916 options = mount_options_from_designator(mount_options, type.designator);
18d73705
LB
917 if (options) {
918 o = strdup(options);
919 if (!o)
920 return -ENOMEM;
921 }
922
22e932f4 923 m->partitions[type.designator] = (DissectedPartition) {
8c1be37e
LP
924 .found = true,
925 .partno = nr,
926 .rw = rw,
de98f631 927 .growfs = growfs,
22e932f4 928 .architecture = type.arch,
0fb5036f 929 .node = TAKE_PTR(node),
1cc6c93a 930 .fstype = TAKE_PTR(t),
08fe0a53 931 .label = TAKE_PTR(l),
be30ad41 932 .uuid = id,
18d73705 933 .mount_options = TAKE_PTR(o),
f7725647 934 .mount_node_fd = TAKE_FD(mount_node_fd),
88b3300f
LP
935 .offset = (uint64_t) start * 512,
936 .size = (uint64_t) size * 512,
d90b03f8 937 .gpt_flags = pflags,
8c1be37e 938 };
8c1be37e
LP
939 }
940
941 } else if (is_mbr) {
942
a8c47660 943 switch (blkid_partition_get_type(pp)) {
8c1be37e 944
a8c47660
LP
945 case 0x83: /* Linux partition */
946
947 if (pflags != 0x80) /* Bootable flag */
948 continue;
8c1be37e 949
a8c47660
LP
950 if (generic_node)
951 multiple_generic = true;
952 else {
953 generic_nr = nr;
954 generic_rw = true;
de98f631 955 generic_growfs = false;
a8c47660
LP
956 generic_node = strdup(node);
957 if (!generic_node)
958 return -ENOMEM;
959 }
960
961 break;
962
963 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
f7725647 964 _cleanup_close_ int mount_node_fd = -1;
0fb5036f 965 _cleanup_free_ char *o = NULL;
a8c47660 966 sd_id128_t id = SD_ID128_NULL;
e3b9a5ff 967 const char *options = NULL;
a8c47660
LP
968
969 /* First one wins */
234c2e16 970 if (m->partitions[PARTITION_XBOOTLDR].found)
a8c47660
LP
971 continue;
972
73d88b80 973 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
f7725647
YW
974 mount_node_fd = open_partition(node, /* is_partition = */ true, m->loop);
975 if (mount_node_fd < 0)
976 return mount_node_fd;
977 }
978
e3b9a5ff 979 (void) blkid_partition_get_uuid_id128(pp, &id);
a8c47660 980
f5215bc8 981 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
18d73705
LB
982 if (options) {
983 o = strdup(options);
984 if (!o)
985 return -ENOMEM;
986 }
987
a8c47660
LP
988 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
989 .found = true,
990 .partno = nr,
991 .rw = true,
de98f631 992 .growfs = false,
a8c47660 993 .architecture = _ARCHITECTURE_INVALID,
0fb5036f 994 .node = TAKE_PTR(node),
a8c47660 995 .uuid = id,
18d73705 996 .mount_options = TAKE_PTR(o),
f7725647 997 .mount_node_fd = TAKE_FD(mount_node_fd),
88b3300f
LP
998 .offset = (uint64_t) start * 512,
999 .size = (uint64_t) size * 512,
a8c47660
LP
1000 };
1001
1002 break;
1003 }}
8c1be37e
LP
1004 }
1005 }
1006
22e932f4
DDM
1007 if (!m->partitions[PARTITION_ROOT].found &&
1008 (m->partitions[PARTITION_ROOT_VERITY].found ||
1009 m->partitions[PARTITION_ROOT_VERITY_SIG].found))
1010 return -EADDRNOTAVAIL; /* Verity found but no matching rootfs? Something is off, refuse. */
49ae9d91 1011
8ee9615e
LP
1012 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1013 if (m->partitions[PARTITION_ROOT_VERITY_SIG].found && !m->partitions[PARTITION_ROOT_VERITY].found)
1014 return -EADDRNOTAVAIL;
7cf66030 1015
22e932f4
DDM
1016 if (!m->partitions[PARTITION_USR].found &&
1017 (m->partitions[PARTITION_USR_VERITY].found ||
1018 m->partitions[PARTITION_USR_VERITY_SIG].found))
1019 return -EADDRNOTAVAIL; /* as above */
7cf66030 1020
22e932f4 1021 /* as above */
8ee9615e
LP
1022 if (m->partitions[PARTITION_USR_VERITY_SIG].found && !m->partitions[PARTITION_USR_VERITY].found)
1023 return -EADDRNOTAVAIL;
1024
cb241a69
LP
1025 /* If root and /usr are combined then insist that the architecture matches */
1026 if (m->partitions[PARTITION_ROOT].found &&
1027 m->partitions[PARTITION_USR].found &&
1028 (m->partitions[PARTITION_ROOT].architecture >= 0 &&
1029 m->partitions[PARTITION_USR].architecture >= 0 &&
1030 m->partitions[PARTITION_ROOT].architecture != m->partitions[PARTITION_USR].architecture))
1031 return -EADDRNOTAVAIL;
1032
4ab51780
LP
1033 if (!m->partitions[PARTITION_ROOT].found &&
1034 !m->partitions[PARTITION_USR].found &&
1035 (flags & DISSECT_IMAGE_GENERIC_ROOT) &&
00a8b34f 1036 (!verity || !verity->root_hash || verity->designator != PARTITION_USR)) {
7cf66030 1037
1b010ae7 1038 /* OK, we found nothing usable, then check if there's a single generic partition, and use
4b5de5dd
LP
1039 * that. If the root hash was set however, then we won't fall back to a generic node, because
1040 * the root hash decides. */
7cf66030
LP
1041
1042 /* If we didn't find a properly marked root partition, but we did find a single suitable
1043 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1044 if (multiple_generic)
1045 return -ENOTUNIQ;
1046
4b5de5dd
LP
1047 /* If we didn't find a generic node, then we can't fix this up either */
1048 if (generic_node) {
f7725647 1049 _cleanup_close_ int mount_node_fd = -1;
4b5de5dd
LP
1050 _cleanup_free_ char *o = NULL;
1051 const char *options;
8c1be37e 1052
73d88b80 1053 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
f7725647
YW
1054 mount_node_fd = open_partition(generic_node, /* is_partition = */ true, m->loop);
1055 if (mount_node_fd < 0)
1056 return mount_node_fd;
1057 }
1058
f5215bc8 1059 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
1060 if (options) {
1061 o = strdup(options);
1062 if (!o)
1063 return -ENOMEM;
1064 }
1065
1f8fb21c 1066 assert(generic_nr >= 0);
8c1be37e
LP
1067 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1068 .found = true,
1069 .rw = generic_rw,
de98f631 1070 .growfs = generic_growfs,
8c1be37e
LP
1071 .partno = generic_nr,
1072 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 1073 .node = TAKE_PTR(generic_node),
be30ad41 1074 .uuid = generic_uuid,
18d73705 1075 .mount_options = TAKE_PTR(o),
f7725647 1076 .mount_node_fd = TAKE_FD(mount_node_fd),
88b3300f
LP
1077 .offset = UINT64_MAX,
1078 .size = UINT64_MAX,
8c1be37e 1079 };
e0f9e7bd 1080 }
8c1be37e
LP
1081 }
1082
4b5de5dd
LP
1083 /* Check if we have a root fs if we are told to do check. /usr alone is fine too, but only if appropriate flag for that is set too */
1084 if (FLAGS_SET(flags, DISSECT_IMAGE_REQUIRE_ROOT) &&
1085 !(m->partitions[PARTITION_ROOT].found || (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1086 return -ENXIO;
1087
7b32164f
LP
1088 if (m->partitions[PARTITION_ROOT_VERITY].found) {
1089 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1090 if (m->partitions[PARTITION_USR_VERITY].found)
1091 return -ENOTUNIQ;
1092
1093 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1094 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1095 if (m->partitions[PARTITION_USR].found)
1096 return -EADDRNOTAVAIL;
1097 }
aee36b4e 1098
1903defc
LP
1099 if (verity) {
1100 /* If a verity designator is specified, then insist that the matching partition exists */
1101 if (verity->designator >= 0 && !m->partitions[verity->designator].found)
1102 return -EADDRNOTAVAIL;
aee36b4e 1103
3dd73ea7
DDM
1104 bool have_verity_sig_partition =
1105 m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR_VERITY_SIG : PARTITION_ROOT_VERITY_SIG].found;
1106
1903defc 1107 if (verity->root_hash) {
8ee9615e
LP
1108 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1109 * Verity, set things up for it */
1110
1903defc
LP
1111 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1112 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1113 return -EADDRNOTAVAIL;
4623e8e6 1114
1903defc
LP
1115 /* If we found a verity setup, then the root partition is necessarily read-only. */
1116 m->partitions[PARTITION_ROOT].rw = false;
1117 m->verity_ready = true;
1903defc 1118
f9e0bb61
LP
1119 } else {
1120 assert(verity->designator == PARTITION_USR);
1121
1903defc
LP
1122 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1123 return -EADDRNOTAVAIL;
4623e8e6 1124
1903defc
LP
1125 m->partitions[PARTITION_USR].rw = false;
1126 m->verity_ready = true;
1127 }
8ee9615e
LP
1128
1129 if (m->verity_ready)
3dd73ea7 1130 m->verity_sig_ready = verity->root_hash_sig || have_verity_sig_partition;
8ee9615e 1131
3dd73ea7 1132 } else if (have_verity_sig_partition) {
8ee9615e
LP
1133
1134 /* If we found an embedded signature partition, we are ready, too. */
1135
1136 m->verity_ready = m->verity_sig_ready = true;
1137 m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR : PARTITION_ROOT].rw = false;
aee36b4e 1138 }
4623e8e6
LP
1139 }
1140
c80c9079
LP
1141 r = dissected_image_probe_filesystems(m, fd);
1142 if (r < 0)
1143 return r;
1144
08f14be4
YW
1145 return 0;
1146}
1147#endif
18b5886e 1148
08f14be4
YW
1149int dissect_image_file(
1150 const char *path,
1151 const VeritySettings *verity,
1152 const MountOptions *mount_options,
1153 DissectImageFlags flags,
1154 DissectedImage **ret) {
8c1be37e 1155
08f14be4
YW
1156#if HAVE_BLKID
1157 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
1158 _cleanup_close_ int fd = -1;
1159 int r;
8c1be37e 1160
08f14be4 1161 assert(path);
08f14be4 1162 assert(ret);
8c1be37e 1163
08f14be4
YW
1164 fd = open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1165 if (fd < 0)
1166 return -errno;
896f937f 1167
08f14be4
YW
1168 r = fd_verify_regular(fd);
1169 if (r < 0)
1170 return r;
de98f631 1171
08f14be4
YW
1172 r = dissected_image_new(path, &m);
1173 if (r < 0)
1174 return r;
1175
1176 r = dissect_image(m, fd, path, verity, mount_options, flags);
698bb074
YW
1177 if (r < 0)
1178 return r;
8c1be37e 1179
1cc6c93a 1180 *ret = TAKE_PTR(m);
8c1be37e
LP
1181 return 0;
1182#else
1183 return -EOPNOTSUPP;
1184#endif
1185}
1186
1187DissectedImage* dissected_image_unref(DissectedImage *m) {
8c1be37e
LP
1188 if (!m)
1189 return NULL;
1190
ac1e1b5f 1191 /* First, clear dissected partitions. */
08fe0a53 1192 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
234c2e16 1193 dissected_partition_done(m->partitions + i);
8c1be37e 1194
ac1e1b5f
YW
1195 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1196 * DecryptedImage may try to deactivate partitions. */
1197 decrypted_image_unref(m->decrypted_image);
1198
1e63dc4f
YW
1199 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1200 * remove existing partitions on the loopback block device. */
1201 loop_device_unref(m->loop);
1202
593fe6c0 1203 free(m->image_name);
3b925504
LP
1204 free(m->hostname);
1205 strv_free(m->machine_info);
1206 strv_free(m->os_release);
fab22946 1207 strv_free(m->initrd_release);
7718ac97 1208 strv_free(m->extension_release);
3b925504 1209
5fecf46d 1210 return mfree(m);
8c1be37e
LP
1211}
1212
18b5886e 1213static int is_loop_device(const char *path) {
553e15f2 1214 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
1215 struct stat st;
1216
1217 assert(path);
1218
1219 if (stat(path, &st) < 0)
1220 return -errno;
1221
1222 if (!S_ISBLK(st.st_mode))
1223 return -ENOTBLK;
1224
553e15f2 1225 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
1226 if (access(s, F_OK) < 0) {
1227 if (errno != ENOENT)
1228 return -errno;
1229
1230 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 1231 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
1232 if (access(s, F_OK) < 0)
1233 return errno == ENOENT ? false : -errno;
1234 }
1235
1236 return true;
1237}
1238
f8ab7812 1239static int run_fsck(int node_fd, const char *fstype) {
cf32c486
LP
1240 int r, exit_status;
1241 pid_t pid;
1242
f8ab7812 1243 assert(node_fd >= 0);
cf32c486
LP
1244 assert(fstype);
1245
13556724 1246 r = fsck_exists_for_fstype(fstype);
cf32c486
LP
1247 if (r < 0) {
1248 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1249 return 0;
1250 }
1251 if (r == 0) {
f8ab7812 1252 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd), fstype);
cf32c486
LP
1253 return 0;
1254 }
1255
f8ab7812
LP
1256 r = safe_fork_full(
1257 "(fsck)",
1258 &node_fd, 1, /* Leave the node fd open */
1259 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO|FORK_CLOEXEC_OFF,
1260 &pid);
cf32c486
LP
1261 if (r < 0)
1262 return log_debug_errno(r, "Failed to fork off fsck: %m");
1263 if (r == 0) {
1264 /* Child */
f8ab7812 1265 execl("/sbin/fsck", "/sbin/fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd), NULL);
7e0ed2e9 1266 log_open();
cf32c486
LP
1267 log_debug_errno(errno, "Failed to execl() fsck: %m");
1268 _exit(FSCK_OPERATIONAL_ERROR);
1269 }
1270
1271 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1272 if (exit_status < 0)
1273 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1274
1275 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1276 log_debug("fsck failed with exit status %i.", exit_status);
1277
1278 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1279 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1280
1281 log_debug("Ignoring fsck error.");
1282 }
1283
1284 return 0;
1285}
1286
81939d9d
LP
1287static int fs_grow(const char *node_path, const char *mount_path) {
1288 _cleanup_close_ int mount_fd = -1, node_fd = -1;
81939d9d
LP
1289 uint64_t size, newsize;
1290 int r;
1291
1292 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1293 if (node_fd < 0)
1294 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
1295
1296 if (ioctl(node_fd, BLKGETSIZE64, &size) != 0)
1297 return log_debug_errno(errno, "Failed to get block device size of %s: %m", node_path);
1298
1299 mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1300 if (mount_fd < 0)
1301 return log_debug_errno(errno, "Failed to open mountd file system %s: %m", mount_path);
1302
1303 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", mount_path, size);
1304 r = resize_fs(mount_fd, size, &newsize);
1305 if (r < 0)
1306 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", mount_path, size);
1307
1308 if (newsize == size)
1309 log_debug("Successfully resized \"%s\" to %s bytes.",
2b59bf51 1310 mount_path, FORMAT_BYTES(newsize));
81939d9d
LP
1311 else {
1312 assert(newsize < size);
1313 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
2b59bf51 1314 mount_path, FORMAT_BYTES(newsize), size - newsize);
81939d9d
LP
1315 }
1316
1317 return 0;
1318}
1319
18b5886e
LP
1320static int mount_partition(
1321 DissectedPartition *m,
1322 const char *where,
1323 const char *directory,
2d3a5a73 1324 uid_t uid_shift,
21b61b1d 1325 uid_t uid_range,
18b5886e
LP
1326 DissectImageFlags flags) {
1327
2d3a5a73
LP
1328 _cleanup_free_ char *chased = NULL, *options = NULL;
1329 const char *p, *node, *fstype;
21b61b1d 1330 bool rw, remap_uid_gid = false;
2eedfd2d 1331 int r;
8c1be37e
LP
1332
1333 assert(m);
1334 assert(where);
1335
f7725647
YW
1336 if (m->mount_node_fd < 0)
1337 return 0;
1338
4dc28665 1339 /* Use decrypted node and matching fstype if available, otherwise use the original device */
f7725647 1340 node = FORMAT_PROC_FD_PATH(m->mount_node_fd);
4dc28665 1341 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
18b5886e 1342
4dc28665
LP
1343 if (!fstype)
1344 return -EAFNOSUPPORT;
8c1be37e 1345
68ac5118
ZJS
1346 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller
1347 * didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this
1348 * case. */
4dc28665 1349 if (streq(fstype, "crypto_LUKS"))
fa45d12c 1350 return -EUNATCH;
18b5886e 1351
ef9c184d 1352 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
8c1be37e 1353
cf32c486 1354 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
f8ab7812 1355 r = run_fsck(m->mount_node_fd, fstype);
cf32c486
LP
1356 if (r < 0)
1357 return r;
1358 }
1359
2eedfd2d 1360 if (directory) {
334eb5b0
LP
1361 /* Automatically create missing mount points inside the image, if necessary. */
1362 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1363 if (r < 0 && r != -EROFS)
1364 return r;
1f0f82f1 1365
a5648b80 1366 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2eedfd2d
LP
1367 if (r < 0)
1368 return r;
1369
1370 p = chased;
9842905e
LP
1371 } else {
1372 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1373 * image (as the branch above does) but the host hierarchy, and the created directory might
1374 * survive our mount in the host hierarchy hence. */
1375 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1376 r = mkdir_p(where, 0755);
1377 if (r < 0)
1378 return r;
1379 }
1380
8c1be37e 1381 p = where;
9842905e 1382 }
8c1be37e 1383
18b5886e 1384 /* If requested, turn on discard support. */
154d2269 1385 if (fstype_can_discard(fstype) &&
18b5886e 1386 ((flags & DISSECT_IMAGE_DISCARD) ||
3afda7c7 1387 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
2d3a5a73
LP
1388 options = strdup("discard");
1389 if (!options)
1390 return -ENOMEM;
1391 }
1392
21b61b1d 1393 if (uid_is_valid(uid_shift) && uid_shift != 0) {
2d3a5a73 1394
21b61b1d
LP
1395 if (fstype_can_uid_gid(fstype)) {
1396 _cleanup_free_ char *uid_option = NULL;
2d3a5a73 1397
21b61b1d
LP
1398 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1399 return -ENOMEM;
1400
1401 if (!strextend_with_separator(&options, ",", uid_option))
1402 return -ENOMEM;
1403 } else if (FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED))
1404 remap_uid_gid = true;
2d3a5a73 1405 }
8c1be37e 1406
18d73705 1407 if (!isempty(m->mount_options))
c2bc710b 1408 if (!strextend_with_separator(&options, ",", m->mount_options))
18d73705
LB
1409 return -ENOMEM;
1410
b620bf33
LP
1411 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1412 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1413 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1414 * from the upper file system still get propagated through to the underlying file system,
1415 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1416 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1417 * carry a per file system table here.
1418 *
1419 * Note that this means that we might not be able to mount corrupted file systems as read-only
1420 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1421 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1422 * mount options for loopback devices this is the right choice, since otherwise using the same
1423 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1424 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1425 * access that actually modifies stuff work on such image files. Or to say this differently: if
1426 * people want their file systems to be fixed up they should just open them in writable mode, where
1427 * all these problems don't exist. */
1428 if (!rw && STRPTR_IN_SET(fstype, "ext3", "ext4", "xfs", "btrfs"))
1429 if (!strextend_with_separator(&options, ",", "norecovery"))
1430 return -ENOMEM;
1431
511a8cfe 1432 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
d9223c07
LP
1433 if (r < 0)
1434 return r;
1435
81939d9d
LP
1436 if (rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS))
1437 (void) fs_grow(node, p);
1438
21b61b1d 1439 if (remap_uid_gid) {
2b2777ed 1440 r = remount_idmap(p, uid_shift, uid_range, UID_INVALID, REMOUNT_IDMAPPING_HOST_ROOT);
21b61b1d
LP
1441 if (r < 0)
1442 return r;
1443 }
1444
d9223c07 1445 return 1;
8c1be37e
LP
1446}
1447
7cf66030
LP
1448static int mount_root_tmpfs(const char *where, uid_t uid_shift, DissectImageFlags flags) {
1449 _cleanup_free_ char *options = NULL;
1450 int r;
1451
1452 assert(where);
1453
1454 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1455
1456 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1457 r = mkdir_p(where, 0755);
1458 if (r < 0)
1459 return r;
1460 }
1461
1462 if (uid_is_valid(uid_shift)) {
1463 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1464 return -ENOMEM;
1465 }
1466
1467 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
1468 if (r < 0)
1469 return r;
1470
1471 return 1;
1472}
1473
21b61b1d
LP
1474int dissected_image_mount(
1475 DissectedImage *m,
1476 const char *where,
1477 uid_t uid_shift,
1478 uid_t uid_range,
1479 DissectImageFlags flags) {
1480
1f0f82f1 1481 int r, xbootldr_mounted;
8c1be37e
LP
1482
1483 assert(m);
1484 assert(where);
1485
fa45d12c
LP
1486 /* Returns:
1487 *
1488 * -ENXIO → No root partition found
7718ac97 1489 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
fa45d12c
LP
1490 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1491 * -EUCLEAN → fsck for file system failed
1492 * -EBUSY → File system already mounted/used elsewhere (kernel)
4dc28665 1493 * -EAFNOSUPPORT → File system type not supported or not known
fa45d12c
LP
1494 */
1495
7cf66030
LP
1496 if (!(m->partitions[PARTITION_ROOT].found ||
1497 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1498 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
8c1be37e 1499
2d3a5a73 1500 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
7cf66030
LP
1501
1502 /* First mount the root fs. If there's none we use a tmpfs. */
1503 if (m->partitions[PARTITION_ROOT].found)
21b61b1d 1504 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, flags);
7cf66030
LP
1505 else
1506 r = mount_root_tmpfs(where, uid_shift, flags);
2d3a5a73
LP
1507 if (r < 0)
1508 return r;
aee36b4e 1509
aee36b4e 1510 /* For us mounting root always means mounting /usr as well */
21b61b1d 1511 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, flags);
aee36b4e
LP
1512 if (r < 0)
1513 return r;
03bcb6d4 1514
9ccb531a
LB
1515 if ((flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
1516 /* If either one of the validation flags are set, ensure that the image qualifies
1517 * as one or the other (or both). */
1518 bool ok = false;
1519
1520 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
1521 r = path_is_os_tree(where);
1522 if (r < 0)
1523 return r;
1524 if (r > 0)
1525 ok = true;
1526 }
1527 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT)) {
06768b90 1528 r = path_is_extension_tree(where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_SYSEXT_CHECK));
7718ac97
LB
1529 if (r < 0)
1530 return r;
9ccb531a
LB
1531 if (r > 0)
1532 ok = true;
7718ac97 1533 }
9ccb531a
LB
1534
1535 if (!ok)
1536 return -ENOMEDIUM;
03bcb6d4 1537 }
2d3a5a73
LP
1538 }
1539
705727fd 1540 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 1541 return 0;
8c1be37e 1542
21b61b1d 1543 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, flags);
8c1be37e
LP
1544 if (r < 0)
1545 return r;
1546
21b61b1d 1547 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, flags);
8c1be37e
LP
1548 if (r < 0)
1549 return r;
1550
21b61b1d 1551 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, flags);
d4dffb85
LP
1552 if (r < 0)
1553 return r;
1554
21b61b1d 1555 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, flags);
d4dffb85
LP
1556 if (r < 0)
1557 return r;
1558
21b61b1d 1559 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, flags);
1f0f82f1
LP
1560 if (xbootldr_mounted < 0)
1561 return xbootldr_mounted;
d9223c07 1562
8c1be37e 1563 if (m->partitions[PARTITION_ESP].found) {
1f0f82f1
LP
1564 int esp_done = false;
1565
d9223c07
LP
1566 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1567 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
8c1be37e 1568
a5648b80 1569 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1f0f82f1
LP
1570 if (r < 0) {
1571 if (r != -ENOENT)
d9223c07 1572 return r;
8c1be37e 1573
1f0f82f1
LP
1574 /* /efi doesn't exist. Let's see if /boot is suitable then */
1575
1576 if (!xbootldr_mounted) {
1577 _cleanup_free_ char *p = NULL;
2eedfd2d 1578
1f0f82f1
LP
1579 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1580 if (r < 0) {
1581 if (r != -ENOENT)
1582 return r;
db55bbf2 1583 } else if (dir_is_empty(p, /* ignore_hidden_or_backup= */ false) > 0) {
1f0f82f1 1584 /* It exists and is an empty directory. Let's mount the ESP there. */
21b61b1d 1585 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, uid_range, flags);
1f0f82f1
LP
1586 if (r < 0)
1587 return r;
1588
1589 esp_done = true;
1590 }
2eedfd2d 1591 }
8c1be37e 1592 }
1f0f82f1
LP
1593
1594 if (!esp_done) {
1595 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1596
21b61b1d 1597 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, uid_range, flags);
1f0f82f1
LP
1598 if (r < 0)
1599 return r;
1600 }
8c1be37e
LP
1601 }
1602
1603 return 0;
1604}
1605
21b61b1d
LP
1606int dissected_image_mount_and_warn(
1607 DissectedImage *m,
1608 const char *where,
1609 uid_t uid_shift,
1610 uid_t uid_range,
1611 DissectImageFlags flags) {
1612
af187ab2
LP
1613 int r;
1614
1615 assert(m);
1616 assert(where);
1617
21b61b1d 1618 r = dissected_image_mount(m, where, uid_shift, uid_range, flags);
af187ab2
LP
1619 if (r == -ENXIO)
1620 return log_error_errno(r, "Not root file system found in image.");
1621 if (r == -EMEDIUMTYPE)
7718ac97 1622 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
af187ab2
LP
1623 if (r == -EUNATCH)
1624 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1625 if (r == -EUCLEAN)
1626 return log_error_errno(r, "File system check on image failed.");
1627 if (r == -EBUSY)
1628 return log_error_errno(r, "File system already mounted elsewhere.");
4dc28665
LP
1629 if (r == -EAFNOSUPPORT)
1630 return log_error_errno(r, "File system type not supported or not known.");
af187ab2
LP
1631 if (r < 0)
1632 return log_error_errno(r, "Failed to mount image: %m");
1633
1634 return r;
1635}
1636
349cc4a5 1637#if HAVE_LIBCRYPTSETUP
9321ad51 1638struct DecryptedPartition {
18b5886e
LP
1639 struct crypt_device *device;
1640 char *name;
1641 bool relinquished;
9321ad51
YW
1642};
1643#endif
1644
1645typedef struct DecryptedPartition DecryptedPartition;
18b5886e
LP
1646
1647struct DecryptedImage {
9321ad51 1648 unsigned n_ref;
18b5886e
LP
1649 DecryptedPartition *decrypted;
1650 size_t n_decrypted;
18b5886e 1651};
18b5886e 1652
9321ad51 1653static DecryptedImage* decrypted_image_free(DecryptedImage *d) {
349cc4a5 1654#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1655 int r;
1656
1657 if (!d)
1658 return NULL;
1659
67f63ee5 1660 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
1661 DecryptedPartition *p = d->decrypted + i;
1662
1663 if (p->device && p->name && !p->relinquished) {
ea16d7f4
YW
1664 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
1665 r = sym_crypt_deactivate_by_name(p->device, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
1666 if (r < 0)
1667 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1668 }
1669
1670 if (p->device)
0d12936d 1671 sym_crypt_free(p->device);
18b5886e
LP
1672 free(p->name);
1673 }
1674
f91861e4 1675 free(d->decrypted);
18b5886e
LP
1676 free(d);
1677#endif
1678 return NULL;
1679}
1680
9321ad51
YW
1681DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage, decrypted_image, decrypted_image_free);
1682
349cc4a5 1683#if HAVE_LIBCRYPTSETUP
9321ad51
YW
1684static int decrypted_image_new(DecryptedImage **ret) {
1685 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
1686
1687 assert(ret);
1688
1689 d = new(DecryptedImage, 1);
1690 if (!d)
1691 return -ENOMEM;
1692
1693 *d = (DecryptedImage) {
1694 .n_ref = 1,
1695 };
1696
1697 *ret = TAKE_PTR(d);
1698 return 0;
1699}
4623e8e6
LP
1700
1701static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1702 _cleanup_free_ char *name = NULL, *node = NULL;
1703 const char *base;
1704
1705 assert(original_node);
1706 assert(suffix);
1707 assert(ret_name);
1708 assert(ret_node);
1709
1710 base = strrchr(original_node, '/');
1711 if (!base)
ac1f3ad0
LB
1712 base = original_node;
1713 else
1714 base++;
4623e8e6
LP
1715 if (isempty(base))
1716 return -EINVAL;
1717
1718 name = strjoin(base, suffix);
1719 if (!name)
1720 return -ENOMEM;
1721 if (!filename_is_valid(name))
1722 return -EINVAL;
1723
0d12936d 1724 node = path_join(sym_crypt_get_dir(), name);
4623e8e6
LP
1725 if (!node)
1726 return -ENOMEM;
1727
1cc6c93a
YW
1728 *ret_name = TAKE_PTR(name);
1729 *ret_node = TAKE_PTR(node);
4623e8e6 1730
4623e8e6
LP
1731 return 0;
1732}
1733
18b5886e
LP
1734static int decrypt_partition(
1735 DissectedPartition *m,
1736 const char *passphrase,
1737 DissectImageFlags flags,
1738 DecryptedImage *d) {
1739
1740 _cleanup_free_ char *node = NULL, *name = NULL;
0d12936d 1741 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
f7725647 1742 _cleanup_close_ int fd = -1;
18b5886e
LP
1743 int r;
1744
1745 assert(m);
1746 assert(d);
1747
1748 if (!m->found || !m->node || !m->fstype)
1749 return 0;
1750
1751 if (!streq(m->fstype, "crypto_LUKS"))
1752 return 0;
1753
bdd73ac5
ZJS
1754 if (!passphrase)
1755 return -ENOKEY;
1756
0d12936d
LP
1757 r = dlopen_cryptsetup();
1758 if (r < 0)
1759 return r;
1760
4623e8e6
LP
1761 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1762 if (r < 0)
1763 return r;
18b5886e 1764
319a4f4b 1765 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
18b5886e
LP
1766 return -ENOMEM;
1767
0d12936d 1768 r = sym_crypt_init(&cd, m->node);
18b5886e 1769 if (r < 0)
715cbb81 1770 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 1771
efc3b12f 1772 cryptsetup_enable_logging(cd);
1887032f 1773
0d12936d 1774 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
1775 if (r < 0)
1776 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e 1777
0d12936d 1778 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
ef9c184d 1779 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
0d12936d 1780 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 1781 if (r < 0) {
715cbb81 1782 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 1783 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 1784 }
18b5886e 1785
f7725647
YW
1786 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
1787 if (fd < 0)
1788 return log_debug_errno(errno, "Failed to open %s: %m", node);
1789
94344385
LP
1790 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1791 .name = TAKE_PTR(name),
1792 .device = TAKE_PTR(cd),
1793 };
18b5886e 1794
1cc6c93a 1795 m->decrypted_node = TAKE_PTR(node);
f7725647 1796 close_and_replace(m->mount_node_fd, fd);
18b5886e
LP
1797
1798 return 0;
4623e8e6
LP
1799}
1800
89e62e0b
LP
1801static int verity_can_reuse(
1802 const VeritySettings *verity,
1803 const char *name,
1804 struct crypt_device **ret_cd) {
1805
ac1f3ad0
LB
1806 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1807 _cleanup_free_ char *root_hash_existing = NULL;
0d12936d 1808 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1809 struct crypt_params_verity crypt_params = {};
89e62e0b 1810 size_t root_hash_existing_size;
ac1f3ad0
LB
1811 int r;
1812
89e62e0b
LP
1813 assert(verity);
1814 assert(name);
ac1f3ad0
LB
1815 assert(ret_cd);
1816
0d12936d 1817 r = sym_crypt_init_by_name(&cd, name);
ac1f3ad0
LB
1818 if (r < 0)
1819 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
0d12936d 1820
c719805e
LP
1821 cryptsetup_enable_logging(cd);
1822
0d12936d 1823 r = sym_crypt_get_verity_info(cd, &crypt_params);
ac1f3ad0
LB
1824 if (r < 0)
1825 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
0d12936d 1826
89e62e0b
LP
1827 root_hash_existing_size = verity->root_hash_size;
1828 root_hash_existing = malloc0(root_hash_existing_size);
ac1f3ad0
LB
1829 if (!root_hash_existing)
1830 return -ENOMEM;
0d12936d
LP
1831
1832 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
ac1f3ad0
LB
1833 if (r < 0)
1834 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
89e62e0b
LP
1835 if (verity->root_hash_size != root_hash_existing_size ||
1836 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
ac1f3ad0 1837 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
89e62e0b 1838
ac1f3ad0 1839#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
1840 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1841 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
28423d9a 1842 * signing for the new one, and vice versa. */
89e62e0b 1843 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
ac1f3ad0
LB
1844 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1845#endif
1846
1847 *ret_cd = TAKE_PTR(cd);
1848 return 0;
1849}
1850
75db809a 1851static inline char* dm_deferred_remove_clean(char *name) {
ac1f3ad0 1852 if (!name)
75db809a 1853 return NULL;
0d12936d
LP
1854
1855 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
75db809a 1856 return mfree(name);
ac1f3ad0
LB
1857}
1858DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1859
c2fa92e7
LP
1860static int validate_signature_userspace(const VeritySettings *verity) {
1861#if HAVE_OPENSSL
1862 _cleanup_(sk_X509_free_allp) STACK_OF(X509) *sk = NULL;
1863 _cleanup_strv_free_ char **certs = NULL;
1864 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
1865 _cleanup_free_ char *s = NULL;
1866 _cleanup_(BIO_freep) BIO *bio = NULL; /* 'bio' must be freed first, 's' second, hence keep this order
1867 * of declaration in place, please */
1868 const unsigned char *d;
c2fa92e7
LP
1869 int r;
1870
1871 assert(verity);
1872 assert(verity->root_hash);
1873 assert(verity->root_hash_sig);
1874
1875 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
1876 * userspace validation. */
1877
1878 r = conf_files_list_nulstr(&certs, ".crt", NULL, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, CONF_PATHS_NULSTR("verity.d"));
1879 if (r < 0)
1880 return log_debug_errno(r, "Failed to enumerate certificates: %m");
1881 if (strv_isempty(certs)) {
1882 log_debug("No userspace dm-verity certificates found.");
1883 return 0;
1884 }
1885
1886 d = verity->root_hash_sig;
1887 p7 = d2i_PKCS7(NULL, &d, (long) verity->root_hash_sig_size);
1888 if (!p7)
1889 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PKCS7 DER signature data.");
1890
1891 s = hexmem(verity->root_hash, verity->root_hash_size);
1892 if (!s)
1893 return log_oom_debug();
1894
1895 bio = BIO_new_mem_buf(s, strlen(s));
1896 if (!bio)
1897 return log_oom_debug();
1898
1899 sk = sk_X509_new_null();
1900 if (!sk)
1901 return log_oom_debug();
1902
1903 STRV_FOREACH(i, certs) {
1904 _cleanup_(X509_freep) X509 *c = NULL;
1905 _cleanup_fclose_ FILE *f = NULL;
1906
1907 f = fopen(*i, "re");
1908 if (!f) {
1909 log_debug_errno(errno, "Failed to open '%s', ignoring: %m", *i);
1910 continue;
1911 }
1912
1913 c = PEM_read_X509(f, NULL, NULL, NULL);
1914 if (!c) {
1915 log_debug("Failed to load X509 certificate '%s', ignoring.", *i);
1916 continue;
1917 }
1918
1919 if (sk_X509_push(sk, c) == 0)
1920 return log_oom_debug();
1921
1922 TAKE_PTR(c);
1923 }
1924
1925 r = PKCS7_verify(p7, sk, NULL, bio, NULL, PKCS7_NOINTERN|PKCS7_NOVERIFY);
1926 if (r)
1927 log_debug("Userspace PKCS#7 validation succeeded.");
1928 else
1929 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL));
1930
1931 return r;
1932#else
1933 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
1934 return 0;
1935#endif
1936}
1937
1938static int do_crypt_activate_verity(
1939 struct crypt_device *cd,
1940 const char *name,
1941 const VeritySettings *verity) {
1942
1943 bool check_signature;
1944 int r;
1945
1946 assert(cd);
1947 assert(name);
1948 assert(verity);
1949
1950 if (verity->root_hash_sig) {
1951 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIGNATURE");
1952 if (r < 0 && r != -ENXIO)
1953 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
1954
1955 check_signature = r != 0;
1956 } else
1957 check_signature = false;
1958
1959 if (check_signature) {
1960
1961#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1962 /* First, if we have support for signed keys in the kernel, then try that first. */
1963 r = sym_crypt_activate_by_signed_key(
1964 cd,
1965 name,
1966 verity->root_hash,
1967 verity->root_hash_size,
1968 verity->root_hash_sig,
1969 verity->root_hash_sig_size,
1970 CRYPT_ACTIVATE_READONLY);
1971 if (r >= 0)
1972 return r;
1973
1974 log_debug("Validation of dm-verity signature failed via the kernel, trying userspace validation instead.");
1975#else
1976 log_debug("Activation of verity device with signature requested, but not supported via the kernel by %s due to missing crypt_activate_by_signed_key(), trying userspace validation instead.",
1977 program_invocation_short_name);
1978#endif
1979
1980 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
1981 * works we'll try to activate without telling the kernel the signature. */
1982
1983 r = validate_signature_userspace(verity);
1984 if (r < 0)
1985 return r;
1986 if (r == 0)
1987 return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY),
1988 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
1989 }
1990
1991 return sym_crypt_activate_by_volume_key(
1992 cd,
1993 name,
1994 verity->root_hash,
1995 verity->root_hash_size,
1996 CRYPT_ACTIVATE_READONLY);
1997}
1998
ad361a50
YW
1999static usec_t verity_timeout(void) {
2000 usec_t t = 100 * USEC_PER_MSEC;
2001 const char *e;
2002 int r;
2003
2004 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2005 * Let's make the timeout configurable. */
2006
2007 e = getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2008 if (!e)
2009 return t;
2010
2011 r = parse_sec(e, &t);
2012 if (r < 0)
2013 log_debug_errno(r,
2014 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2015 "using the default timeout (%s).",
2016 FORMAT_TIMESPAN(t, USEC_PER_MSEC));
2017
2018 return t;
2019}
2020
4623e8e6 2021static int verity_partition(
aee36b4e 2022 PartitionDesignator designator,
4623e8e6
LP
2023 DissectedPartition *m,
2024 DissectedPartition *v,
89e62e0b 2025 const VeritySettings *verity,
4623e8e6
LP
2026 DissectImageFlags flags,
2027 DecryptedImage *d) {
2028
0d12936d 2029 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 2030 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
89e62e0b 2031 _cleanup_free_ char *node = NULL, *name = NULL;
f7725647 2032 _cleanup_close_ int mount_node_fd = -1;
4623e8e6
LP
2033 int r;
2034
2035 assert(m);
89e62e0b 2036 assert(v || (verity && verity->data_path));
4623e8e6 2037
89e62e0b 2038 if (!verity || !verity->root_hash)
4623e8e6 2039 return 0;
aee36b4e
LP
2040 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2041 (verity->designator == designator)))
2042 return 0;
4623e8e6
LP
2043
2044 if (!m->found || !m->node || !m->fstype)
2045 return 0;
89e62e0b 2046 if (!verity->data_path) {
e7cbe5cb
LB
2047 if (!v->found || !v->node || !v->fstype)
2048 return 0;
4623e8e6 2049
e7cbe5cb
LB
2050 if (!streq(v->fstype, "DM_verity_hash"))
2051 return 0;
2052 }
4623e8e6 2053
0d12936d
LP
2054 r = dlopen_cryptsetup();
2055 if (r < 0)
2056 return r;
2057
ac1f3ad0
LB
2058 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2059 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2060 _cleanup_free_ char *root_hash_encoded = NULL;
0d12936d 2061
89e62e0b 2062 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
ac1f3ad0
LB
2063 if (!root_hash_encoded)
2064 return -ENOMEM;
aee36b4e 2065
ac1f3ad0
LB
2066 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2067 } else
2068 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
4623e8e6
LP
2069 if (r < 0)
2070 return r;
2071
89e62e0b 2072 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
4623e8e6
LP
2073 if (r < 0)
2074 return r;
2075
efc3b12f 2076 cryptsetup_enable_logging(cd);
1887032f 2077
0d12936d 2078 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
4623e8e6 2079 if (r < 0)
294bd454 2080 return r;
4623e8e6 2081
0d12936d 2082 r = sym_crypt_set_data_device(cd, m->node);
4623e8e6 2083 if (r < 0)
294bd454 2084 return r;
4623e8e6 2085
319a4f4b 2086 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
ac1f3ad0
LB
2087 return -ENOMEM;
2088
2089 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2090 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2091 * retry a few times before giving up. */
2092 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
1d369d78 2093 _cleanup_(sym_crypt_freep) struct crypt_device *existing_cd = NULL;
f80015ff 2094 _cleanup_close_ int fd = -1;
c2fa92e7 2095
f80015ff
YW
2096 /* First, check if the device already exists. */
2097 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2098 if (fd < 0 && !ERRNO_IS_DEVICE_ABSENT(errno))
2099 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2100 if (fd >= 0)
2101 goto check; /* The device already exists. Let's check it. */
2102
2103 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
c2fa92e7 2104 r = do_crypt_activate_verity(cd, name, verity);
1d369d78 2105 if (r >= 0)
f7725647 2106 goto try_open; /* The device is activated. Let's open it. */
ac1f3ad0
LB
2107 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2108 * There's no way to distinguish this situation from a genuine error due to invalid
2aed63f4 2109 * parameters, so immediately fall back to activating the device with a unique name.
89e62e0b
LP
2110 * Improvements in libcrypsetup can ensure this never happens:
2111 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
ac1f3ad0 2112 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
0f75b0c5 2113 break;
1d369d78
YW
2114 if (r == -ENODEV) /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */
2115 goto try_again;
2116 if (!IN_SET(r,
2117 -EEXIST, /* Volume has already been opened and ready to be used. */
2118 -EBUSY /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2119 return log_debug_errno(r, "Failed to activate verity device %s: %m", node);
2120
f80015ff 2121 check:
1d369d78
YW
2122 if (!restore_deferred_remove){
2123 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2124 r = dm_deferred_remove_cancel(name);
12f5fbdf
YW
2125 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2126 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2127 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2128 if (IN_SET(r, -EBUSY, -ENXIO))
2129 goto try_again;
2130 if (r < 0)
1d369d78 2131 return log_debug_errno(r, "Failed to disable automated deferred removal for verity device %s: %m", node);
12f5fbdf
YW
2132
2133 restore_deferred_remove = strdup(name);
2134 if (!restore_deferred_remove)
2135 return log_oom_debug();
1d369d78 2136 }
c2923fdc 2137
1d369d78
YW
2138 r = verity_can_reuse(verity, name, &existing_cd);
2139 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2140 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2141 break;
2142 if (IN_SET(r,
2143 -ENOENT, /* Removed?? */
2144 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2145 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2146 goto try_again;
2147 if (r < 0)
2148 return log_debug_errno(r, "Failed to check if existing verity device %s can be reused: %m", node);
2149
f80015ff 2150 if (fd < 0) {
1d369d78
YW
2151 /* devmapper might say that the device exists, but the devlink might not yet have been
2152 * created. Check and wait for the udev event in that case. */
2153 r = device_wait_for_devlink(node, "block", verity_timeout(), NULL);
2154 /* Fallback to activation with a unique device if it's taking too long */
2155 if (r == -ETIMEDOUT && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
0f75b0c5 2156 break;
1d369d78
YW
2157 if (r < 0)
2158 return log_debug_errno(r, "Failed to wait device node symlink %s: %m", node);
c2923fdc 2159 }
ecab4c47 2160
f7725647
YW
2161 try_open:
2162 if (fd < 0) {
2163 /* Now, the device is activated and devlink is created. Let's open it. */
2164 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2165 if (fd < 0) {
2166 if (!ERRNO_IS_DEVICE_ABSENT(errno))
2167 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2168
2169 /* The device has already been removed?? */
2170 goto try_again;
2171 }
2172 }
2173
2174 mount_node_fd = TAKE_FD(fd);
1d369d78
YW
2175 if (existing_cd)
2176 crypt_free_and_replace(cd, existing_cd);
2177
2178 goto success;
2179
2180 try_again:
2181 /* Device is being removed by another process. Let's wait for a while. */
ecab4c47 2182 (void) usleep(2 * USEC_PER_MSEC);
ac1f3ad0
LB
2183 }
2184
0f75b0c5
YW
2185 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2186 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2187 /* Before trying to activate with unique name, we need to free crypt_device object.
2188 * Otherwise, we get error from libcryptsetup like the following:
2189 * ------
2190 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2191 * ------
2192 */
2193 sym_crypt_free(cd);
2194 cd = NULL;
aee36b4e 2195 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
0f75b0c5 2196 }
ac1f3ad0 2197
9972e6d6
YW
2198 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All attempts to activate verity device %s failed.", name);
2199
2200success:
ac1f3ad0
LB
2201 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2202 restore_deferred_remove = mfree(restore_deferred_remove);
4623e8e6 2203
94344385
LP
2204 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2205 .name = TAKE_PTR(name),
2206 .device = TAKE_PTR(cd),
2207 };
4623e8e6 2208
1cc6c93a 2209 m->decrypted_node = TAKE_PTR(node);
f7725647 2210 close_and_replace(m->mount_node_fd, mount_node_fd);
4623e8e6
LP
2211
2212 return 0;
18b5886e
LP
2213}
2214#endif
2215
2216int dissected_image_decrypt(
2217 DissectedImage *m,
2218 const char *passphrase,
89e62e0b 2219 const VeritySettings *verity,
e330f97a 2220 DissectImageFlags flags) {
18b5886e 2221
349cc4a5 2222#if HAVE_LIBCRYPTSETUP
49b5b3b4 2223 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
2224 int r;
2225#endif
2226
2227 assert(m);
89e62e0b 2228 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
18b5886e
LP
2229
2230 /* Returns:
2231 *
2232 * = 0 → There was nothing to decrypt
2233 * > 0 → Decrypted successfully
d1c536f5 2234 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
2235 * -EKEYREJECTED → Passed key was not correct
2236 */
2237
89e62e0b 2238 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
2239 return -EINVAL;
2240
e330f97a 2241 if (!m->encrypted && !m->verity_ready)
18b5886e 2242 return 0;
18b5886e 2243
349cc4a5 2244#if HAVE_LIBCRYPTSETUP
9321ad51
YW
2245 r = decrypted_image_new(&d);
2246 if (r < 0)
2247 return r;
18b5886e 2248
569a0e42 2249 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 2250 DissectedPartition *p = m->partitions + i;
22043172 2251 PartitionDesignator k;
18b5886e
LP
2252
2253 if (!p->found)
2254 continue;
2255
2256 r = decrypt_partition(p, passphrase, flags, d);
2257 if (r < 0)
2258 return r;
2259
dd894023 2260 k = partition_verity_of(i);
4623e8e6 2261 if (k >= 0) {
aee36b4e 2262 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
4623e8e6
LP
2263 if (r < 0)
2264 return r;
2265 }
2266
d2c6e79d 2267 if (!p->decrypted_fstype && p->mount_node_fd >= 0 && p->decrypted_node) {
c80c9079 2268 r = probe_filesystem_full(p->mount_node_fd, p->decrypted_node, 0, UINT64_MAX, &p->decrypted_fstype);
7cc84b2c 2269 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
2270 return r;
2271 }
2272 }
2273
ac1e1b5f 2274 m->decrypted_image = TAKE_PTR(d);
18b5886e
LP
2275
2276 return 1;
2277#else
2278 return -EOPNOTSUPP;
2279#endif
2280}
2281
2282int dissected_image_decrypt_interactively(
2283 DissectedImage *m,
2284 const char *passphrase,
89e62e0b 2285 const VeritySettings *verity,
e330f97a 2286 DissectImageFlags flags) {
18b5886e
LP
2287
2288 _cleanup_strv_free_erase_ char **z = NULL;
2289 int n = 3, r;
2290
2291 if (passphrase)
2292 n--;
2293
2294 for (;;) {
e330f97a 2295 r = dissected_image_decrypt(m, passphrase, verity, flags);
18b5886e
LP
2296 if (r >= 0)
2297 return r;
2298 if (r == -EKEYREJECTED)
2299 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
2300 else if (r != -ENOKEY)
2301 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 2302
baaa35ad
ZJS
2303 if (--n < 0)
2304 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
2305 "Too many retries.");
18b5886e
LP
2306
2307 z = strv_free(z);
2308
8806bb4b 2309 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY, 0, &z);
18b5886e
LP
2310 if (r < 0)
2311 return log_error_errno(r, "Failed to query for passphrase: %m");
2312
2313 passphrase = z[0];
2314 }
2315}
2316
e330f97a 2317static int decrypted_image_relinquish(DecryptedImage *d) {
18b5886e
LP
2318 assert(d);
2319
67f63ee5
ZJS
2320 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2321 * boolean so that we don't clean it up ourselves either anymore */
18b5886e 2322
349cc4a5 2323#if HAVE_LIBCRYPTSETUP
67f63ee5
ZJS
2324 int r;
2325
2326 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
2327 DecryptedPartition *p = d->decrypted + i;
2328
2329 if (p->relinquished)
2330 continue;
2331
0d12936d 2332 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
2333 if (r < 0)
2334 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
2335
2336 p->relinquished = true;
2337 }
2338#endif
2339
2340 return 0;
2341}
2342
f906075a
YW
2343int dissected_image_relinquish(DissectedImage *m) {
2344 int r;
2345
2346 assert(m);
2347
2348 if (m->decrypted_image) {
2349 r = decrypted_image_relinquish(m->decrypted_image);
2350 if (r < 0)
2351 return r;
2352 }
2353
2354 if (m->loop)
2355 loop_device_relinquish(m->loop);
2356
2357 return 0;
2358}
2359
89e62e0b
LP
2360static char *build_auxiliary_path(const char *image, const char *suffix) {
2361 const char *e;
2362 char *n;
2363
2364 assert(image);
2365 assert(suffix);
2366
2367 e = endswith(image, ".raw");
2368 if (!e)
2369 return strjoin(e, suffix);
2370
2371 n = new(char, e - image + strlen(suffix) + 1);
2372 if (!n)
2373 return NULL;
2374
2375 strcpy(mempcpy(n, image, e - image), suffix);
2376 return n;
2377}
2378
2379void verity_settings_done(VeritySettings *v) {
2380 assert(v);
2381
2382 v->root_hash = mfree(v->root_hash);
2383 v->root_hash_size = 0;
2384
2385 v->root_hash_sig = mfree(v->root_hash_sig);
2386 v->root_hash_sig_size = 0;
2387
2388 v->data_path = mfree(v->data_path);
2389}
2390
2391int verity_settings_load(
2392 VeritySettings *verity,
f5ea63a5
LP
2393 const char *image,
2394 const char *root_hash_path,
89e62e0b
LP
2395 const char *root_hash_sig_path) {
2396
2397 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2398 size_t root_hash_size = 0, root_hash_sig_size = 0;
2399 _cleanup_free_ char *verity_data_path = NULL;
aee36b4e 2400 PartitionDesignator designator;
78ebe980
LP
2401 int r;
2402
89e62e0b 2403 assert(verity);
78ebe980 2404 assert(image);
aee36b4e 2405 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
78ebe980 2406
89e62e0b
LP
2407 /* If we are asked to load the root hash for a device node, exit early */
2408 if (is_device_path(image))
78ebe980 2409 return 0;
78ebe980 2410
d5fcc5b0
LP
2411 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2412 if (r < 0 && r != -ENXIO)
2413 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2414 if (r == 0)
2415 return 0;
2416
aee36b4e
LP
2417 designator = verity->designator;
2418
89e62e0b 2419 /* We only fill in what isn't already filled in */
c2923fdc 2420
89e62e0b 2421 if (!verity->root_hash) {
e7cbe5cb 2422 _cleanup_free_ char *text = NULL;
e7cbe5cb 2423
0389f4fa 2424 if (root_hash_path) {
aee36b4e 2425 /* If explicitly specified it takes precedence */
0389f4fa
LB
2426 r = read_one_line_file(root_hash_path, &text);
2427 if (r < 0)
e7cbe5cb 2428 return r;
aee36b4e
LP
2429
2430 if (designator < 0)
2431 designator = PARTITION_ROOT;
0389f4fa 2432 } else {
aee36b4e
LP
2433 /* Otherwise look for xattr and separate file, and first for the data for root and if
2434 * that doesn't exist for /usr */
0389f4fa 2435
aee36b4e 2436 if (designator < 0 || designator == PARTITION_ROOT) {
c53e07e2 2437 r = getxattr_malloc(image, "user.verity.roothash", &text);
aee36b4e
LP
2438 if (r < 0) {
2439 _cleanup_free_ char *p = NULL;
78ebe980 2440
00675c36 2441 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
aee36b4e 2442 return r;
e7cbe5cb 2443
aee36b4e
LP
2444 p = build_auxiliary_path(image, ".roothash");
2445 if (!p)
2446 return -ENOMEM;
2447
2448 r = read_one_line_file(p, &text);
2449 if (r < 0 && r != -ENOENT)
2450 return r;
2451 }
2452
2453 if (text)
2454 designator = PARTITION_ROOT;
2455 }
2456
2457 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2458 /* So in the "roothash" xattr/file name above the "root" of course primarily
2459 * refers to the root of the Verity Merkle tree. But coincidentally it also
2460 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2461 * two distinct concepts called "root". Taking benefit of this happy
2462 * coincidence we call the file with the root hash for the /usr/ file system
2463 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2464 * confusing. We thus drop the reference to the root of the Merkle tree, and
2465 * just indicate which file system it's about. */
c53e07e2 2466 r = getxattr_malloc(image, "user.verity.usrhash", &text);
aee36b4e
LP
2467 if (r < 0) {
2468 _cleanup_free_ char *p = NULL;
2469
00675c36 2470 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
aee36b4e
LP
2471 return r;
2472
2473 p = build_auxiliary_path(image, ".usrhash");
2474 if (!p)
2475 return -ENOMEM;
2476
2477 r = read_one_line_file(p, &text);
2478 if (r < 0 && r != -ENOENT)
2479 return r;
2480 }
2481
2482 if (text)
2483 designator = PARTITION_USR;
0389f4fa 2484 }
e7cbe5cb
LB
2485 }
2486
2487 if (text) {
89e62e0b 2488 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
e7cbe5cb
LB
2489 if (r < 0)
2490 return r;
89e62e0b 2491 if (root_hash_size < sizeof(sd_id128_t))
e7cbe5cb
LB
2492 return -EINVAL;
2493 }
2494 }
2495
90f98986 2496 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
aee36b4e 2497 if (root_hash_sig_path) {
ae9cf30b 2498 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2499 if (r < 0 && r != -ENOENT)
2500 return r;
2501
2502 if (designator < 0)
2503 designator = PARTITION_ROOT;
2504 } else {
2505 if (designator < 0 || designator == PARTITION_ROOT) {
2506 _cleanup_free_ char *p = NULL;
2507
2508 /* Follow naming convention recommended by the relevant RFC:
2509 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2510 p = build_auxiliary_path(image, ".roothash.p7s");
2511 if (!p)
2512 return -ENOMEM;
89e62e0b 2513
ae9cf30b 2514 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2515 if (r < 0 && r != -ENOENT)
2516 return r;
2517 if (r >= 0)
2518 designator = PARTITION_ROOT;
2519 }
2520
2521 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2522 _cleanup_free_ char *p = NULL;
2523
2524 p = build_auxiliary_path(image, ".usrhash.p7s");
2525 if (!p)
2526 return -ENOMEM;
89e62e0b 2527
ae9cf30b 2528 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2529 if (r < 0 && r != -ENOENT)
2530 return r;
2531 if (r >= 0)
2532 designator = PARTITION_USR;
2533 }
89e62e0b
LP
2534 }
2535
aee36b4e 2536 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
89e62e0b
LP
2537 return -EINVAL;
2538 }
2539
2540 if (!verity->data_path) {
2541 _cleanup_free_ char *p = NULL;
2542
2543 p = build_auxiliary_path(image, ".verity");
2544 if (!p)
2545 return -ENOMEM;
2546
2547 if (access(p, F_OK) < 0) {
2548 if (errno != ENOENT)
2549 return -errno;
2550 } else
2551 verity_data_path = TAKE_PTR(p);
2552 }
2553
2554 if (root_hash) {
2555 verity->root_hash = TAKE_PTR(root_hash);
2556 verity->root_hash_size = root_hash_size;
2557 }
2558
2559 if (root_hash_sig) {
2560 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2561 verity->root_hash_sig_size = root_hash_sig_size;
e7cbe5cb 2562 }
89e62e0b
LP
2563
2564 if (verity_data_path)
2565 verity->data_path = TAKE_PTR(verity_data_path);
78ebe980 2566
aee36b4e
LP
2567 if (verity->designator < 0)
2568 verity->designator = designator;
2569
78ebe980
LP
2570 return 1;
2571}
2572
88b3300f
LP
2573int dissected_image_load_verity_sig_partition(
2574 DissectedImage *m,
2575 int fd,
2576 VeritySettings *verity) {
2577
2578 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2579 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
2580 size_t root_hash_size, root_hash_sig_size;
2581 _cleanup_free_ char *buf = NULL;
2582 PartitionDesignator d;
2583 DissectedPartition *p;
2584 JsonVariant *rh, *sig;
2585 ssize_t n;
2586 char *e;
2587 int r;
2588
2589 assert(m);
2590 assert(fd >= 0);
2591 assert(verity);
2592
2593 if (verity->root_hash && verity->root_hash_sig) /* Already loaded? */
2594 return 0;
2595
2596 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
2597 if (r < 0 && r != -ENXIO)
2598 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
2599 if (r == 0)
2600 return 0;
2601
dd894023 2602 d = partition_verity_sig_of(verity->designator < 0 ? PARTITION_ROOT : verity->designator);
88b3300f
LP
2603 assert(d >= 0);
2604
2605 p = m->partitions + d;
2606 if (!p->found)
2607 return 0;
2608 if (p->offset == UINT64_MAX || p->size == UINT64_MAX)
2609 return -EINVAL;
2610
2611 if (p->size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
2612 return -EFBIG;
2613
2614 buf = new(char, p->size+1);
2615 if (!buf)
2616 return -ENOMEM;
2617
2618 n = pread(fd, buf, p->size, p->offset);
2619 if (n < 0)
2620 return -ENOMEM;
2621 if ((uint64_t) n != p->size)
2622 return -EIO;
2623
2624 e = memchr(buf, 0, p->size);
2625 if (e) {
2626 /* If we found a NUL byte then the rest of the data must be NUL too */
2627 if (!memeqzero(e, p->size - (e - buf)))
2628 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
2629 } else
2630 buf[p->size] = 0;
2631
2632 r = json_parse(buf, 0, &v, NULL, NULL);
2633 if (r < 0)
2634 return log_debug_errno(r, "Failed to parse signature JSON data: %m");
2635
2636 rh = json_variant_by_key(v, "rootHash");
2637 if (!rh)
2638 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
2639 if (!json_variant_is_string(rh))
2640 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'rootHash' field of signature JSON object is not a string.");
2641
2642 r = unhexmem(json_variant_string(rh), SIZE_MAX, &root_hash, &root_hash_size);
2643 if (r < 0)
2644 return log_debug_errno(r, "Failed to parse root hash field: %m");
2645
2646 /* Check if specified root hash matches if it is specified */
2647 if (verity->root_hash &&
2648 memcmp_nn(verity->root_hash, verity->root_hash_size, root_hash, root_hash_size) != 0) {
2649 _cleanup_free_ char *a = NULL, *b = NULL;
2650
2651 a = hexmem(root_hash, root_hash_size);
2652 b = hexmem(verity->root_hash, verity->root_hash_size);
2653
2654 return log_debug_errno(r, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a), strna(b));
2655 }
2656
2657 sig = json_variant_by_key(v, "signature");
2658 if (!sig)
2659 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
2660 if (!json_variant_is_string(sig))
2661 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'signature' field of signature JSON object is not a string.");
2662
2663 r = unbase64mem(json_variant_string(sig), SIZE_MAX, &root_hash_sig, &root_hash_sig_size);
2664 if (r < 0)
2665 return log_debug_errno(r, "Failed to parse signature field: %m");
2666
2667 free_and_replace(verity->root_hash, root_hash);
2668 verity->root_hash_size = root_hash_size;
2669
2670 free_and_replace(verity->root_hash_sig, root_hash_sig);
2671 verity->root_hash_sig_size = root_hash_sig_size;
2672
2673 return 1;
2674}
2675
22847508 2676int dissected_image_acquire_metadata(DissectedImage *m, DissectImageFlags extra_flags) {
3b925504
LP
2677
2678 enum {
2679 META_HOSTNAME,
2680 META_MACHINE_ID,
2681 META_MACHINE_INFO,
2682 META_OS_RELEASE,
fab22946 2683 META_INITRD_RELEASE,
7718ac97 2684 META_EXTENSION_RELEASE,
a4e0d617 2685 META_HAS_INIT_SYSTEM,
3b925504
LP
2686 _META_MAX,
2687 };
2688
9a4b883b 2689 static const char *const paths[_META_MAX] = {
7718ac97
LB
2690 [META_HOSTNAME] = "/etc/hostname\0",
2691 [META_MACHINE_ID] = "/etc/machine-id\0",
2692 [META_MACHINE_INFO] = "/etc/machine-info\0",
9a4b883b 2693 [META_OS_RELEASE] = ("/etc/os-release\0"
22847508 2694 "/usr/lib/os-release\0"),
fab22946
LP
2695 [META_INITRD_RELEASE] = ("/etc/initrd-release\0"
2696 "/usr/lib/initrd-release\0"),
a4e0d617
LP
2697 [META_EXTENSION_RELEASE] = "extension-release\0", /* Used only for logging. */
2698 [META_HAS_INIT_SYSTEM] = "has-init-system\0", /* ditto */
3b925504
LP
2699 };
2700
fab22946 2701 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **initrd_release = NULL, **extension_release = NULL;
af8219d5 2702 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
3b925504
LP
2703 _cleanup_(rmdir_and_freep) char *t = NULL;
2704 _cleanup_(sigkill_waitp) pid_t child = 0;
2705 sd_id128_t machine_id = SD_ID128_NULL;
2706 _cleanup_free_ char *hostname = NULL;
67f63ee5 2707 unsigned n_meta_initialized = 0;
af8219d5 2708 int fds[2 * _META_MAX], r, v;
a4e0d617 2709 int has_init_system = -1;
af8219d5 2710 ssize_t n;
3b925504
LP
2711
2712 BLOCK_SIGNALS(SIGCHLD);
2713
2714 assert(m);
2715
7718ac97 2716 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++) {
d9119c00
LP
2717 if (!paths[n_meta_initialized]) {
2718 fds[2*n_meta_initialized] = fds[2*n_meta_initialized+1] = -1;
7718ac97 2719 continue;
d9119c00
LP
2720 }
2721
3b925504
LP
2722 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2723 r = -errno;
2724 goto finish;
2725 }
7718ac97 2726 }
3b925504
LP
2727
2728 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2729 if (r < 0)
2730 goto finish;
2731
af8219d5
LP
2732 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2733 r = -errno;
2734 goto finish;
2735 }
2736
e2047ba9 2737 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 2738 if (r < 0)
3b925504 2739 goto finish;
be39f6ee 2740 if (r == 0) {
a4e0d617 2741 /* Child in a new mount namespace */
af8219d5
LP
2742 error_pipe[0] = safe_close(error_pipe[0]);
2743
7cf66030
LP
2744 r = dissected_image_mount(
2745 m,
2746 t,
2747 UID_INVALID,
21b61b1d 2748 UID_INVALID,
22847508
ZJS
2749 extra_flags |
2750 DISSECT_IMAGE_READ_ONLY |
2751 DISSECT_IMAGE_MOUNT_ROOT_ONLY |
7cf66030 2752 DISSECT_IMAGE_USR_NO_ROOT);
429d4e41
LP
2753 if (r < 0) {
2754 log_debug_errno(r, "Failed to mount dissected image: %m");
03ae68f4 2755 goto inner_fail;
429d4e41 2756 }
3b925504 2757
67f63ee5 2758 for (unsigned k = 0; k < _META_MAX; k++) {
37e44c3f 2759 _cleanup_close_ int fd = -ENOENT;
3b925504 2760
7718ac97
LB
2761 if (!paths[k])
2762 continue;
2763
3b925504
LP
2764 fds[2*k] = safe_close(fds[2*k]);
2765
a4e0d617
LP
2766 switch (k) {
2767
2768 case META_EXTENSION_RELEASE:
9a4b883b
LB
2769 /* As per the os-release spec, if the image is an extension it will have a file
2770 * named after the image name in extension-release.d/ - we use the image name
2771 * and try to resolve it with the extension-release helpers, as sometimes
2772 * the image names are mangled on deployment and do not match anymore.
2773 * Unlike other paths this is not fixed, and the image name
2774 * can be mangled on deployment, so by calling into the helper
2775 * we allow a fallback that matches on the first extension-release
2776 * file found in the directory, if one named after the image cannot
2777 * be found first. */
06768b90 2778 r = open_extension_release(t, m->image_name, /* relax_extension_release_check= */ false, NULL, &fd);
9a4b883b
LB
2779 if (r < 0)
2780 fd = r; /* Propagate the error. */
a4e0d617
LP
2781 break;
2782
2783 case META_HAS_INIT_SYSTEM: {
2784 bool found = false;
a4e0d617
LP
2785
2786 FOREACH_STRING(init,
2787 "/usr/lib/systemd/systemd", /* systemd on /usr merged system */
2788 "/lib/systemd/systemd", /* systemd on /usr non-merged systems */
2789 "/sbin/init") { /* traditional path the Linux kernel invokes */
2790
2791 r = chase_symlinks(init, t, CHASE_PREFIX_ROOT, NULL, NULL);
2792 if (r < 0) {
2793 if (r != -ENOENT)
2794 log_debug_errno(r, "Failed to resolve %s, ignoring: %m", init);
2795 } else {
2796 found = true;
2797 break;
2798 }
2799 }
2800
2801 r = loop_write(fds[2*k+1], &found, sizeof(found), false);
2802 if (r < 0)
2803 goto inner_fail;
2804
2805 continue;
2806 }
2807
2808 default:
9a4b883b
LB
2809 NULSTR_FOREACH(p, paths[k]) {
2810 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
2811 if (fd >= 0)
2812 break;
2813 }
a4e0d617
LP
2814 }
2815
36952d19
LP
2816 if (fd < 0) {
2817 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
37e44c3f 2818 fds[2*k+1] = safe_close(fds[2*k+1]);
3b925504 2819 continue;
36952d19 2820 }
3b925504 2821
f5fbe71d 2822 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
a4e0d617
LP
2823 if (r < 0)
2824 goto inner_fail;
3b925504
LP
2825
2826 fds[2*k+1] = safe_close(fds[2*k+1]);
2827 }
2828
2829 _exit(EXIT_SUCCESS);
a4e0d617
LP
2830
2831 inner_fail:
03ae68f4 2832 /* Let parent know the error */
a4e0d617
LP
2833 (void) write(error_pipe[1], &r, sizeof(r));
2834 _exit(EXIT_FAILURE);
3b925504
LP
2835 }
2836
af8219d5
LP
2837 error_pipe[1] = safe_close(error_pipe[1]);
2838
67f63ee5 2839 for (unsigned k = 0; k < _META_MAX; k++) {
3b925504
LP
2840 _cleanup_fclose_ FILE *f = NULL;
2841
7718ac97
LB
2842 if (!paths[k])
2843 continue;
2844
3b925504
LP
2845 fds[2*k+1] = safe_close(fds[2*k+1]);
2846
4fa744a3 2847 f = take_fdopen(&fds[2*k], "r");
3b925504
LP
2848 if (!f) {
2849 r = -errno;
2850 goto finish;
2851 }
2852
3b925504
LP
2853 switch (k) {
2854
2855 case META_HOSTNAME:
2856 r = read_etc_hostname_stream(f, &hostname);
2857 if (r < 0)
f6048e5e 2858 log_debug_errno(r, "Failed to read /etc/hostname of image: %m");
3b925504
LP
2859
2860 break;
2861
2862 case META_MACHINE_ID: {
2863 _cleanup_free_ char *line = NULL;
2864
2865 r = read_line(f, LONG_LINE_MAX, &line);
2866 if (r < 0)
f6048e5e 2867 log_debug_errno(r, "Failed to read /etc/machine-id of image: %m");
3b925504
LP
2868 else if (r == 33) {
2869 r = sd_id128_from_string(line, &machine_id);
2870 if (r < 0)
2871 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
2872 } else if (r == 0)
f6048e5e 2873 log_debug("/etc/machine-id file of image is empty.");
ab763cb2 2874 else if (streq(line, "uninitialized"))
f6048e5e 2875 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3b925504 2876 else
f6048e5e 2877 log_debug("/etc/machine-id file of image has unexpected length %i.", r);
3b925504
LP
2878
2879 break;
2880 }
2881
2882 case META_MACHINE_INFO:
aa8fbc74 2883 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504 2884 if (r < 0)
f6048e5e 2885 log_debug_errno(r, "Failed to read /etc/machine-info of image: %m");
3b925504
LP
2886
2887 break;
2888
2889 case META_OS_RELEASE:
aa8fbc74 2890 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504 2891 if (r < 0)
f6048e5e 2892 log_debug_errno(r, "Failed to read OS release file of image: %m");
3b925504
LP
2893
2894 break;
7718ac97 2895
fab22946
LP
2896 case META_INITRD_RELEASE:
2897 r = load_env_file_pairs(f, "initrd-release", &initrd_release);
2898 if (r < 0)
2899 log_debug_errno(r, "Failed to read initrd release file of image: %m");
2900
2901 break;
2902
7718ac97
LB
2903 case META_EXTENSION_RELEASE:
2904 r = load_env_file_pairs(f, "extension-release", &extension_release);
2905 if (r < 0)
f6048e5e 2906 log_debug_errno(r, "Failed to read extension release file of image: %m");
7718ac97
LB
2907
2908 break;
a4e0d617
LP
2909
2910 case META_HAS_INIT_SYSTEM: {
2911 bool b = false;
2912 size_t nr;
2913
2914 errno = 0;
2915 nr = fread(&b, 1, sizeof(b), f);
2916 if (nr != sizeof(b))
2917 log_debug_errno(errno_or_else(EIO), "Failed to read has-init-system boolean: %m");
2918 else
2919 has_init_system = b;
2920
2921 break;
2922 }}
3b925504
LP
2923 }
2924
2e87a1fd 2925 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 2926 child = 0;
2e87a1fd 2927 if (r < 0)
af8219d5
LP
2928 return r;
2929
2930 n = read(error_pipe[0], &v, sizeof(v));
2931 if (n < 0)
2932 return -errno;
2933 if (n == sizeof(v))
2934 return v; /* propagate error sent to us from child */
2935 if (n != 0)
2936 return -EIO;
2937
2e87a1fd
LP
2938 if (r != EXIT_SUCCESS)
2939 return -EPROTO;
3b925504
LP
2940
2941 free_and_replace(m->hostname, hostname);
2942 m->machine_id = machine_id;
2943 strv_free_and_replace(m->machine_info, machine_info);
2944 strv_free_and_replace(m->os_release, os_release);
fab22946 2945 strv_free_and_replace(m->initrd_release, initrd_release);
7718ac97 2946 strv_free_and_replace(m->extension_release, extension_release);
a4e0d617 2947 m->has_init_system = has_init_system;
3b925504
LP
2948
2949finish:
67f63ee5 2950 for (unsigned k = 0; k < n_meta_initialized; k++)
3b925504
LP
2951 safe_close_pair(fds + 2*k);
2952
2953 return r;
2954}
2955
1e63dc4f
YW
2956int dissect_loop_device(
2957 LoopDevice *loop,
2958 const VeritySettings *verity,
2959 const MountOptions *mount_options,
2960 DissectImageFlags flags,
2961 DissectedImage **ret) {
2962
08f14be4 2963#if HAVE_BLKID
1e63dc4f
YW
2964 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
2965 int r;
2966
2967 assert(loop);
2968 assert(ret);
2969
08f14be4 2970 r = dissected_image_new(loop->backing_file ?: loop->node, &m);
1e63dc4f
YW
2971 if (r < 0)
2972 return r;
2973
2974 m->loop = loop_device_ref(loop);
2975
73d88b80 2976 r = dissect_image(m, loop->fd, loop->node, verity, mount_options, flags);
08f14be4 2977 if (r < 0)
08f14be4
YW
2978 return r;
2979
1e63dc4f
YW
2980 *ret = TAKE_PTR(m);
2981 return 0;
08f14be4
YW
2982#else
2983 return -EOPNOTSUPP;
2984#endif
1e63dc4f
YW
2985}
2986
bad31660 2987int dissect_loop_device_and_warn(
1e63dc4f 2988 LoopDevice *loop,
89e62e0b 2989 const VeritySettings *verity,
18d73705 2990 const MountOptions *mount_options,
4526113f
LP
2991 DissectImageFlags flags,
2992 DissectedImage **ret) {
2993
64dd3a24 2994 const char *name;
4526113f
LP
2995 int r;
2996
bad31660
YW
2997 assert(loop);
2998 assert(loop->fd >= 0);
4526113f 2999
64dd3a24 3000 name = ASSERT_PTR(loop->backing_file ?: loop->node);
4526113f 3001
369de26f 3002 r = dissect_loop_device(loop, verity, mount_options, flags, ret);
4526113f
LP
3003 switch (r) {
3004
3005 case -EOPNOTSUPP:
3006 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
3007
3008 case -ENOPKG:
48084df6
ZJS
3009 return log_error_errno(r, "%s: Couldn't identify a suitable partition table or file system.", name);
3010
3011 case -ENOMEDIUM:
3012 return log_error_errno(r, "%s: The image does not pass validation.", name);
4526113f
LP
3013
3014 case -EADDRNOTAVAIL:
48084df6 3015 return log_error_errno(r, "%s: No root partition for specified root hash found.", name);
4526113f
LP
3016
3017 case -ENOTUNIQ:
48084df6 3018 return log_error_errno(r, "%s: Multiple suitable root partitions found in image.", name);
4526113f
LP
3019
3020 case -ENXIO:
48084df6 3021 return log_error_errno(r, "%s: No suitable root partition found in image.", name);
4526113f
LP
3022
3023 case -EPROTONOSUPPORT:
3024 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
3025
48084df6
ZJS
3026 case -ENOTBLK:
3027 return log_error_errno(r, "%s: Image is not a block device.", name);
3028
a94aa2b9
LP
3029 case -EBADR:
3030 return log_error_errno(r,
3031 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
3032 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
3033 name, strna(verity ? verity->data_path : NULL));
3034
4526113f
LP
3035 default:
3036 if (r < 0)
3037 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
3038
3039 return r;
3040 }
3041}
3042
49536766
LP
3043bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
3044 assert(image);
3045
3046 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3047 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3048 * images we only check the partition type.
3049 *
3050 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3051 * image. */
3052
e7cbe5cb 3053 if (image->single_file_system)
c3c88d67 3054 return partition_designator == PARTITION_ROOT && image->has_verity;
e7cbe5cb 3055
dd894023 3056 return partition_verity_of(partition_designator) >= 0;
e7cbe5cb
LB
3057}
3058
49536766
LP
3059bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3060 PartitionDesignator k;
3061
3062 assert(image);
3063
3064 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3065 * works for the root partition, for others only if the associated verity partition was found. */
3066
3067 if (!image->verity_ready)
3068 return false;
e7cbe5cb
LB
3069
3070 if (image->single_file_system)
49536766 3071 return partition_designator == PARTITION_ROOT;
e7cbe5cb 3072
dd894023 3073 k = partition_verity_of(partition_designator);
e7cbe5cb
LB
3074 return k >= 0 && image->partitions[k].found;
3075}
3076
8ee9615e
LP
3077bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3078 PartitionDesignator k;
3079
3080 assert(image);
3081
3082 /* Checks if this partition has verity signature data available that we can use. */
3083
3084 if (!image->verity_sig_ready)
3085 return false;
3086
3087 if (image->single_file_system)
3088 return partition_designator == PARTITION_ROOT;
3089
dd894023 3090 k = partition_verity_sig_of(partition_designator);
8ee9615e
LP
3091 return k >= 0 && image->partitions[k].found;
3092}
3093
18d73705
LB
3094MountOptions* mount_options_free_all(MountOptions *options) {
3095 MountOptions *m;
3096
3097 while ((m = options)) {
3098 LIST_REMOVE(mount_options, options, m);
3099 free(m->options);
3100 free(m);
3101 }
3102
3103 return NULL;
3104}
3105
569a0e42 3106const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
f5215bc8 3107 LIST_FOREACH(mount_options, m, options)
9ece6444 3108 if (designator == m->partition_designator && !isempty(m->options))
18d73705 3109 return m->options;
6aa05ebd 3110
18d73705
LB
3111 return NULL;
3112}
3113
6aa05ebd
LP
3114int mount_image_privately_interactively(
3115 const char *image,
3116 DissectImageFlags flags,
3117 char **ret_directory,
e330f97a 3118 LoopDevice **ret_loop_device) {
6aa05ebd 3119
27ec815e 3120 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
6aa05ebd 3121 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
6aa05ebd
LP
3122 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3123 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
3124 _cleanup_free_ char *temp = NULL;
3125 int r;
3126
3127 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3128 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3129 * easily. */
3130
3131 assert(image);
3132 assert(ret_directory);
3133 assert(ret_loop_device);
6aa05ebd 3134
73d88b80
LP
3135 /* We intend to mount this right-away, hence add the partitions if needed and pin them*/
3136 flags |= DISSECT_IMAGE_ADD_PARTITION_DEVICES |
3137 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
3138
27ec815e
LP
3139 r = verity_settings_load(&verity, image, NULL, NULL);
3140 if (r < 0)
3141 return log_error_errno(r, "Failed to load root hash data: %m");
3142
6aa05ebd
LP
3143 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
3144 if (r < 0)
3145 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
3146
3147 r = loop_device_make_by_path(
3148 image,
ef9c184d 3149 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
6aa05ebd 3150 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
7f52206a 3151 LOCK_SH,
6aa05ebd
LP
3152 &d);
3153 if (r < 0)
7b87fe4c 3154 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
6aa05ebd 3155
64dd3a24 3156 r = dissect_loop_device_and_warn(d, &verity, NULL, flags, &dissected_image);
6aa05ebd
LP
3157 if (r < 0)
3158 return r;
3159
88b3300f
LP
3160 r = dissected_image_load_verity_sig_partition(dissected_image, d->fd, &verity);
3161 if (r < 0)
3162 return r;
3163
e330f97a 3164 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags);
6aa05ebd
LP
3165 if (r < 0)
3166 return r;
3167
3168 r = detach_mount_namespace();
3169 if (r < 0)
3170 return log_error_errno(r, "Failed to detach mount namespace: %m");
3171
3172 r = mkdir_p(temp, 0700);
3173 if (r < 0)
3174 return log_error_errno(r, "Failed to create mount point: %m");
3175
3176 created_dir = TAKE_PTR(temp);
3177
21b61b1d 3178 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, UID_INVALID, flags);
6aa05ebd 3179 if (r < 0)
af187ab2 3180 return r;
6aa05ebd 3181
41bc4849
LP
3182 r = loop_device_flock(d, LOCK_UN);
3183 if (r < 0)
3184 return r;
3185
3044d343
YW
3186 r = dissected_image_relinquish(dissected_image);
3187 if (r < 0)
3188 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
6aa05ebd
LP
3189
3190 *ret_directory = TAKE_PTR(created_dir);
3191 *ret_loop_device = TAKE_PTR(d);
6aa05ebd
LP
3192
3193 return 0;
3194}
3195
06768b90
LB
3196static bool mount_options_relax_extension_release_checks(const MountOptions *options) {
3197 if (!options)
3198 return false;
3199
3200 return string_contains_word(mount_options_from_designator(options, PARTITION_ROOT), ",", "x-systemd.relax-extension-release-check") ||
3201 string_contains_word(mount_options_from_designator(options, PARTITION_USR), ",", "x-systemd.relax-extension-release-check") ||
3202 string_contains_word(options->options, ",", "x-systemd.relax-extension-release-check");
3203}
3204
93f59701 3205int verity_dissect_and_mount(
cedf5b1a 3206 int src_fd,
93f59701
LB
3207 const char *src,
3208 const char *dest,
3209 const MountOptions *options,
3210 const char *required_host_os_release_id,
3211 const char *required_host_os_release_version_id,
60c5f700
LP
3212 const char *required_host_os_release_sysext_level,
3213 const char *required_sysext_scope) {
93f59701 3214
4beda316 3215 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
4beda316
LB
3216 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3217 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3218 DissectImageFlags dissect_image_flags;
06768b90 3219 bool relax_extension_release_check;
4beda316
LB
3220 int r;
3221
3222 assert(src);
3223 assert(dest);
3224
06768b90
LB
3225 relax_extension_release_check = mount_options_relax_extension_release_checks(options);
3226
cedf5b1a 3227 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
4beda316
LB
3228 r = verity_settings_load(&verity, src, NULL, NULL);
3229 if (r < 0)
3230 return log_debug_errno(r, "Failed to load root hash: %m");
3231
06768b90 3232 dissect_image_flags = (verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0) |
73d88b80
LP
3233 (relax_extension_release_check ? DISSECT_IMAGE_RELAX_SYSEXT_CHECK : 0) |
3234 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
3235 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
4beda316 3236
cedf5b1a
LB
3237 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
3238 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4beda316 3239 r = loop_device_make_by_path(
cedf5b1a 3240 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
4beda316
LB
3241 -1,
3242 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
7f52206a 3243 LOCK_SH,
4beda316
LB
3244 &loop_device);
3245 if (r < 0)
3246 return log_debug_errno(r, "Failed to create loop device for image: %m");
3247
bad31660
YW
3248 r = dissect_loop_device(
3249 loop_device,
4beda316
LB
3250 &verity,
3251 options,
3252 dissect_image_flags,
3253 &dissected_image);
3254 /* No partition table? Might be a single-filesystem image, try again */
3255 if (!verity.data_path && r == -ENOPKG)
bad31660
YW
3256 r = dissect_loop_device(
3257 loop_device,
4beda316
LB
3258 &verity,
3259 options,
75dc190d 3260 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
4beda316
LB
3261 &dissected_image);
3262 if (r < 0)
3263 return log_debug_errno(r, "Failed to dissect image: %m");
3264
88b3300f
LP
3265 r = dissected_image_load_verity_sig_partition(dissected_image, loop_device->fd, &verity);
3266 if (r < 0)
3267 return r;
3268
4beda316
LB
3269 r = dissected_image_decrypt(
3270 dissected_image,
3271 NULL,
3272 &verity,
e330f97a 3273 dissect_image_flags);
4beda316
LB
3274 if (r < 0)
3275 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
3276
3277 r = mkdir_p_label(dest, 0755);
3278 if (r < 0)
3279 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
3280 r = umount_recursive(dest, 0);
3281 if (r < 0)
3282 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
3283
21b61b1d 3284 r = dissected_image_mount(dissected_image, dest, UID_INVALID, UID_INVALID, dissect_image_flags);
4beda316
LB
3285 if (r < 0)
3286 return log_debug_errno(r, "Failed to mount image: %m");
3287
41bc4849
LP
3288 r = loop_device_flock(loop_device, LOCK_UN);
3289 if (r < 0)
3290 return log_debug_errno(r, "Failed to unlock loopback device: %m");
3291
93f59701
LB
3292 /* If we got os-release values from the caller, then we need to match them with the image's
3293 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3294 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
37361f46
LB
3295 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
3296 * then a simple match on the ID will be performed. */
8b2dcbbd 3297 if (required_host_os_release_id) {
93f59701
LB
3298 _cleanup_strv_free_ char **extension_release = NULL;
3299
d30d86b7
YW
3300 assert(!isempty(required_host_os_release_id));
3301
06768b90 3302 r = load_extension_release_pairs(dest, dissected_image->image_name, relax_extension_release_check, &extension_release);
93f59701
LB
3303 if (r < 0)
3304 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
3305
3306 r = extension_release_validate(
60c5f700
LP
3307 dissected_image->image_name,
3308 required_host_os_release_id,
3309 required_host_os_release_version_id,
3310 required_host_os_release_sysext_level,
3311 required_sysext_scope,
3312 extension_release);
93f59701
LB
3313 if (r == 0)
3314 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
3315 if (r < 0)
3316 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
3317 }
3318
3044d343
YW
3319 r = dissected_image_relinquish(dissected_image);
3320 if (r < 0)
3321 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
4beda316
LB
3322
3323 return 0;
3324}