]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
copy: Support passing a deny list of files/directories to not copy
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
8c1be37e 2
10c1b188
LP
3#if HAVE_VALGRIND_MEMCHECK_H
4#include <valgrind/memcheck.h>
5#endif
6
01234e1f
YW
7#include <linux/dm-ioctl.h>
8#include <linux/loop.h>
19df770f 9#include <sys/file.h>
8c1be37e 10#include <sys/mount.h>
3b925504
LP
11#include <sys/prctl.h>
12#include <sys/wait.h>
f5ea63a5 13#include <sysexits.h>
8c1be37e 14
c2fa92e7
LP
15#if HAVE_OPENSSL
16#include <openssl/err.h>
17#include <openssl/pem.h>
18#include <openssl/x509.h>
19#endif
20
3c1f2cee 21#include "sd-device.h"
dccca82b
LP
22#include "sd-id128.h"
23
8c1be37e 24#include "architecture.h"
18b5886e 25#include "ask-password-api.h"
8c1be37e 26#include "blkid-util.h"
18c528e9 27#include "blockdev-util.h"
f4351959 28#include "chase-symlinks.h"
c2fa92e7 29#include "conf-files.h"
28db6fbf 30#include "constants.h"
3b925504 31#include "copy.h"
1e2f3230 32#include "cryptsetup-util.h"
553e15f2 33#include "device-nodes.h"
8437c059 34#include "device-util.h"
f7725647 35#include "devnum-util.h"
7718ac97 36#include "discover-image.h"
8c1be37e 37#include "dissect-image.h"
a709a315 38#include "dm-util.h"
686d13b9 39#include "env-file.h"
88b3300f 40#include "env-util.h"
93f59701 41#include "extension-release.h"
18b5886e 42#include "fd-util.h"
78ebe980 43#include "fileio.h"
2eedfd2d 44#include "fs-util.h"
cf32c486 45#include "fsck-util.h"
8c1be37e 46#include "gpt.h"
78ebe980 47#include "hexdecoct.h"
e2054217 48#include "hostname-setup.h"
3b925504 49#include "id128-util.h"
593fe6c0 50#include "import-util.h"
a4e0d617 51#include "io-util.h"
35cd0ba5 52#include "mkdir-label.h"
8c1be37e 53#include "mount-util.h"
e4de7287 54#include "mountpoint-util.h"
6aa05ebd 55#include "namespace-util.h"
d8b4d14d 56#include "nulstr-util.h"
c2fa92e7 57#include "openssl-util.h"
d58ad743 58#include "os-util.h"
8c1be37e 59#include "path-util.h"
3b925504
LP
60#include "process-util.h"
61#include "raw-clone.h"
81939d9d 62#include "resize-fs.h"
3b925504 63#include "signal-util.h"
8c1be37e 64#include "stat-util.h"
18b5886e 65#include "stdio-util.h"
8c1be37e
LP
66#include "string-table.h"
67#include "string-util.h"
2eedfd2d 68#include "strv.h"
e4de7287 69#include "tmpfile-util.h"
a8040b6d 70#include "udev-util.h"
2d3a5a73 71#include "user-util.h"
41488e1f 72#include "xattr-util.h"
8c1be37e 73
28e2641a
FF
74/* how many times to wait for the device nodes to appear */
75#define N_DEVICE_NODE_LIST_ATTEMPTS 10
76
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);
fab22946 1299 strv_free(m->initrd_release);
7718ac97 1300 strv_free(m->extension_release);
3b925504 1301
5fecf46d 1302 return mfree(m);
8c1be37e
LP
1303}
1304
18b5886e 1305static int is_loop_device(const char *path) {
553e15f2 1306 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
1307 struct stat st;
1308
1309 assert(path);
1310
1311 if (stat(path, &st) < 0)
1312 return -errno;
1313
1314 if (!S_ISBLK(st.st_mode))
1315 return -ENOTBLK;
1316
553e15f2 1317 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
1318 if (access(s, F_OK) < 0) {
1319 if (errno != ENOENT)
1320 return -errno;
1321
1322 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 1323 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
1324 if (access(s, F_OK) < 0)
1325 return errno == ENOENT ? false : -errno;
1326 }
1327
1328 return true;
1329}
1330
f8ab7812 1331static int run_fsck(int node_fd, const char *fstype) {
cf32c486
LP
1332 int r, exit_status;
1333 pid_t pid;
1334
f8ab7812 1335 assert(node_fd >= 0);
cf32c486
LP
1336 assert(fstype);
1337
13556724 1338 r = fsck_exists_for_fstype(fstype);
cf32c486
LP
1339 if (r < 0) {
1340 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1341 return 0;
1342 }
1343 if (r == 0) {
f8ab7812 1344 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd), fstype);
cf32c486
LP
1345 return 0;
1346 }
1347
f8ab7812
LP
1348 r = safe_fork_full(
1349 "(fsck)",
1350 &node_fd, 1, /* Leave the node fd open */
1351 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO|FORK_CLOEXEC_OFF,
1352 &pid);
cf32c486
LP
1353 if (r < 0)
1354 return log_debug_errno(r, "Failed to fork off fsck: %m");
1355 if (r == 0) {
1356 /* Child */
f8ab7812 1357 execl("/sbin/fsck", "/sbin/fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd), NULL);
7e0ed2e9 1358 log_open();
cf32c486
LP
1359 log_debug_errno(errno, "Failed to execl() fsck: %m");
1360 _exit(FSCK_OPERATIONAL_ERROR);
1361 }
1362
1363 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1364 if (exit_status < 0)
1365 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1366
1367 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1368 log_debug("fsck failed with exit status %i.", exit_status);
1369
1370 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1371 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1372
1373 log_debug("Ignoring fsck error.");
1374 }
1375
1376 return 0;
1377}
1378
81939d9d
LP
1379static int fs_grow(const char *node_path, const char *mount_path) {
1380 _cleanup_close_ int mount_fd = -1, node_fd = -1;
81939d9d
LP
1381 uint64_t size, newsize;
1382 int r;
1383
1384 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1385 if (node_fd < 0)
1386 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
1387
1388 if (ioctl(node_fd, BLKGETSIZE64, &size) != 0)
1389 return log_debug_errno(errno, "Failed to get block device size of %s: %m", node_path);
1390
1391 mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1392 if (mount_fd < 0)
1393 return log_debug_errno(errno, "Failed to open mountd file system %s: %m", mount_path);
1394
1395 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", mount_path, size);
1396 r = resize_fs(mount_fd, size, &newsize);
1397 if (r < 0)
1398 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", mount_path, size);
1399
1400 if (newsize == size)
1401 log_debug("Successfully resized \"%s\" to %s bytes.",
2b59bf51 1402 mount_path, FORMAT_BYTES(newsize));
81939d9d
LP
1403 else {
1404 assert(newsize < size);
1405 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
2b59bf51 1406 mount_path, FORMAT_BYTES(newsize), size - newsize);
81939d9d
LP
1407 }
1408
1409 return 0;
1410}
1411
18b5886e
LP
1412static int mount_partition(
1413 DissectedPartition *m,
1414 const char *where,
1415 const char *directory,
2d3a5a73 1416 uid_t uid_shift,
21b61b1d 1417 uid_t uid_range,
18b5886e
LP
1418 DissectImageFlags flags) {
1419
2d3a5a73
LP
1420 _cleanup_free_ char *chased = NULL, *options = NULL;
1421 const char *p, *node, *fstype;
21b61b1d 1422 bool rw, remap_uid_gid = false;
2eedfd2d 1423 int r;
8c1be37e
LP
1424
1425 assert(m);
1426 assert(where);
1427
f7725647
YW
1428 if (m->mount_node_fd < 0)
1429 return 0;
1430
4dc28665 1431 /* Use decrypted node and matching fstype if available, otherwise use the original device */
f7725647 1432 node = FORMAT_PROC_FD_PATH(m->mount_node_fd);
4dc28665 1433 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
18b5886e 1434
4dc28665
LP
1435 if (!fstype)
1436 return -EAFNOSUPPORT;
8c1be37e 1437
68ac5118
ZJS
1438 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller
1439 * didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this
1440 * case. */
4dc28665 1441 if (streq(fstype, "crypto_LUKS"))
fa45d12c 1442 return -EUNATCH;
18b5886e 1443
ef9c184d 1444 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
8c1be37e 1445
cf32c486 1446 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
f8ab7812 1447 r = run_fsck(m->mount_node_fd, fstype);
cf32c486
LP
1448 if (r < 0)
1449 return r;
1450 }
1451
2eedfd2d 1452 if (directory) {
334eb5b0
LP
1453 /* Automatically create missing mount points inside the image, if necessary. */
1454 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1455 if (r < 0 && r != -EROFS)
1456 return r;
1f0f82f1 1457
a5648b80 1458 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2eedfd2d
LP
1459 if (r < 0)
1460 return r;
1461
1462 p = chased;
9842905e
LP
1463 } else {
1464 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1465 * image (as the branch above does) but the host hierarchy, and the created directory might
1466 * survive our mount in the host hierarchy hence. */
1467 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1468 r = mkdir_p(where, 0755);
1469 if (r < 0)
1470 return r;
1471 }
1472
8c1be37e 1473 p = where;
9842905e 1474 }
8c1be37e 1475
18b5886e 1476 /* If requested, turn on discard support. */
154d2269 1477 if (fstype_can_discard(fstype) &&
18b5886e 1478 ((flags & DISSECT_IMAGE_DISCARD) ||
3afda7c7 1479 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
2d3a5a73
LP
1480 options = strdup("discard");
1481 if (!options)
1482 return -ENOMEM;
1483 }
1484
21b61b1d 1485 if (uid_is_valid(uid_shift) && uid_shift != 0) {
2d3a5a73 1486
21b61b1d
LP
1487 if (fstype_can_uid_gid(fstype)) {
1488 _cleanup_free_ char *uid_option = NULL;
2d3a5a73 1489
21b61b1d
LP
1490 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1491 return -ENOMEM;
1492
1493 if (!strextend_with_separator(&options, ",", uid_option))
1494 return -ENOMEM;
1495 } else if (FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED))
1496 remap_uid_gid = true;
2d3a5a73 1497 }
8c1be37e 1498
18d73705 1499 if (!isempty(m->mount_options))
c2bc710b 1500 if (!strextend_with_separator(&options, ",", m->mount_options))
18d73705
LB
1501 return -ENOMEM;
1502
b620bf33
LP
1503 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1504 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1505 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1506 * from the upper file system still get propagated through to the underlying file system,
1507 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1508 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1509 * carry a per file system table here.
1510 *
1511 * Note that this means that we might not be able to mount corrupted file systems as read-only
1512 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1513 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1514 * mount options for loopback devices this is the right choice, since otherwise using the same
1515 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1516 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1517 * access that actually modifies stuff work on such image files. Or to say this differently: if
1518 * people want their file systems to be fixed up they should just open them in writable mode, where
1519 * all these problems don't exist. */
1520 if (!rw && STRPTR_IN_SET(fstype, "ext3", "ext4", "xfs", "btrfs"))
1521 if (!strextend_with_separator(&options, ",", "norecovery"))
1522 return -ENOMEM;
1523
511a8cfe 1524 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
d9223c07
LP
1525 if (r < 0)
1526 return r;
1527
81939d9d
LP
1528 if (rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS))
1529 (void) fs_grow(node, p);
1530
21b61b1d 1531 if (remap_uid_gid) {
2b2777ed 1532 r = remount_idmap(p, uid_shift, uid_range, UID_INVALID, REMOUNT_IDMAPPING_HOST_ROOT);
21b61b1d
LP
1533 if (r < 0)
1534 return r;
1535 }
1536
d9223c07 1537 return 1;
8c1be37e
LP
1538}
1539
7cf66030
LP
1540static int mount_root_tmpfs(const char *where, uid_t uid_shift, DissectImageFlags flags) {
1541 _cleanup_free_ char *options = NULL;
1542 int r;
1543
1544 assert(where);
1545
1546 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1547
1548 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1549 r = mkdir_p(where, 0755);
1550 if (r < 0)
1551 return r;
1552 }
1553
1554 if (uid_is_valid(uid_shift)) {
1555 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1556 return -ENOMEM;
1557 }
1558
1559 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
1560 if (r < 0)
1561 return r;
1562
1563 return 1;
1564}
1565
21b61b1d
LP
1566int dissected_image_mount(
1567 DissectedImage *m,
1568 const char *where,
1569 uid_t uid_shift,
1570 uid_t uid_range,
1571 DissectImageFlags flags) {
1572
1f0f82f1 1573 int r, xbootldr_mounted;
8c1be37e
LP
1574
1575 assert(m);
1576 assert(where);
1577
fa45d12c
LP
1578 /* Returns:
1579 *
1580 * -ENXIO → No root partition found
7718ac97 1581 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
fa45d12c
LP
1582 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1583 * -EUCLEAN → fsck for file system failed
1584 * -EBUSY → File system already mounted/used elsewhere (kernel)
4dc28665 1585 * -EAFNOSUPPORT → File system type not supported or not known
fa45d12c
LP
1586 */
1587
7cf66030
LP
1588 if (!(m->partitions[PARTITION_ROOT].found ||
1589 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1590 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
8c1be37e 1591
2d3a5a73 1592 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
7cf66030
LP
1593
1594 /* First mount the root fs. If there's none we use a tmpfs. */
1595 if (m->partitions[PARTITION_ROOT].found)
21b61b1d 1596 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, flags);
7cf66030
LP
1597 else
1598 r = mount_root_tmpfs(where, uid_shift, flags);
2d3a5a73
LP
1599 if (r < 0)
1600 return r;
aee36b4e 1601
aee36b4e 1602 /* For us mounting root always means mounting /usr as well */
21b61b1d 1603 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, flags);
aee36b4e
LP
1604 if (r < 0)
1605 return r;
03bcb6d4 1606
9ccb531a
LB
1607 if ((flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
1608 /* If either one of the validation flags are set, ensure that the image qualifies
1609 * as one or the other (or both). */
1610 bool ok = false;
1611
1612 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
1613 r = path_is_os_tree(where);
1614 if (r < 0)
1615 return r;
1616 if (r > 0)
1617 ok = true;
1618 }
1619 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT)) {
06768b90 1620 r = path_is_extension_tree(where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_SYSEXT_CHECK));
7718ac97
LB
1621 if (r < 0)
1622 return r;
9ccb531a
LB
1623 if (r > 0)
1624 ok = true;
7718ac97 1625 }
9ccb531a
LB
1626
1627 if (!ok)
1628 return -ENOMEDIUM;
03bcb6d4 1629 }
2d3a5a73
LP
1630 }
1631
705727fd 1632 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 1633 return 0;
8c1be37e 1634
21b61b1d 1635 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, flags);
8c1be37e
LP
1636 if (r < 0)
1637 return r;
1638
21b61b1d 1639 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, flags);
8c1be37e
LP
1640 if (r < 0)
1641 return r;
1642
21b61b1d 1643 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, flags);
d4dffb85
LP
1644 if (r < 0)
1645 return r;
1646
21b61b1d 1647 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, flags);
d4dffb85
LP
1648 if (r < 0)
1649 return r;
1650
21b61b1d 1651 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, flags);
1f0f82f1
LP
1652 if (xbootldr_mounted < 0)
1653 return xbootldr_mounted;
d9223c07 1654
8c1be37e 1655 if (m->partitions[PARTITION_ESP].found) {
1f0f82f1
LP
1656 int esp_done = false;
1657
d9223c07
LP
1658 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1659 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
8c1be37e 1660
a5648b80 1661 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1f0f82f1
LP
1662 if (r < 0) {
1663 if (r != -ENOENT)
d9223c07 1664 return r;
8c1be37e 1665
1f0f82f1
LP
1666 /* /efi doesn't exist. Let's see if /boot is suitable then */
1667
1668 if (!xbootldr_mounted) {
1669 _cleanup_free_ char *p = NULL;
2eedfd2d 1670
1f0f82f1
LP
1671 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1672 if (r < 0) {
1673 if (r != -ENOENT)
1674 return r;
db55bbf2 1675 } else if (dir_is_empty(p, /* ignore_hidden_or_backup= */ false) > 0) {
1f0f82f1 1676 /* It exists and is an empty directory. Let's mount the ESP there. */
21b61b1d 1677 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, uid_range, flags);
1f0f82f1
LP
1678 if (r < 0)
1679 return r;
1680
1681 esp_done = true;
1682 }
2eedfd2d 1683 }
8c1be37e 1684 }
1f0f82f1
LP
1685
1686 if (!esp_done) {
1687 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1688
21b61b1d 1689 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, uid_range, flags);
1f0f82f1
LP
1690 if (r < 0)
1691 return r;
1692 }
8c1be37e
LP
1693 }
1694
1695 return 0;
1696}
1697
21b61b1d
LP
1698int dissected_image_mount_and_warn(
1699 DissectedImage *m,
1700 const char *where,
1701 uid_t uid_shift,
1702 uid_t uid_range,
1703 DissectImageFlags flags) {
1704
af187ab2
LP
1705 int r;
1706
1707 assert(m);
1708 assert(where);
1709
21b61b1d 1710 r = dissected_image_mount(m, where, uid_shift, uid_range, flags);
af187ab2
LP
1711 if (r == -ENXIO)
1712 return log_error_errno(r, "Not root file system found in image.");
1713 if (r == -EMEDIUMTYPE)
7718ac97 1714 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
af187ab2
LP
1715 if (r == -EUNATCH)
1716 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1717 if (r == -EUCLEAN)
1718 return log_error_errno(r, "File system check on image failed.");
1719 if (r == -EBUSY)
1720 return log_error_errno(r, "File system already mounted elsewhere.");
4dc28665
LP
1721 if (r == -EAFNOSUPPORT)
1722 return log_error_errno(r, "File system type not supported or not known.");
af187ab2
LP
1723 if (r < 0)
1724 return log_error_errno(r, "Failed to mount image: %m");
1725
1726 return r;
1727}
1728
349cc4a5 1729#if HAVE_LIBCRYPTSETUP
9321ad51 1730struct DecryptedPartition {
18b5886e
LP
1731 struct crypt_device *device;
1732 char *name;
1733 bool relinquished;
9321ad51
YW
1734};
1735#endif
1736
1737typedef struct DecryptedPartition DecryptedPartition;
18b5886e
LP
1738
1739struct DecryptedImage {
9321ad51 1740 unsigned n_ref;
18b5886e
LP
1741 DecryptedPartition *decrypted;
1742 size_t n_decrypted;
18b5886e 1743};
18b5886e 1744
9321ad51 1745static DecryptedImage* decrypted_image_free(DecryptedImage *d) {
349cc4a5 1746#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1747 int r;
1748
1749 if (!d)
1750 return NULL;
1751
67f63ee5 1752 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
1753 DecryptedPartition *p = d->decrypted + i;
1754
1755 if (p->device && p->name && !p->relinquished) {
ea16d7f4
YW
1756 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
1757 r = sym_crypt_deactivate_by_name(p->device, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
1758 if (r < 0)
1759 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1760 }
1761
1762 if (p->device)
0d12936d 1763 sym_crypt_free(p->device);
18b5886e
LP
1764 free(p->name);
1765 }
1766
f91861e4 1767 free(d->decrypted);
18b5886e
LP
1768 free(d);
1769#endif
1770 return NULL;
1771}
1772
9321ad51
YW
1773DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage, decrypted_image, decrypted_image_free);
1774
349cc4a5 1775#if HAVE_LIBCRYPTSETUP
9321ad51
YW
1776static int decrypted_image_new(DecryptedImage **ret) {
1777 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
1778
1779 assert(ret);
1780
1781 d = new(DecryptedImage, 1);
1782 if (!d)
1783 return -ENOMEM;
1784
1785 *d = (DecryptedImage) {
1786 .n_ref = 1,
1787 };
1788
1789 *ret = TAKE_PTR(d);
1790 return 0;
1791}
4623e8e6
LP
1792
1793static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1794 _cleanup_free_ char *name = NULL, *node = NULL;
1795 const char *base;
1796
1797 assert(original_node);
1798 assert(suffix);
1799 assert(ret_name);
1800 assert(ret_node);
1801
1802 base = strrchr(original_node, '/');
1803 if (!base)
ac1f3ad0
LB
1804 base = original_node;
1805 else
1806 base++;
4623e8e6
LP
1807 if (isempty(base))
1808 return -EINVAL;
1809
1810 name = strjoin(base, suffix);
1811 if (!name)
1812 return -ENOMEM;
1813 if (!filename_is_valid(name))
1814 return -EINVAL;
1815
0d12936d 1816 node = path_join(sym_crypt_get_dir(), name);
4623e8e6
LP
1817 if (!node)
1818 return -ENOMEM;
1819
1cc6c93a
YW
1820 *ret_name = TAKE_PTR(name);
1821 *ret_node = TAKE_PTR(node);
4623e8e6 1822
4623e8e6
LP
1823 return 0;
1824}
1825
18b5886e
LP
1826static int decrypt_partition(
1827 DissectedPartition *m,
1828 const char *passphrase,
1829 DissectImageFlags flags,
1830 DecryptedImage *d) {
1831
1832 _cleanup_free_ char *node = NULL, *name = NULL;
0d12936d 1833 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
f7725647 1834 _cleanup_close_ int fd = -1;
18b5886e
LP
1835 int r;
1836
1837 assert(m);
1838 assert(d);
1839
1840 if (!m->found || !m->node || !m->fstype)
1841 return 0;
1842
1843 if (!streq(m->fstype, "crypto_LUKS"))
1844 return 0;
1845
bdd73ac5
ZJS
1846 if (!passphrase)
1847 return -ENOKEY;
1848
0d12936d
LP
1849 r = dlopen_cryptsetup();
1850 if (r < 0)
1851 return r;
1852
4623e8e6
LP
1853 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1854 if (r < 0)
1855 return r;
18b5886e 1856
319a4f4b 1857 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
18b5886e
LP
1858 return -ENOMEM;
1859
0d12936d 1860 r = sym_crypt_init(&cd, m->node);
18b5886e 1861 if (r < 0)
715cbb81 1862 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 1863
efc3b12f 1864 cryptsetup_enable_logging(cd);
1887032f 1865
0d12936d 1866 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
1867 if (r < 0)
1868 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e 1869
0d12936d 1870 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
ef9c184d 1871 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
0d12936d 1872 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 1873 if (r < 0) {
715cbb81 1874 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 1875 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 1876 }
18b5886e 1877
f7725647
YW
1878 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
1879 if (fd < 0)
1880 return log_debug_errno(errno, "Failed to open %s: %m", node);
1881
94344385
LP
1882 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1883 .name = TAKE_PTR(name),
1884 .device = TAKE_PTR(cd),
1885 };
18b5886e 1886
1cc6c93a 1887 m->decrypted_node = TAKE_PTR(node);
f7725647 1888 close_and_replace(m->mount_node_fd, fd);
18b5886e
LP
1889
1890 return 0;
4623e8e6
LP
1891}
1892
89e62e0b
LP
1893static int verity_can_reuse(
1894 const VeritySettings *verity,
1895 const char *name,
1896 struct crypt_device **ret_cd) {
1897
ac1f3ad0
LB
1898 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1899 _cleanup_free_ char *root_hash_existing = NULL;
0d12936d 1900 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1901 struct crypt_params_verity crypt_params = {};
89e62e0b 1902 size_t root_hash_existing_size;
ac1f3ad0
LB
1903 int r;
1904
89e62e0b
LP
1905 assert(verity);
1906 assert(name);
ac1f3ad0
LB
1907 assert(ret_cd);
1908
0d12936d 1909 r = sym_crypt_init_by_name(&cd, name);
ac1f3ad0
LB
1910 if (r < 0)
1911 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
0d12936d 1912
c719805e
LP
1913 cryptsetup_enable_logging(cd);
1914
0d12936d 1915 r = sym_crypt_get_verity_info(cd, &crypt_params);
ac1f3ad0
LB
1916 if (r < 0)
1917 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
0d12936d 1918
89e62e0b
LP
1919 root_hash_existing_size = verity->root_hash_size;
1920 root_hash_existing = malloc0(root_hash_existing_size);
ac1f3ad0
LB
1921 if (!root_hash_existing)
1922 return -ENOMEM;
0d12936d
LP
1923
1924 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
ac1f3ad0
LB
1925 if (r < 0)
1926 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
89e62e0b
LP
1927 if (verity->root_hash_size != root_hash_existing_size ||
1928 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
ac1f3ad0 1929 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
89e62e0b 1930
ac1f3ad0 1931#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
1932 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1933 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
28423d9a 1934 * signing for the new one, and vice versa. */
89e62e0b 1935 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
ac1f3ad0
LB
1936 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1937#endif
1938
1939 *ret_cd = TAKE_PTR(cd);
1940 return 0;
1941}
1942
75db809a 1943static inline char* dm_deferred_remove_clean(char *name) {
ac1f3ad0 1944 if (!name)
75db809a 1945 return NULL;
0d12936d
LP
1946
1947 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
75db809a 1948 return mfree(name);
ac1f3ad0
LB
1949}
1950DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1951
c2fa92e7
LP
1952static int validate_signature_userspace(const VeritySettings *verity) {
1953#if HAVE_OPENSSL
1954 _cleanup_(sk_X509_free_allp) STACK_OF(X509) *sk = NULL;
1955 _cleanup_strv_free_ char **certs = NULL;
1956 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
1957 _cleanup_free_ char *s = NULL;
1958 _cleanup_(BIO_freep) BIO *bio = NULL; /* 'bio' must be freed first, 's' second, hence keep this order
1959 * of declaration in place, please */
1960 const unsigned char *d;
c2fa92e7
LP
1961 int r;
1962
1963 assert(verity);
1964 assert(verity->root_hash);
1965 assert(verity->root_hash_sig);
1966
1967 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
1968 * userspace validation. */
1969
1970 r = conf_files_list_nulstr(&certs, ".crt", NULL, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, CONF_PATHS_NULSTR("verity.d"));
1971 if (r < 0)
1972 return log_debug_errno(r, "Failed to enumerate certificates: %m");
1973 if (strv_isempty(certs)) {
1974 log_debug("No userspace dm-verity certificates found.");
1975 return 0;
1976 }
1977
1978 d = verity->root_hash_sig;
1979 p7 = d2i_PKCS7(NULL, &d, (long) verity->root_hash_sig_size);
1980 if (!p7)
1981 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PKCS7 DER signature data.");
1982
1983 s = hexmem(verity->root_hash, verity->root_hash_size);
1984 if (!s)
1985 return log_oom_debug();
1986
1987 bio = BIO_new_mem_buf(s, strlen(s));
1988 if (!bio)
1989 return log_oom_debug();
1990
1991 sk = sk_X509_new_null();
1992 if (!sk)
1993 return log_oom_debug();
1994
1995 STRV_FOREACH(i, certs) {
1996 _cleanup_(X509_freep) X509 *c = NULL;
1997 _cleanup_fclose_ FILE *f = NULL;
1998
1999 f = fopen(*i, "re");
2000 if (!f) {
2001 log_debug_errno(errno, "Failed to open '%s', ignoring: %m", *i);
2002 continue;
2003 }
2004
2005 c = PEM_read_X509(f, NULL, NULL, NULL);
2006 if (!c) {
2007 log_debug("Failed to load X509 certificate '%s', ignoring.", *i);
2008 continue;
2009 }
2010
2011 if (sk_X509_push(sk, c) == 0)
2012 return log_oom_debug();
2013
2014 TAKE_PTR(c);
2015 }
2016
2017 r = PKCS7_verify(p7, sk, NULL, bio, NULL, PKCS7_NOINTERN|PKCS7_NOVERIFY);
2018 if (r)
2019 log_debug("Userspace PKCS#7 validation succeeded.");
2020 else
2021 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL));
2022
2023 return r;
2024#else
2025 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2026 return 0;
2027#endif
2028}
2029
2030static int do_crypt_activate_verity(
2031 struct crypt_device *cd,
2032 const char *name,
2033 const VeritySettings *verity) {
2034
2035 bool check_signature;
2036 int r;
2037
2038 assert(cd);
2039 assert(name);
2040 assert(verity);
2041
2042 if (verity->root_hash_sig) {
2043 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2044 if (r < 0 && r != -ENXIO)
2045 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2046
2047 check_signature = r != 0;
2048 } else
2049 check_signature = false;
2050
2051 if (check_signature) {
2052
2053#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2054 /* First, if we have support for signed keys in the kernel, then try that first. */
2055 r = sym_crypt_activate_by_signed_key(
2056 cd,
2057 name,
2058 verity->root_hash,
2059 verity->root_hash_size,
2060 verity->root_hash_sig,
2061 verity->root_hash_sig_size,
2062 CRYPT_ACTIVATE_READONLY);
2063 if (r >= 0)
2064 return r;
2065
2066 log_debug("Validation of dm-verity signature failed via the kernel, trying userspace validation instead.");
2067#else
2068 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.",
2069 program_invocation_short_name);
2070#endif
2071
2072 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2073 * works we'll try to activate without telling the kernel the signature. */
2074
2075 r = validate_signature_userspace(verity);
2076 if (r < 0)
2077 return r;
2078 if (r == 0)
2079 return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY),
2080 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2081 }
2082
2083 return sym_crypt_activate_by_volume_key(
2084 cd,
2085 name,
2086 verity->root_hash,
2087 verity->root_hash_size,
2088 CRYPT_ACTIVATE_READONLY);
2089}
2090
ad361a50
YW
2091static usec_t verity_timeout(void) {
2092 usec_t t = 100 * USEC_PER_MSEC;
2093 const char *e;
2094 int r;
2095
2096 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2097 * Let's make the timeout configurable. */
2098
2099 e = getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2100 if (!e)
2101 return t;
2102
2103 r = parse_sec(e, &t);
2104 if (r < 0)
2105 log_debug_errno(r,
2106 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2107 "using the default timeout (%s).",
2108 FORMAT_TIMESPAN(t, USEC_PER_MSEC));
2109
2110 return t;
2111}
2112
4623e8e6 2113static int verity_partition(
aee36b4e 2114 PartitionDesignator designator,
4623e8e6
LP
2115 DissectedPartition *m,
2116 DissectedPartition *v,
89e62e0b 2117 const VeritySettings *verity,
4623e8e6
LP
2118 DissectImageFlags flags,
2119 DecryptedImage *d) {
2120
0d12936d 2121 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 2122 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
89e62e0b 2123 _cleanup_free_ char *node = NULL, *name = NULL;
f7725647 2124 _cleanup_close_ int mount_node_fd = -1;
4623e8e6
LP
2125 int r;
2126
2127 assert(m);
89e62e0b 2128 assert(v || (verity && verity->data_path));
4623e8e6 2129
89e62e0b 2130 if (!verity || !verity->root_hash)
4623e8e6 2131 return 0;
aee36b4e
LP
2132 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2133 (verity->designator == designator)))
2134 return 0;
4623e8e6
LP
2135
2136 if (!m->found || !m->node || !m->fstype)
2137 return 0;
89e62e0b 2138 if (!verity->data_path) {
e7cbe5cb
LB
2139 if (!v->found || !v->node || !v->fstype)
2140 return 0;
4623e8e6 2141
e7cbe5cb
LB
2142 if (!streq(v->fstype, "DM_verity_hash"))
2143 return 0;
2144 }
4623e8e6 2145
0d12936d
LP
2146 r = dlopen_cryptsetup();
2147 if (r < 0)
2148 return r;
2149
ac1f3ad0
LB
2150 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2151 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2152 _cleanup_free_ char *root_hash_encoded = NULL;
0d12936d 2153
89e62e0b 2154 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
ac1f3ad0
LB
2155 if (!root_hash_encoded)
2156 return -ENOMEM;
aee36b4e 2157
ac1f3ad0
LB
2158 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2159 } else
2160 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
4623e8e6
LP
2161 if (r < 0)
2162 return r;
2163
89e62e0b 2164 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
4623e8e6
LP
2165 if (r < 0)
2166 return r;
2167
efc3b12f 2168 cryptsetup_enable_logging(cd);
1887032f 2169
0d12936d 2170 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
4623e8e6 2171 if (r < 0)
294bd454 2172 return r;
4623e8e6 2173
0d12936d 2174 r = sym_crypt_set_data_device(cd, m->node);
4623e8e6 2175 if (r < 0)
294bd454 2176 return r;
4623e8e6 2177
319a4f4b 2178 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
ac1f3ad0
LB
2179 return -ENOMEM;
2180
2181 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2182 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2183 * retry a few times before giving up. */
2184 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
1d369d78 2185 _cleanup_(sym_crypt_freep) struct crypt_device *existing_cd = NULL;
f80015ff 2186 _cleanup_close_ int fd = -1;
c2fa92e7 2187
f80015ff
YW
2188 /* First, check if the device already exists. */
2189 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2190 if (fd < 0 && !ERRNO_IS_DEVICE_ABSENT(errno))
2191 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2192 if (fd >= 0)
2193 goto check; /* The device already exists. Let's check it. */
2194
2195 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
c2fa92e7 2196 r = do_crypt_activate_verity(cd, name, verity);
1d369d78 2197 if (r >= 0)
f7725647 2198 goto try_open; /* The device is activated. Let's open it. */
ac1f3ad0
LB
2199 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2200 * There's no way to distinguish this situation from a genuine error due to invalid
2aed63f4 2201 * parameters, so immediately fall back to activating the device with a unique name.
89e62e0b
LP
2202 * Improvements in libcrypsetup can ensure this never happens:
2203 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
ac1f3ad0 2204 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
0f75b0c5 2205 break;
1d369d78
YW
2206 if (r == -ENODEV) /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */
2207 goto try_again;
2208 if (!IN_SET(r,
2209 -EEXIST, /* Volume has already been opened and ready to be used. */
2210 -EBUSY /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2211 return log_debug_errno(r, "Failed to activate verity device %s: %m", node);
2212
f80015ff 2213 check:
1d369d78
YW
2214 if (!restore_deferred_remove){
2215 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2216 r = dm_deferred_remove_cancel(name);
12f5fbdf
YW
2217 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2218 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2219 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2220 if (IN_SET(r, -EBUSY, -ENXIO))
2221 goto try_again;
2222 if (r < 0)
1d369d78 2223 return log_debug_errno(r, "Failed to disable automated deferred removal for verity device %s: %m", node);
12f5fbdf
YW
2224
2225 restore_deferred_remove = strdup(name);
2226 if (!restore_deferred_remove)
2227 return log_oom_debug();
1d369d78 2228 }
c2923fdc 2229
1d369d78
YW
2230 r = verity_can_reuse(verity, name, &existing_cd);
2231 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2232 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2233 break;
2234 if (IN_SET(r,
2235 -ENOENT, /* Removed?? */
2236 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2237 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2238 goto try_again;
2239 if (r < 0)
2240 return log_debug_errno(r, "Failed to check if existing verity device %s can be reused: %m", node);
2241
f80015ff 2242 if (fd < 0) {
1d369d78
YW
2243 /* devmapper might say that the device exists, but the devlink might not yet have been
2244 * created. Check and wait for the udev event in that case. */
2245 r = device_wait_for_devlink(node, "block", verity_timeout(), NULL);
2246 /* Fallback to activation with a unique device if it's taking too long */
2247 if (r == -ETIMEDOUT && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
0f75b0c5 2248 break;
1d369d78
YW
2249 if (r < 0)
2250 return log_debug_errno(r, "Failed to wait device node symlink %s: %m", node);
c2923fdc 2251 }
ecab4c47 2252
f7725647
YW
2253 try_open:
2254 if (fd < 0) {
2255 /* Now, the device is activated and devlink is created. Let's open it. */
2256 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2257 if (fd < 0) {
2258 if (!ERRNO_IS_DEVICE_ABSENT(errno))
2259 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2260
2261 /* The device has already been removed?? */
2262 goto try_again;
2263 }
2264 }
2265
2266 mount_node_fd = TAKE_FD(fd);
1d369d78
YW
2267 if (existing_cd)
2268 crypt_free_and_replace(cd, existing_cd);
2269
2270 goto success;
2271
2272 try_again:
2273 /* Device is being removed by another process. Let's wait for a while. */
ecab4c47 2274 (void) usleep(2 * USEC_PER_MSEC);
ac1f3ad0
LB
2275 }
2276
0f75b0c5
YW
2277 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2278 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2279 /* Before trying to activate with unique name, we need to free crypt_device object.
2280 * Otherwise, we get error from libcryptsetup like the following:
2281 * ------
2282 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2283 * ------
2284 */
2285 sym_crypt_free(cd);
2286 cd = NULL;
aee36b4e 2287 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
0f75b0c5 2288 }
ac1f3ad0 2289
9972e6d6
YW
2290 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All attempts to activate verity device %s failed.", name);
2291
2292success:
ac1f3ad0
LB
2293 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2294 restore_deferred_remove = mfree(restore_deferred_remove);
4623e8e6 2295
94344385
LP
2296 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2297 .name = TAKE_PTR(name),
2298 .device = TAKE_PTR(cd),
2299 };
4623e8e6 2300
1cc6c93a 2301 m->decrypted_node = TAKE_PTR(node);
f7725647 2302 close_and_replace(m->mount_node_fd, mount_node_fd);
4623e8e6
LP
2303
2304 return 0;
18b5886e
LP
2305}
2306#endif
2307
2308int dissected_image_decrypt(
2309 DissectedImage *m,
2310 const char *passphrase,
89e62e0b 2311 const VeritySettings *verity,
e330f97a 2312 DissectImageFlags flags) {
18b5886e 2313
349cc4a5 2314#if HAVE_LIBCRYPTSETUP
49b5b3b4 2315 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
2316 int r;
2317#endif
2318
2319 assert(m);
89e62e0b 2320 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
18b5886e
LP
2321
2322 /* Returns:
2323 *
2324 * = 0 → There was nothing to decrypt
2325 * > 0 → Decrypted successfully
d1c536f5 2326 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
2327 * -EKEYREJECTED → Passed key was not correct
2328 */
2329
89e62e0b 2330 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
2331 return -EINVAL;
2332
e330f97a 2333 if (!m->encrypted && !m->verity_ready)
18b5886e 2334 return 0;
18b5886e 2335
349cc4a5 2336#if HAVE_LIBCRYPTSETUP
9321ad51
YW
2337 r = decrypted_image_new(&d);
2338 if (r < 0)
2339 return r;
18b5886e 2340
569a0e42 2341 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 2342 DissectedPartition *p = m->partitions + i;
22043172 2343 PartitionDesignator k;
18b5886e
LP
2344
2345 if (!p->found)
2346 continue;
2347
2348 r = decrypt_partition(p, passphrase, flags, d);
2349 if (r < 0)
2350 return r;
2351
4623e8e6
LP
2352 k = PARTITION_VERITY_OF(i);
2353 if (k >= 0) {
aee36b4e 2354 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
4623e8e6
LP
2355 if (r < 0)
2356 return r;
2357 }
2358
d2c6e79d
YW
2359 if (!p->decrypted_fstype && p->mount_node_fd >= 0 && p->decrypted_node) {
2360 r = probe_filesystem_full(p->mount_node_fd, p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 2361 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
2362 return r;
2363 }
2364 }
2365
ac1e1b5f 2366 m->decrypted_image = TAKE_PTR(d);
18b5886e
LP
2367
2368 return 1;
2369#else
2370 return -EOPNOTSUPP;
2371#endif
2372}
2373
2374int dissected_image_decrypt_interactively(
2375 DissectedImage *m,
2376 const char *passphrase,
89e62e0b 2377 const VeritySettings *verity,
e330f97a 2378 DissectImageFlags flags) {
18b5886e
LP
2379
2380 _cleanup_strv_free_erase_ char **z = NULL;
2381 int n = 3, r;
2382
2383 if (passphrase)
2384 n--;
2385
2386 for (;;) {
e330f97a 2387 r = dissected_image_decrypt(m, passphrase, verity, flags);
18b5886e
LP
2388 if (r >= 0)
2389 return r;
2390 if (r == -EKEYREJECTED)
2391 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
2392 else if (r != -ENOKEY)
2393 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 2394
baaa35ad
ZJS
2395 if (--n < 0)
2396 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
2397 "Too many retries.");
18b5886e
LP
2398
2399 z = strv_free(z);
2400
8806bb4b 2401 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY, 0, &z);
18b5886e
LP
2402 if (r < 0)
2403 return log_error_errno(r, "Failed to query for passphrase: %m");
2404
2405 passphrase = z[0];
2406 }
2407}
2408
e330f97a 2409static int decrypted_image_relinquish(DecryptedImage *d) {
18b5886e
LP
2410 assert(d);
2411
67f63ee5
ZJS
2412 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2413 * boolean so that we don't clean it up ourselves either anymore */
18b5886e 2414
349cc4a5 2415#if HAVE_LIBCRYPTSETUP
67f63ee5
ZJS
2416 int r;
2417
2418 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
2419 DecryptedPartition *p = d->decrypted + i;
2420
2421 if (p->relinquished)
2422 continue;
2423
0d12936d 2424 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
2425 if (r < 0)
2426 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
2427
2428 p->relinquished = true;
2429 }
2430#endif
2431
2432 return 0;
2433}
2434
f906075a
YW
2435int dissected_image_relinquish(DissectedImage *m) {
2436 int r;
2437
2438 assert(m);
2439
2440 if (m->decrypted_image) {
2441 r = decrypted_image_relinquish(m->decrypted_image);
2442 if (r < 0)
2443 return r;
2444 }
2445
2446 if (m->loop)
2447 loop_device_relinquish(m->loop);
2448
2449 return 0;
2450}
2451
89e62e0b
LP
2452static char *build_auxiliary_path(const char *image, const char *suffix) {
2453 const char *e;
2454 char *n;
2455
2456 assert(image);
2457 assert(suffix);
2458
2459 e = endswith(image, ".raw");
2460 if (!e)
2461 return strjoin(e, suffix);
2462
2463 n = new(char, e - image + strlen(suffix) + 1);
2464 if (!n)
2465 return NULL;
2466
2467 strcpy(mempcpy(n, image, e - image), suffix);
2468 return n;
2469}
2470
2471void verity_settings_done(VeritySettings *v) {
2472 assert(v);
2473
2474 v->root_hash = mfree(v->root_hash);
2475 v->root_hash_size = 0;
2476
2477 v->root_hash_sig = mfree(v->root_hash_sig);
2478 v->root_hash_sig_size = 0;
2479
2480 v->data_path = mfree(v->data_path);
2481}
2482
2483int verity_settings_load(
2484 VeritySettings *verity,
f5ea63a5
LP
2485 const char *image,
2486 const char *root_hash_path,
89e62e0b
LP
2487 const char *root_hash_sig_path) {
2488
2489 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2490 size_t root_hash_size = 0, root_hash_sig_size = 0;
2491 _cleanup_free_ char *verity_data_path = NULL;
aee36b4e 2492 PartitionDesignator designator;
78ebe980
LP
2493 int r;
2494
89e62e0b 2495 assert(verity);
78ebe980 2496 assert(image);
aee36b4e 2497 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
78ebe980 2498
89e62e0b
LP
2499 /* If we are asked to load the root hash for a device node, exit early */
2500 if (is_device_path(image))
78ebe980 2501 return 0;
78ebe980 2502
d5fcc5b0
LP
2503 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2504 if (r < 0 && r != -ENXIO)
2505 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2506 if (r == 0)
2507 return 0;
2508
aee36b4e
LP
2509 designator = verity->designator;
2510
89e62e0b 2511 /* We only fill in what isn't already filled in */
c2923fdc 2512
89e62e0b 2513 if (!verity->root_hash) {
e7cbe5cb 2514 _cleanup_free_ char *text = NULL;
e7cbe5cb 2515
0389f4fa 2516 if (root_hash_path) {
aee36b4e 2517 /* If explicitly specified it takes precedence */
0389f4fa
LB
2518 r = read_one_line_file(root_hash_path, &text);
2519 if (r < 0)
e7cbe5cb 2520 return r;
aee36b4e
LP
2521
2522 if (designator < 0)
2523 designator = PARTITION_ROOT;
0389f4fa 2524 } else {
aee36b4e
LP
2525 /* Otherwise look for xattr and separate file, and first for the data for root and if
2526 * that doesn't exist for /usr */
0389f4fa 2527
aee36b4e 2528 if (designator < 0 || designator == PARTITION_ROOT) {
c53e07e2 2529 r = getxattr_malloc(image, "user.verity.roothash", &text);
aee36b4e
LP
2530 if (r < 0) {
2531 _cleanup_free_ char *p = NULL;
78ebe980 2532
00675c36 2533 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
aee36b4e 2534 return r;
e7cbe5cb 2535
aee36b4e
LP
2536 p = build_auxiliary_path(image, ".roothash");
2537 if (!p)
2538 return -ENOMEM;
2539
2540 r = read_one_line_file(p, &text);
2541 if (r < 0 && r != -ENOENT)
2542 return r;
2543 }
2544
2545 if (text)
2546 designator = PARTITION_ROOT;
2547 }
2548
2549 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2550 /* So in the "roothash" xattr/file name above the "root" of course primarily
2551 * refers to the root of the Verity Merkle tree. But coincidentally it also
2552 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2553 * two distinct concepts called "root". Taking benefit of this happy
2554 * coincidence we call the file with the root hash for the /usr/ file system
2555 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2556 * confusing. We thus drop the reference to the root of the Merkle tree, and
2557 * just indicate which file system it's about. */
c53e07e2 2558 r = getxattr_malloc(image, "user.verity.usrhash", &text);
aee36b4e
LP
2559 if (r < 0) {
2560 _cleanup_free_ char *p = NULL;
2561
00675c36 2562 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
aee36b4e
LP
2563 return r;
2564
2565 p = build_auxiliary_path(image, ".usrhash");
2566 if (!p)
2567 return -ENOMEM;
2568
2569 r = read_one_line_file(p, &text);
2570 if (r < 0 && r != -ENOENT)
2571 return r;
2572 }
2573
2574 if (text)
2575 designator = PARTITION_USR;
0389f4fa 2576 }
e7cbe5cb
LB
2577 }
2578
2579 if (text) {
89e62e0b 2580 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
e7cbe5cb
LB
2581 if (r < 0)
2582 return r;
89e62e0b 2583 if (root_hash_size < sizeof(sd_id128_t))
e7cbe5cb
LB
2584 return -EINVAL;
2585 }
2586 }
2587
90f98986 2588 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
aee36b4e 2589 if (root_hash_sig_path) {
ae9cf30b 2590 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2591 if (r < 0 && r != -ENOENT)
2592 return r;
2593
2594 if (designator < 0)
2595 designator = PARTITION_ROOT;
2596 } else {
2597 if (designator < 0 || designator == PARTITION_ROOT) {
2598 _cleanup_free_ char *p = NULL;
2599
2600 /* Follow naming convention recommended by the relevant RFC:
2601 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2602 p = build_auxiliary_path(image, ".roothash.p7s");
2603 if (!p)
2604 return -ENOMEM;
89e62e0b 2605
ae9cf30b 2606 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2607 if (r < 0 && r != -ENOENT)
2608 return r;
2609 if (r >= 0)
2610 designator = PARTITION_ROOT;
2611 }
2612
2613 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2614 _cleanup_free_ char *p = NULL;
2615
2616 p = build_auxiliary_path(image, ".usrhash.p7s");
2617 if (!p)
2618 return -ENOMEM;
89e62e0b 2619
ae9cf30b 2620 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2621 if (r < 0 && r != -ENOENT)
2622 return r;
2623 if (r >= 0)
2624 designator = PARTITION_USR;
2625 }
89e62e0b
LP
2626 }
2627
aee36b4e 2628 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
89e62e0b
LP
2629 return -EINVAL;
2630 }
2631
2632 if (!verity->data_path) {
2633 _cleanup_free_ char *p = NULL;
2634
2635 p = build_auxiliary_path(image, ".verity");
2636 if (!p)
2637 return -ENOMEM;
2638
2639 if (access(p, F_OK) < 0) {
2640 if (errno != ENOENT)
2641 return -errno;
2642 } else
2643 verity_data_path = TAKE_PTR(p);
2644 }
2645
2646 if (root_hash) {
2647 verity->root_hash = TAKE_PTR(root_hash);
2648 verity->root_hash_size = root_hash_size;
2649 }
2650
2651 if (root_hash_sig) {
2652 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2653 verity->root_hash_sig_size = root_hash_sig_size;
e7cbe5cb 2654 }
89e62e0b
LP
2655
2656 if (verity_data_path)
2657 verity->data_path = TAKE_PTR(verity_data_path);
78ebe980 2658
aee36b4e
LP
2659 if (verity->designator < 0)
2660 verity->designator = designator;
2661
78ebe980
LP
2662 return 1;
2663}
2664
88b3300f
LP
2665int dissected_image_load_verity_sig_partition(
2666 DissectedImage *m,
2667 int fd,
2668 VeritySettings *verity) {
2669
2670 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2671 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
2672 size_t root_hash_size, root_hash_sig_size;
2673 _cleanup_free_ char *buf = NULL;
2674 PartitionDesignator d;
2675 DissectedPartition *p;
2676 JsonVariant *rh, *sig;
2677 ssize_t n;
2678 char *e;
2679 int r;
2680
2681 assert(m);
2682 assert(fd >= 0);
2683 assert(verity);
2684
2685 if (verity->root_hash && verity->root_hash_sig) /* Already loaded? */
2686 return 0;
2687
2688 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
2689 if (r < 0 && r != -ENXIO)
2690 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
2691 if (r == 0)
2692 return 0;
2693
2694 d = PARTITION_VERITY_SIG_OF(verity->designator < 0 ? PARTITION_ROOT : verity->designator);
2695 assert(d >= 0);
2696
2697 p = m->partitions + d;
2698 if (!p->found)
2699 return 0;
2700 if (p->offset == UINT64_MAX || p->size == UINT64_MAX)
2701 return -EINVAL;
2702
2703 if (p->size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
2704 return -EFBIG;
2705
2706 buf = new(char, p->size+1);
2707 if (!buf)
2708 return -ENOMEM;
2709
2710 n = pread(fd, buf, p->size, p->offset);
2711 if (n < 0)
2712 return -ENOMEM;
2713 if ((uint64_t) n != p->size)
2714 return -EIO;
2715
2716 e = memchr(buf, 0, p->size);
2717 if (e) {
2718 /* If we found a NUL byte then the rest of the data must be NUL too */
2719 if (!memeqzero(e, p->size - (e - buf)))
2720 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
2721 } else
2722 buf[p->size] = 0;
2723
2724 r = json_parse(buf, 0, &v, NULL, NULL);
2725 if (r < 0)
2726 return log_debug_errno(r, "Failed to parse signature JSON data: %m");
2727
2728 rh = json_variant_by_key(v, "rootHash");
2729 if (!rh)
2730 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
2731 if (!json_variant_is_string(rh))
2732 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'rootHash' field of signature JSON object is not a string.");
2733
2734 r = unhexmem(json_variant_string(rh), SIZE_MAX, &root_hash, &root_hash_size);
2735 if (r < 0)
2736 return log_debug_errno(r, "Failed to parse root hash field: %m");
2737
2738 /* Check if specified root hash matches if it is specified */
2739 if (verity->root_hash &&
2740 memcmp_nn(verity->root_hash, verity->root_hash_size, root_hash, root_hash_size) != 0) {
2741 _cleanup_free_ char *a = NULL, *b = NULL;
2742
2743 a = hexmem(root_hash, root_hash_size);
2744 b = hexmem(verity->root_hash, verity->root_hash_size);
2745
2746 return log_debug_errno(r, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a), strna(b));
2747 }
2748
2749 sig = json_variant_by_key(v, "signature");
2750 if (!sig)
2751 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
2752 if (!json_variant_is_string(sig))
2753 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'signature' field of signature JSON object is not a string.");
2754
2755 r = unbase64mem(json_variant_string(sig), SIZE_MAX, &root_hash_sig, &root_hash_sig_size);
2756 if (r < 0)
2757 return log_debug_errno(r, "Failed to parse signature field: %m");
2758
2759 free_and_replace(verity->root_hash, root_hash);
2760 verity->root_hash_size = root_hash_size;
2761
2762 free_and_replace(verity->root_hash_sig, root_hash_sig);
2763 verity->root_hash_sig_size = root_hash_sig_size;
2764
2765 return 1;
2766}
2767
22847508 2768int dissected_image_acquire_metadata(DissectedImage *m, DissectImageFlags extra_flags) {
3b925504
LP
2769
2770 enum {
2771 META_HOSTNAME,
2772 META_MACHINE_ID,
2773 META_MACHINE_INFO,
2774 META_OS_RELEASE,
fab22946 2775 META_INITRD_RELEASE,
7718ac97 2776 META_EXTENSION_RELEASE,
a4e0d617 2777 META_HAS_INIT_SYSTEM,
3b925504
LP
2778 _META_MAX,
2779 };
2780
9a4b883b 2781 static const char *const paths[_META_MAX] = {
7718ac97
LB
2782 [META_HOSTNAME] = "/etc/hostname\0",
2783 [META_MACHINE_ID] = "/etc/machine-id\0",
2784 [META_MACHINE_INFO] = "/etc/machine-info\0",
9a4b883b 2785 [META_OS_RELEASE] = ("/etc/os-release\0"
22847508 2786 "/usr/lib/os-release\0"),
fab22946
LP
2787 [META_INITRD_RELEASE] = ("/etc/initrd-release\0"
2788 "/usr/lib/initrd-release\0"),
a4e0d617
LP
2789 [META_EXTENSION_RELEASE] = "extension-release\0", /* Used only for logging. */
2790 [META_HAS_INIT_SYSTEM] = "has-init-system\0", /* ditto */
3b925504
LP
2791 };
2792
fab22946 2793 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **initrd_release = NULL, **extension_release = NULL;
af8219d5 2794 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
3b925504
LP
2795 _cleanup_(rmdir_and_freep) char *t = NULL;
2796 _cleanup_(sigkill_waitp) pid_t child = 0;
2797 sd_id128_t machine_id = SD_ID128_NULL;
2798 _cleanup_free_ char *hostname = NULL;
67f63ee5 2799 unsigned n_meta_initialized = 0;
af8219d5 2800 int fds[2 * _META_MAX], r, v;
a4e0d617 2801 int has_init_system = -1;
af8219d5 2802 ssize_t n;
3b925504
LP
2803
2804 BLOCK_SIGNALS(SIGCHLD);
2805
2806 assert(m);
2807
7718ac97 2808 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++) {
d9119c00
LP
2809 if (!paths[n_meta_initialized]) {
2810 fds[2*n_meta_initialized] = fds[2*n_meta_initialized+1] = -1;
7718ac97 2811 continue;
d9119c00
LP
2812 }
2813
3b925504
LP
2814 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2815 r = -errno;
2816 goto finish;
2817 }
7718ac97 2818 }
3b925504
LP
2819
2820 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2821 if (r < 0)
2822 goto finish;
2823
af8219d5
LP
2824 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2825 r = -errno;
2826 goto finish;
2827 }
2828
e2047ba9 2829 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 2830 if (r < 0)
3b925504 2831 goto finish;
be39f6ee 2832 if (r == 0) {
a4e0d617 2833 /* Child in a new mount namespace */
af8219d5
LP
2834 error_pipe[0] = safe_close(error_pipe[0]);
2835
7cf66030
LP
2836 r = dissected_image_mount(
2837 m,
2838 t,
2839 UID_INVALID,
21b61b1d 2840 UID_INVALID,
22847508
ZJS
2841 extra_flags |
2842 DISSECT_IMAGE_READ_ONLY |
2843 DISSECT_IMAGE_MOUNT_ROOT_ONLY |
7cf66030 2844 DISSECT_IMAGE_USR_NO_ROOT);
429d4e41
LP
2845 if (r < 0) {
2846 log_debug_errno(r, "Failed to mount dissected image: %m");
03ae68f4 2847 goto inner_fail;
429d4e41 2848 }
3b925504 2849
67f63ee5 2850 for (unsigned k = 0; k < _META_MAX; k++) {
37e44c3f 2851 _cleanup_close_ int fd = -ENOENT;
3b925504
LP
2852 const char *p;
2853
7718ac97
LB
2854 if (!paths[k])
2855 continue;
2856
3b925504
LP
2857 fds[2*k] = safe_close(fds[2*k]);
2858
a4e0d617
LP
2859 switch (k) {
2860
2861 case META_EXTENSION_RELEASE:
9a4b883b
LB
2862 /* As per the os-release spec, if the image is an extension it will have a file
2863 * named after the image name in extension-release.d/ - we use the image name
2864 * and try to resolve it with the extension-release helpers, as sometimes
2865 * the image names are mangled on deployment and do not match anymore.
2866 * Unlike other paths this is not fixed, and the image name
2867 * can be mangled on deployment, so by calling into the helper
2868 * we allow a fallback that matches on the first extension-release
2869 * file found in the directory, if one named after the image cannot
2870 * be found first. */
06768b90 2871 r = open_extension_release(t, m->image_name, /* relax_extension_release_check= */ false, NULL, &fd);
9a4b883b
LB
2872 if (r < 0)
2873 fd = r; /* Propagate the error. */
a4e0d617
LP
2874 break;
2875
2876 case META_HAS_INIT_SYSTEM: {
2877 bool found = false;
a4e0d617
LP
2878
2879 FOREACH_STRING(init,
2880 "/usr/lib/systemd/systemd", /* systemd on /usr merged system */
2881 "/lib/systemd/systemd", /* systemd on /usr non-merged systems */
2882 "/sbin/init") { /* traditional path the Linux kernel invokes */
2883
2884 r = chase_symlinks(init, t, CHASE_PREFIX_ROOT, NULL, NULL);
2885 if (r < 0) {
2886 if (r != -ENOENT)
2887 log_debug_errno(r, "Failed to resolve %s, ignoring: %m", init);
2888 } else {
2889 found = true;
2890 break;
2891 }
2892 }
2893
2894 r = loop_write(fds[2*k+1], &found, sizeof(found), false);
2895 if (r < 0)
2896 goto inner_fail;
2897
2898 continue;
2899 }
2900
2901 default:
9a4b883b
LB
2902 NULSTR_FOREACH(p, paths[k]) {
2903 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
2904 if (fd >= 0)
2905 break;
2906 }
a4e0d617
LP
2907 }
2908
36952d19
LP
2909 if (fd < 0) {
2910 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
37e44c3f 2911 fds[2*k+1] = safe_close(fds[2*k+1]);
3b925504 2912 continue;
36952d19 2913 }
3b925504 2914
f5fbe71d 2915 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
a4e0d617
LP
2916 if (r < 0)
2917 goto inner_fail;
3b925504
LP
2918
2919 fds[2*k+1] = safe_close(fds[2*k+1]);
2920 }
2921
2922 _exit(EXIT_SUCCESS);
a4e0d617
LP
2923
2924 inner_fail:
03ae68f4 2925 /* Let parent know the error */
a4e0d617
LP
2926 (void) write(error_pipe[1], &r, sizeof(r));
2927 _exit(EXIT_FAILURE);
3b925504
LP
2928 }
2929
af8219d5
LP
2930 error_pipe[1] = safe_close(error_pipe[1]);
2931
67f63ee5 2932 for (unsigned k = 0; k < _META_MAX; k++) {
3b925504
LP
2933 _cleanup_fclose_ FILE *f = NULL;
2934
7718ac97
LB
2935 if (!paths[k])
2936 continue;
2937
3b925504
LP
2938 fds[2*k+1] = safe_close(fds[2*k+1]);
2939
4fa744a3 2940 f = take_fdopen(&fds[2*k], "r");
3b925504
LP
2941 if (!f) {
2942 r = -errno;
2943 goto finish;
2944 }
2945
3b925504
LP
2946 switch (k) {
2947
2948 case META_HOSTNAME:
2949 r = read_etc_hostname_stream(f, &hostname);
2950 if (r < 0)
f6048e5e 2951 log_debug_errno(r, "Failed to read /etc/hostname of image: %m");
3b925504
LP
2952
2953 break;
2954
2955 case META_MACHINE_ID: {
2956 _cleanup_free_ char *line = NULL;
2957
2958 r = read_line(f, LONG_LINE_MAX, &line);
2959 if (r < 0)
f6048e5e 2960 log_debug_errno(r, "Failed to read /etc/machine-id of image: %m");
3b925504
LP
2961 else if (r == 33) {
2962 r = sd_id128_from_string(line, &machine_id);
2963 if (r < 0)
2964 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
2965 } else if (r == 0)
f6048e5e 2966 log_debug("/etc/machine-id file of image is empty.");
ab763cb2 2967 else if (streq(line, "uninitialized"))
f6048e5e 2968 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3b925504 2969 else
f6048e5e 2970 log_debug("/etc/machine-id file of image has unexpected length %i.", r);
3b925504
LP
2971
2972 break;
2973 }
2974
2975 case META_MACHINE_INFO:
aa8fbc74 2976 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504 2977 if (r < 0)
f6048e5e 2978 log_debug_errno(r, "Failed to read /etc/machine-info of image: %m");
3b925504
LP
2979
2980 break;
2981
2982 case META_OS_RELEASE:
aa8fbc74 2983 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504 2984 if (r < 0)
f6048e5e 2985 log_debug_errno(r, "Failed to read OS release file of image: %m");
3b925504
LP
2986
2987 break;
7718ac97 2988
fab22946
LP
2989 case META_INITRD_RELEASE:
2990 r = load_env_file_pairs(f, "initrd-release", &initrd_release);
2991 if (r < 0)
2992 log_debug_errno(r, "Failed to read initrd release file of image: %m");
2993
2994 break;
2995
7718ac97
LB
2996 case META_EXTENSION_RELEASE:
2997 r = load_env_file_pairs(f, "extension-release", &extension_release);
2998 if (r < 0)
f6048e5e 2999 log_debug_errno(r, "Failed to read extension release file of image: %m");
7718ac97
LB
3000
3001 break;
a4e0d617
LP
3002
3003 case META_HAS_INIT_SYSTEM: {
3004 bool b = false;
3005 size_t nr;
3006
3007 errno = 0;
3008 nr = fread(&b, 1, sizeof(b), f);
3009 if (nr != sizeof(b))
3010 log_debug_errno(errno_or_else(EIO), "Failed to read has-init-system boolean: %m");
3011 else
3012 has_init_system = b;
3013
3014 break;
3015 }}
3b925504
LP
3016 }
3017
2e87a1fd 3018 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 3019 child = 0;
2e87a1fd 3020 if (r < 0)
af8219d5
LP
3021 return r;
3022
3023 n = read(error_pipe[0], &v, sizeof(v));
3024 if (n < 0)
3025 return -errno;
3026 if (n == sizeof(v))
3027 return v; /* propagate error sent to us from child */
3028 if (n != 0)
3029 return -EIO;
3030
2e87a1fd
LP
3031 if (r != EXIT_SUCCESS)
3032 return -EPROTO;
3b925504
LP
3033
3034 free_and_replace(m->hostname, hostname);
3035 m->machine_id = machine_id;
3036 strv_free_and_replace(m->machine_info, machine_info);
3037 strv_free_and_replace(m->os_release, os_release);
fab22946 3038 strv_free_and_replace(m->initrd_release, initrd_release);
7718ac97 3039 strv_free_and_replace(m->extension_release, extension_release);
a4e0d617 3040 m->has_init_system = has_init_system;
3b925504
LP
3041
3042finish:
67f63ee5 3043 for (unsigned k = 0; k < n_meta_initialized; k++)
3b925504
LP
3044 safe_close_pair(fds + 2*k);
3045
3046 return r;
3047}
3048
1e63dc4f
YW
3049int dissect_loop_device(
3050 LoopDevice *loop,
3051 const VeritySettings *verity,
3052 const MountOptions *mount_options,
3053 DissectImageFlags flags,
3054 DissectedImage **ret) {
3055
08f14be4 3056#if HAVE_BLKID
1e63dc4f
YW
3057 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
3058 int r;
3059
3060 assert(loop);
3061 assert(ret);
3062
08f14be4 3063 r = dissected_image_new(loop->backing_file ?: loop->node, &m);
1e63dc4f
YW
3064 if (r < 0)
3065 return r;
3066
3067 m->loop = loop_device_ref(loop);
3068
08f14be4
YW
3069 r = dissect_image(m, loop->fd, loop->node, verity, mount_options, flags | DISSECT_IMAGE_BLOCK_DEVICE);
3070 if (r < 0)
3071 return r;
3072
3073 r = dissected_image_probe_filesystem(m);
3074 if (r < 0)
3075 return r;
3076
1e63dc4f
YW
3077 *ret = TAKE_PTR(m);
3078 return 0;
08f14be4
YW
3079#else
3080 return -EOPNOTSUPP;
3081#endif
1e63dc4f
YW
3082}
3083
bad31660 3084int dissect_loop_device_and_warn(
1e63dc4f 3085 LoopDevice *loop,
89e62e0b 3086 const VeritySettings *verity,
18d73705 3087 const MountOptions *mount_options,
4526113f
LP
3088 DissectImageFlags flags,
3089 DissectedImage **ret) {
3090
64dd3a24 3091 const char *name;
4526113f
LP
3092 int r;
3093
bad31660
YW
3094 assert(loop);
3095 assert(loop->fd >= 0);
4526113f 3096
64dd3a24 3097 name = ASSERT_PTR(loop->backing_file ?: loop->node);
4526113f 3098
369de26f 3099 r = dissect_loop_device(loop, verity, mount_options, flags, ret);
4526113f
LP
3100 switch (r) {
3101
3102 case -EOPNOTSUPP:
3103 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
3104
3105 case -ENOPKG:
48084df6
ZJS
3106 return log_error_errno(r, "%s: Couldn't identify a suitable partition table or file system.", name);
3107
3108 case -ENOMEDIUM:
3109 return log_error_errno(r, "%s: The image does not pass validation.", name);
4526113f
LP
3110
3111 case -EADDRNOTAVAIL:
48084df6 3112 return log_error_errno(r, "%s: No root partition for specified root hash found.", name);
4526113f
LP
3113
3114 case -ENOTUNIQ:
48084df6 3115 return log_error_errno(r, "%s: Multiple suitable root partitions found in image.", name);
4526113f
LP
3116
3117 case -ENXIO:
48084df6 3118 return log_error_errno(r, "%s: No suitable root partition found in image.", name);
4526113f
LP
3119
3120 case -EPROTONOSUPPORT:
3121 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
3122
48084df6
ZJS
3123 case -ENOTBLK:
3124 return log_error_errno(r, "%s: Image is not a block device.", name);
3125
a94aa2b9
LP
3126 case -EBADR:
3127 return log_error_errno(r,
3128 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
3129 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
3130 name, strna(verity ? verity->data_path : NULL));
3131
4526113f
LP
3132 default:
3133 if (r < 0)
3134 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
3135
3136 return r;
3137 }
3138}
3139
49536766
LP
3140bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
3141 assert(image);
3142
3143 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3144 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3145 * images we only check the partition type.
3146 *
3147 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3148 * image. */
3149
e7cbe5cb 3150 if (image->single_file_system)
c3c88d67 3151 return partition_designator == PARTITION_ROOT && image->has_verity;
e7cbe5cb
LB
3152
3153 return PARTITION_VERITY_OF(partition_designator) >= 0;
3154}
3155
49536766
LP
3156bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3157 PartitionDesignator k;
3158
3159 assert(image);
3160
3161 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3162 * works for the root partition, for others only if the associated verity partition was found. */
3163
3164 if (!image->verity_ready)
3165 return false;
e7cbe5cb
LB
3166
3167 if (image->single_file_system)
49536766 3168 return partition_designator == PARTITION_ROOT;
e7cbe5cb
LB
3169
3170 k = PARTITION_VERITY_OF(partition_designator);
3171 return k >= 0 && image->partitions[k].found;
3172}
3173
8ee9615e
LP
3174bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3175 PartitionDesignator k;
3176
3177 assert(image);
3178
3179 /* Checks if this partition has verity signature data available that we can use. */
3180
3181 if (!image->verity_sig_ready)
3182 return false;
3183
3184 if (image->single_file_system)
3185 return partition_designator == PARTITION_ROOT;
3186
3187 k = PARTITION_VERITY_SIG_OF(partition_designator);
3188 return k >= 0 && image->partitions[k].found;
3189}
3190
18d73705
LB
3191MountOptions* mount_options_free_all(MountOptions *options) {
3192 MountOptions *m;
3193
3194 while ((m = options)) {
3195 LIST_REMOVE(mount_options, options, m);
3196 free(m->options);
3197 free(m);
3198 }
3199
3200 return NULL;
3201}
3202
569a0e42 3203const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
f5215bc8 3204 LIST_FOREACH(mount_options, m, options)
9ece6444 3205 if (designator == m->partition_designator && !isempty(m->options))
18d73705 3206 return m->options;
6aa05ebd 3207
18d73705
LB
3208 return NULL;
3209}
3210
6aa05ebd
LP
3211int mount_image_privately_interactively(
3212 const char *image,
3213 DissectImageFlags flags,
3214 char **ret_directory,
e330f97a 3215 LoopDevice **ret_loop_device) {
6aa05ebd 3216
27ec815e 3217 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
6aa05ebd 3218 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
6aa05ebd
LP
3219 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3220 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
3221 _cleanup_free_ char *temp = NULL;
3222 int r;
3223
3224 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3225 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3226 * easily. */
3227
3228 assert(image);
3229 assert(ret_directory);
3230 assert(ret_loop_device);
6aa05ebd 3231
27ec815e
LP
3232 r = verity_settings_load(&verity, image, NULL, NULL);
3233 if (r < 0)
3234 return log_error_errno(r, "Failed to load root hash data: %m");
3235
6aa05ebd
LP
3236 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
3237 if (r < 0)
3238 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
3239
3240 r = loop_device_make_by_path(
3241 image,
ef9c184d 3242 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
6aa05ebd 3243 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
7f52206a 3244 LOCK_SH,
6aa05ebd
LP
3245 &d);
3246 if (r < 0)
7b87fe4c 3247 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
6aa05ebd 3248
64dd3a24 3249 r = dissect_loop_device_and_warn(d, &verity, NULL, flags, &dissected_image);
6aa05ebd
LP
3250 if (r < 0)
3251 return r;
3252
88b3300f
LP
3253 r = dissected_image_load_verity_sig_partition(dissected_image, d->fd, &verity);
3254 if (r < 0)
3255 return r;
3256
e330f97a 3257 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags);
6aa05ebd
LP
3258 if (r < 0)
3259 return r;
3260
3261 r = detach_mount_namespace();
3262 if (r < 0)
3263 return log_error_errno(r, "Failed to detach mount namespace: %m");
3264
3265 r = mkdir_p(temp, 0700);
3266 if (r < 0)
3267 return log_error_errno(r, "Failed to create mount point: %m");
3268
3269 created_dir = TAKE_PTR(temp);
3270
21b61b1d 3271 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, UID_INVALID, flags);
6aa05ebd 3272 if (r < 0)
af187ab2 3273 return r;
6aa05ebd 3274
41bc4849
LP
3275 r = loop_device_flock(d, LOCK_UN);
3276 if (r < 0)
3277 return r;
3278
3044d343
YW
3279 r = dissected_image_relinquish(dissected_image);
3280 if (r < 0)
3281 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
6aa05ebd
LP
3282
3283 *ret_directory = TAKE_PTR(created_dir);
3284 *ret_loop_device = TAKE_PTR(d);
6aa05ebd
LP
3285
3286 return 0;
3287}
3288
8c1be37e 3289static const char *const partition_designator_table[] = {
68ac5118
ZJS
3290 [PARTITION_ROOT] = "root",
3291 [PARTITION_ROOT_SECONDARY] = "root-secondary",
3292 [PARTITION_ROOT_OTHER] = "root-other",
3293 [PARTITION_USR] = "usr",
3294 [PARTITION_USR_SECONDARY] = "usr-secondary",
3295 [PARTITION_USR_OTHER] = "usr-other",
3296 [PARTITION_HOME] = "home",
3297 [PARTITION_SRV] = "srv",
3298 [PARTITION_ESP] = "esp",
3299 [PARTITION_XBOOTLDR] = "xbootldr",
3300 [PARTITION_SWAP] = "swap",
3301 [PARTITION_ROOT_VERITY] = "root-verity",
3302 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
3303 [PARTITION_ROOT_OTHER_VERITY] = "root-other-verity",
3304 [PARTITION_USR_VERITY] = "usr-verity",
3305 [PARTITION_USR_SECONDARY_VERITY] = "usr-secondary-verity",
3306 [PARTITION_USR_OTHER_VERITY] = "usr-other-verity",
3307 [PARTITION_ROOT_VERITY_SIG] = "root-verity-sig",
8ee9615e 3308 [PARTITION_ROOT_SECONDARY_VERITY_SIG] = "root-secondary-verity-sig",
68ac5118
ZJS
3309 [PARTITION_ROOT_OTHER_VERITY_SIG] = "root-other-verity-sig",
3310 [PARTITION_USR_VERITY_SIG] = "usr-verity-sig",
3311 [PARTITION_USR_SECONDARY_VERITY_SIG] = "usr-secondary-verity-sig",
3312 [PARTITION_USR_OTHER_VERITY_SIG] = "usr-other-verity-sig",
3313 [PARTITION_TMP] = "tmp",
3314 [PARTITION_VAR] = "var",
8c1be37e
LP
3315};
3316
06768b90
LB
3317static bool mount_options_relax_extension_release_checks(const MountOptions *options) {
3318 if (!options)
3319 return false;
3320
3321 return string_contains_word(mount_options_from_designator(options, PARTITION_ROOT), ",", "x-systemd.relax-extension-release-check") ||
3322 string_contains_word(mount_options_from_designator(options, PARTITION_USR), ",", "x-systemd.relax-extension-release-check") ||
3323 string_contains_word(options->options, ",", "x-systemd.relax-extension-release-check");
3324}
3325
93f59701 3326int verity_dissect_and_mount(
cedf5b1a 3327 int src_fd,
93f59701
LB
3328 const char *src,
3329 const char *dest,
3330 const MountOptions *options,
3331 const char *required_host_os_release_id,
3332 const char *required_host_os_release_version_id,
60c5f700
LP
3333 const char *required_host_os_release_sysext_level,
3334 const char *required_sysext_scope) {
93f59701 3335
4beda316 3336 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
4beda316
LB
3337 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3338 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3339 DissectImageFlags dissect_image_flags;
06768b90 3340 bool relax_extension_release_check;
4beda316
LB
3341 int r;
3342
3343 assert(src);
3344 assert(dest);
3345
06768b90
LB
3346 relax_extension_release_check = mount_options_relax_extension_release_checks(options);
3347
cedf5b1a 3348 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
4beda316
LB
3349 r = verity_settings_load(&verity, src, NULL, NULL);
3350 if (r < 0)
3351 return log_debug_errno(r, "Failed to load root hash: %m");
3352
06768b90
LB
3353 dissect_image_flags = (verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0) |
3354 (relax_extension_release_check ? DISSECT_IMAGE_RELAX_SYSEXT_CHECK : 0);
4beda316 3355
cedf5b1a
LB
3356 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
3357 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4beda316 3358 r = loop_device_make_by_path(
cedf5b1a 3359 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
4beda316
LB
3360 -1,
3361 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
7f52206a 3362 LOCK_SH,
4beda316
LB
3363 &loop_device);
3364 if (r < 0)
3365 return log_debug_errno(r, "Failed to create loop device for image: %m");
3366
bad31660
YW
3367 r = dissect_loop_device(
3368 loop_device,
4beda316
LB
3369 &verity,
3370 options,
3371 dissect_image_flags,
3372 &dissected_image);
3373 /* No partition table? Might be a single-filesystem image, try again */
3374 if (!verity.data_path && r == -ENOPKG)
bad31660
YW
3375 r = dissect_loop_device(
3376 loop_device,
4beda316
LB
3377 &verity,
3378 options,
75dc190d 3379 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
4beda316
LB
3380 &dissected_image);
3381 if (r < 0)
3382 return log_debug_errno(r, "Failed to dissect image: %m");
3383
88b3300f
LP
3384 r = dissected_image_load_verity_sig_partition(dissected_image, loop_device->fd, &verity);
3385 if (r < 0)
3386 return r;
3387
4beda316
LB
3388 r = dissected_image_decrypt(
3389 dissected_image,
3390 NULL,
3391 &verity,
e330f97a 3392 dissect_image_flags);
4beda316
LB
3393 if (r < 0)
3394 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
3395
3396 r = mkdir_p_label(dest, 0755);
3397 if (r < 0)
3398 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
3399 r = umount_recursive(dest, 0);
3400 if (r < 0)
3401 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
3402
21b61b1d 3403 r = dissected_image_mount(dissected_image, dest, UID_INVALID, UID_INVALID, dissect_image_flags);
4beda316
LB
3404 if (r < 0)
3405 return log_debug_errno(r, "Failed to mount image: %m");
3406
41bc4849
LP
3407 r = loop_device_flock(loop_device, LOCK_UN);
3408 if (r < 0)
3409 return log_debug_errno(r, "Failed to unlock loopback device: %m");
3410
93f59701
LB
3411 /* If we got os-release values from the caller, then we need to match them with the image's
3412 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3413 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
37361f46
LB
3414 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
3415 * then a simple match on the ID will be performed. */
8b2dcbbd 3416 if (required_host_os_release_id) {
93f59701
LB
3417 _cleanup_strv_free_ char **extension_release = NULL;
3418
d30d86b7
YW
3419 assert(!isempty(required_host_os_release_id));
3420
06768b90 3421 r = load_extension_release_pairs(dest, dissected_image->image_name, relax_extension_release_check, &extension_release);
93f59701
LB
3422 if (r < 0)
3423 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
3424
3425 r = extension_release_validate(
60c5f700
LP
3426 dissected_image->image_name,
3427 required_host_os_release_id,
3428 required_host_os_release_version_id,
3429 required_host_os_release_sysext_level,
3430 required_sysext_scope,
3431 extension_release);
93f59701
LB
3432 if (r == 0)
3433 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
3434 if (r < 0)
3435 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
3436 }
3437
3044d343
YW
3438 r = dissected_image_relinquish(dissected_image);
3439 if (r < 0)
3440 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
4beda316
LB
3441
3442 return 0;
3443}
3444
569a0e42 3445DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);