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