]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
Merge pull request #31531 from poettering/verity-userspace-optional
[thirdparty/systemd.git] / src / shared / dissect-image.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
5 #endif
6
7 #include <linux/dm-ioctl.h>
8 #include <linux/loop.h>
9 #include <sys/file.h>
10 #include <sys/mount.h>
11 #include <sys/prctl.h>
12 #include <sys/wait.h>
13 #include <sysexits.h>
14
15 #if HAVE_OPENSSL
16 #include <openssl/err.h>
17 #include <openssl/pem.h>
18 #include <openssl/x509.h>
19 #endif
20
21 #include "sd-device.h"
22 #include "sd-id128.h"
23
24 #include "architecture.h"
25 #include "ask-password-api.h"
26 #include "blkid-util.h"
27 #include "blockdev-util.h"
28 #include "btrfs-util.h"
29 #include "chase.h"
30 #include "conf-files.h"
31 #include "constants.h"
32 #include "copy.h"
33 #include "cryptsetup-util.h"
34 #include "device-nodes.h"
35 #include "device-util.h"
36 #include "devnum-util.h"
37 #include "discover-image.h"
38 #include "dissect-image.h"
39 #include "dm-util.h"
40 #include "env-file.h"
41 #include "env-util.h"
42 #include "extension-util.h"
43 #include "fd-util.h"
44 #include "fileio.h"
45 #include "fs-util.h"
46 #include "fsck-util.h"
47 #include "gpt.h"
48 #include "hexdecoct.h"
49 #include "hostname-setup.h"
50 #include "id128-util.h"
51 #include "import-util.h"
52 #include "io-util.h"
53 #include "missing_mount.h"
54 #include "missing_syscall.h"
55 #include "mkdir-label.h"
56 #include "mount-util.h"
57 #include "mountpoint-util.h"
58 #include "namespace-util.h"
59 #include "nulstr-util.h"
60 #include "openssl-util.h"
61 #include "os-util.h"
62 #include "path-util.h"
63 #include "proc-cmdline.h"
64 #include "process-util.h"
65 #include "raw-clone.h"
66 #include "resize-fs.h"
67 #include "signal-util.h"
68 #include "sparse-endian.h"
69 #include "stat-util.h"
70 #include "stdio-util.h"
71 #include "string-table.h"
72 #include "string-util.h"
73 #include "strv.h"
74 #include "tmpfile-util.h"
75 #include "udev-util.h"
76 #include "user-util.h"
77 #include "xattr-util.h"
78
79 /* how many times to wait for the device nodes to appear */
80 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
81
82 int dissect_fstype_ok(const char *fstype) {
83 const char *e;
84 bool b;
85
86 /* When we automatically mount file systems, be a bit conservative by default what we are willing to
87 * mount, just as an extra safety net to not mount with badly maintained legacy file system
88 * drivers. */
89
90 e = secure_getenv("SYSTEMD_DISSECT_FILE_SYSTEMS");
91 if (e) {
92 _cleanup_strv_free_ char **l = NULL;
93
94 l = strv_split(e, ":");
95 if (!l)
96 return -ENOMEM;
97
98 b = strv_contains(l, fstype);
99 } else
100 b = STR_IN_SET(fstype,
101 "btrfs",
102 "erofs",
103 "ext4",
104 "f2fs",
105 "squashfs",
106 "vfat",
107 "xfs");
108 if (b)
109 return true;
110
111 log_debug("File system type '%s' is not allowed to be mounted as result of automatic dissection.", fstype);
112 return false;
113 }
114
115 int probe_sector_size(int fd, uint32_t *ret) {
116
117 /* Disk images might be for 512B or for 4096 sector sizes, let's try to auto-detect that by searching
118 * for the GPT headers at the relevant byte offsets */
119
120 assert_cc(sizeof(GptHeader) == 92);
121
122 /* We expect a sector size in the range 512…4096. The GPT header is located in the second
123 * sector. Hence it could be at byte 512 at the earliest, and at byte 4096 at the latest. And we must
124 * read with granularity of the largest sector size we care about. Which means 8K. */
125 uint8_t sectors[2 * 4096];
126 uint32_t found = 0;
127 ssize_t n;
128
129 assert(fd >= 0);
130 assert(ret);
131
132 n = pread(fd, sectors, sizeof(sectors), 0);
133 if (n < 0)
134 return -errno;
135 if (n != sizeof(sectors)) /* too short? */
136 goto not_found;
137
138 /* Let's see if we find the GPT partition header with various expected sector sizes */
139 for (uint32_t sz = 512; sz <= 4096; sz <<= 1) {
140 const GptHeader *p;
141
142 assert(sizeof(sectors) >= sz * 2);
143 p = (const GptHeader*) (sectors + sz);
144
145 if (!gpt_header_has_signature(p))
146 continue;
147
148 if (found != 0)
149 return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
150 "Detected valid partition table at offsets matching multiple sector sizes, refusing.");
151
152 found = sz;
153 }
154
155 if (found != 0) {
156 log_debug("Determined sector size %" PRIu32 " based on discovered partition table.", found);
157 *ret = found;
158 return 1; /* indicate we *did* find it */
159 }
160
161 not_found:
162 log_debug("Couldn't find any partition table to derive sector size of.");
163 *ret = 512; /* pick the traditional default */
164 return 0; /* indicate we didn't find it */
165 }
166
167 int probe_sector_size_prefer_ioctl(int fd, uint32_t *ret) {
168 struct stat st;
169
170 assert(fd >= 0);
171 assert(ret);
172
173 /* Just like probe_sector_size(), but if we are looking at a block device, will use the already
174 * configured sector size rather than probing by contents */
175
176 if (fstat(fd, &st) < 0)
177 return -errno;
178
179 if (S_ISBLK(st.st_mode))
180 return blockdev_get_sector_size(fd, ret);
181
182 return probe_sector_size(fd, ret);
183 }
184
185 int probe_filesystem_full(
186 int fd,
187 const char *path,
188 uint64_t offset,
189 uint64_t size,
190 char **ret_fstype) {
191
192 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
193 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
194 * different error otherwise. */
195
196 #if HAVE_BLKID
197 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
198 _cleanup_free_ char *path_by_fd = NULL;
199 _cleanup_close_ int fd_close = -EBADF;
200 const char *fstype;
201 int r;
202
203 assert(fd >= 0 || path);
204 assert(ret_fstype);
205
206 if (fd < 0) {
207 fd_close = open(path, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
208 if (fd_close < 0)
209 return -errno;
210
211 fd = fd_close;
212 }
213
214 if (!path) {
215 r = fd_get_path(fd, &path_by_fd);
216 if (r < 0)
217 return r;
218
219 path = path_by_fd;
220 }
221
222 if (size == 0) /* empty size? nothing found! */
223 goto not_found;
224
225 b = blkid_new_probe();
226 if (!b)
227 return -ENOMEM;
228
229 /* The Linux kernel maintains separate block device caches for main ("whole") and partition block
230 * devices, which means making a change to one might not be reflected immediately when reading via
231 * the other. That's massively confusing when mixing accesses to such devices. Let's address this in
232 * a limited way: when probing a file system that is not at the beginning of the block device we
233 * apparently probe a partition via the main block device, and in that case let's first flush the
234 * main block device cache, so that we get the data that the per-partition block device last
235 * sync'ed on.
236 *
237 * This only works under the assumption that any tools that write to the partition block devices
238 * issue an syncfs()/fsync() on the device after making changes. Typically file system formatting
239 * tools that write a superblock onto a partition block device do that, however. */
240 if (offset != 0)
241 if (ioctl(fd, BLKFLSBUF, 0) < 0)
242 log_debug_errno(errno, "Failed to flush block device cache, ignoring: %m");
243
244 errno = 0;
245 r = blkid_probe_set_device(
246 b,
247 fd,
248 offset,
249 size == UINT64_MAX ? 0 : size); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
250 if (r != 0)
251 return errno_or_else(ENOMEM);
252
253 blkid_probe_enable_superblocks(b, 1);
254 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
255
256 errno = 0;
257 r = blkid_do_safeprobe(b);
258 if (r == _BLKID_SAFEPROBE_NOT_FOUND)
259 goto not_found;
260 if (r == _BLKID_SAFEPROBE_AMBIGUOUS)
261 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
262 "Results ambiguous for partition %s", path);
263 if (r == _BLKID_SAFEPROBE_ERROR)
264 return log_debug_errno(errno_or_else(EIO), "Failed to probe partition %s: %m", path);
265
266 assert(r == _BLKID_SAFEPROBE_FOUND);
267
268 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
269
270 if (fstype) {
271 char *t;
272
273 log_debug("Probed fstype '%s' on partition %s.", fstype, path);
274
275 t = strdup(fstype);
276 if (!t)
277 return -ENOMEM;
278
279 *ret_fstype = t;
280 return 1;
281 }
282
283 not_found:
284 log_debug("No type detected on partition %s", path);
285 *ret_fstype = NULL;
286 return 0;
287 #else
288 return -EOPNOTSUPP;
289 #endif
290 }
291
292 #if HAVE_BLKID
293 static int image_policy_may_use(
294 const ImagePolicy *policy,
295 PartitionDesignator designator) {
296
297 PartitionPolicyFlags f;
298
299 /* For each partition we find in the partition table do a first check if it may exist at all given
300 * the policy, or if it shall be ignored. */
301
302 f = image_policy_get_exhaustively(policy, designator);
303 if (f < 0)
304 return f;
305
306 if ((f & _PARTITION_POLICY_USE_MASK) == PARTITION_POLICY_ABSENT)
307 /* only flag set in policy is "absent"? then this partition may not exist at all */
308 return log_debug_errno(
309 SYNTHETIC_ERRNO(ERFKILL),
310 "Partition of designator '%s' exists, but not allowed by policy, refusing.",
311 partition_designator_to_string(designator));
312 if ((f & _PARTITION_POLICY_USE_MASK & ~PARTITION_POLICY_ABSENT) == PARTITION_POLICY_UNUSED) {
313 /* only "unused" or "unused" + "absent" are set? then don't use it */
314 log_debug("Partition of designator '%s' exists, and policy dictates to ignore it, doing so.",
315 partition_designator_to_string(designator));
316 return false; /* ignore! */
317 }
318
319 return true; /* use! */
320 }
321
322 static int image_policy_check_protection(
323 const ImagePolicy *policy,
324 PartitionDesignator designator,
325 PartitionPolicyFlags found_flags) {
326
327 PartitionPolicyFlags policy_flags;
328
329 /* Checks if the flags in the policy for the designated partition overlap the flags of what we found */
330
331 if (found_flags < 0)
332 return found_flags;
333
334 policy_flags = image_policy_get_exhaustively(policy, designator);
335 if (policy_flags < 0)
336 return policy_flags;
337
338 if ((found_flags & policy_flags) == 0) {
339 _cleanup_free_ char *found_flags_string = NULL, *policy_flags_string = NULL;
340
341 (void) partition_policy_flags_to_string(found_flags, /* simplify= */ true, &found_flags_string);
342 (void) partition_policy_flags_to_string(policy_flags, /* simplify= */ true, &policy_flags_string);
343
344 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s discovered with policy '%s' but '%s' was required, refusing.",
345 partition_designator_to_string(designator),
346 strnull(found_flags_string), strnull(policy_flags_string));
347 }
348
349 return 0;
350 }
351
352 static int image_policy_check_partition_flags(
353 const ImagePolicy *policy,
354 PartitionDesignator designator,
355 uint64_t gpt_flags) {
356
357 PartitionPolicyFlags policy_flags;
358 bool b;
359
360 /* Checks if the partition flags in the policy match reality */
361
362 policy_flags = image_policy_get_exhaustively(policy, designator);
363 if (policy_flags < 0)
364 return policy_flags;
365
366 b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_READ_ONLY);
367 if ((policy_flags & _PARTITION_POLICY_READ_ONLY_MASK) == (b ? PARTITION_POLICY_READ_ONLY_OFF : PARTITION_POLICY_READ_ONLY_ON))
368 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'read-only' flag incorrectly set (must be %s, is %s), refusing.",
369 partition_designator_to_string(designator),
370 one_zero(!b), one_zero(b));
371
372 b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_GROWFS);
373 if ((policy_flags & _PARTITION_POLICY_GROWFS_MASK) == (b ? PARTITION_POLICY_GROWFS_OFF : PARTITION_POLICY_GROWFS_ON))
374 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'growfs' flag incorrectly set (must be %s, is %s), refusing.",
375 partition_designator_to_string(designator),
376 one_zero(!b), one_zero(b));
377
378 return 0;
379 }
380
381 static int dissected_image_probe_filesystems(
382 DissectedImage *m,
383 int fd,
384 const ImagePolicy *policy) {
385
386 int r;
387
388 assert(m);
389
390 /* Fill in file system types if we don't know them yet. */
391
392 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
393 DissectedPartition *p = m->partitions + i;
394 PartitionPolicyFlags found_flags;
395
396 if (!p->found)
397 continue;
398
399 if (!p->fstype) {
400 /* If we have an fd referring to the partition block device, use that. Otherwise go
401 * via the whole block device or backing regular file, and read via offset. */
402 if (p->mount_node_fd >= 0)
403 r = probe_filesystem_full(p->mount_node_fd, p->node, 0, UINT64_MAX, &p->fstype);
404 else
405 r = probe_filesystem_full(fd, p->node, p->offset, p->size, &p->fstype);
406 if (r < 0)
407 return r;
408 }
409
410 if (streq_ptr(p->fstype, "crypto_LUKS")) {
411 m->encrypted = true;
412 found_flags = PARTITION_POLICY_ENCRYPTED; /* found this one, and its definitely encrypted */
413 } else
414 /* found it, but it's definitely not encrypted, hence mask the encrypted flag, but
415 * set all other ways that indicate "present". */
416 found_flags = PARTITION_POLICY_UNPROTECTED|PARTITION_POLICY_VERITY|PARTITION_POLICY_SIGNED;
417
418 if (p->fstype && fstype_is_ro(p->fstype))
419 p->rw = false;
420
421 if (!p->rw)
422 p->growfs = false;
423
424 /* We might have learnt more about the file system now (i.e. whether it is encrypted or not),
425 * hence we need to validate this against policy again, to see if the policy still matches
426 * with this new information. Note that image_policy_check_protection() will check for
427 * overlap between what's allowed in the policy and what we pass as 'found_policy' here. In
428 * the unencrypted case we thus might pass an overly unspecific mask here (i.e. unprotected
429 * OR verity OR signed), but that's fine since the earlier policy check already checked more
430 * specific which of those three cases where OK. Keep in mind that this function here only
431 * looks at specific partitions (and thus can only deduce encryption or not) but not the
432 * overall partition table (and thus cannot deduce verity or not). The earlier dissection
433 * checks already did the relevant checks that look at the whole partition table, and
434 * enforced policy there as needed. */
435 r = image_policy_check_protection(policy, i, found_flags);
436 if (r < 0)
437 return r;
438 }
439
440 return 0;
441 }
442
443 static void check_partition_flags(
444 const char *node,
445 unsigned long long pflags,
446 unsigned long long supported) {
447
448 assert(node);
449
450 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
451 pflags &= ~(supported |
452 SD_GPT_FLAG_REQUIRED_PARTITION |
453 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL |
454 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE);
455
456 if (pflags == 0)
457 return;
458
459 /* If there are other bits set, then log about it, to make things discoverable */
460 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
461 unsigned long long bit = 1ULL << i;
462 if (!FLAGS_SET(pflags, bit))
463 continue;
464
465 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
466 }
467 }
468
469 static int dissected_image_new(const char *path, DissectedImage **ret) {
470 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
471 _cleanup_free_ char *name = NULL;
472 int r;
473
474 assert(ret);
475
476 if (path) {
477 _cleanup_free_ char *filename = NULL;
478
479 r = path_extract_filename(path, &filename);
480 if (r < 0)
481 return r;
482
483 r = raw_strip_suffixes(filename, &name);
484 if (r < 0)
485 return r;
486
487 if (!image_name_is_valid(name)) {
488 log_debug("Image name %s is not valid, ignoring.", strna(name));
489 name = mfree(name);
490 }
491 }
492
493 m = new(DissectedImage, 1);
494 if (!m)
495 return -ENOMEM;
496
497 *m = (DissectedImage) {
498 .has_init_system = -1,
499 .image_name = TAKE_PTR(name),
500 };
501
502 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
503 m->partitions[i] = DISSECTED_PARTITION_NULL;
504
505 *ret = TAKE_PTR(m);
506 return 0;
507 }
508 #endif
509
510 static void dissected_partition_done(DissectedPartition *p) {
511 assert(p);
512
513 free(p->fstype);
514 free(p->node);
515 free(p->label);
516 free(p->decrypted_fstype);
517 free(p->decrypted_node);
518 free(p->mount_options);
519 safe_close(p->mount_node_fd);
520 safe_close(p->fsmount_fd);
521
522 *p = DISSECTED_PARTITION_NULL;
523 }
524
525 #if HAVE_BLKID
526 static int make_partition_devname(
527 const char *whole_devname,
528 uint64_t diskseq,
529 int nr,
530 DissectImageFlags flags,
531 char **ret) {
532
533 _cleanup_free_ char *s = NULL;
534 int r;
535
536 assert(whole_devname);
537 assert(nr != 0); /* zero is not a valid partition nr */
538 assert(ret);
539
540 if (!FLAGS_SET(flags, DISSECT_IMAGE_DISKSEQ_DEVNODE) || diskseq == 0) {
541
542 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition
543 * device name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole
544 * block device node name ends in a digit, then suffix a 'p', followed by the partition
545 * number. Otherwise, just suffix the partition number without any 'p'. */
546
547 if (nr < 0) { /* whole disk? */
548 s = strdup(whole_devname);
549 if (!s)
550 return -ENOMEM;
551 } else {
552 size_t l = strlen(whole_devname);
553 if (l < 1) /* underflow check for the subtraction below */
554 return -EINVAL;
555
556 bool need_p = ascii_isdigit(whole_devname[l-1]); /* Last char a digit? */
557
558 if (asprintf(&s, "%s%s%i", whole_devname, need_p ? "p" : "", nr) < 0)
559 return -ENOMEM;
560 }
561 } else {
562 if (nr < 0) /* whole disk? */
563 r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64, diskseq);
564 else
565 r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64 "-part%i", diskseq, nr);
566 if (r < 0)
567 return -ENOMEM;
568 }
569
570 *ret = TAKE_PTR(s);
571 return 0;
572 }
573
574 static int open_partition(
575 const char *node,
576 bool is_partition,
577 const LoopDevice *loop) {
578
579 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
580 _cleanup_close_ int fd = -EBADF;
581 dev_t devnum;
582 int r;
583
584 assert(node);
585 assert(loop);
586
587 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
588 if (fd < 0)
589 return -errno;
590
591 /* Check if the block device is a child of (or equivalent to) the originally provided one. */
592 r = block_device_new_from_fd(fd, is_partition ? BLOCK_DEVICE_LOOKUP_WHOLE_DISK : 0, &dev);
593 if (r < 0)
594 return r;
595
596 r = sd_device_get_devnum(dev, &devnum);
597 if (r < 0)
598 return r;
599
600 if (loop->devno != devnum)
601 return -ENXIO;
602
603 /* Also check diskseq. */
604 if (loop->diskseq != 0) {
605 uint64_t diskseq;
606
607 r = fd_get_diskseq(fd, &diskseq);
608 if (r < 0)
609 return r;
610
611 if (loop->diskseq != diskseq)
612 return -ENXIO;
613 }
614
615 log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR ", diskseq=%" PRIu64 ").",
616 node, fd, DEVNUM_FORMAT_VAL(loop->devno), loop->diskseq);
617 return TAKE_FD(fd);
618 }
619
620 static int compare_arch(Architecture a, Architecture b) {
621 if (a == b)
622 return 0;
623
624 if (a == native_architecture())
625 return 1;
626
627 if (b == native_architecture())
628 return -1;
629
630 #ifdef ARCHITECTURE_SECONDARY
631 if (a == ARCHITECTURE_SECONDARY)
632 return 1;
633
634 if (b == ARCHITECTURE_SECONDARY)
635 return -1;
636 #endif
637
638 return 0;
639 }
640
641 static int dissect_image(
642 DissectedImage *m,
643 int fd,
644 const char *devname,
645 const VeritySettings *verity,
646 const MountOptions *mount_options,
647 const ImagePolicy *policy,
648 DissectImageFlags flags) {
649
650 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL;
651 sd_id128_t usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
652 bool is_gpt, is_mbr, multiple_generic = false,
653 generic_rw = false, /* initialize to appease gcc */
654 generic_growfs = false;
655 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
656 _cleanup_free_ char *generic_node = NULL;
657 sd_id128_t generic_uuid = SD_ID128_NULL;
658 const char *pttype = NULL, *sptuuid = NULL;
659 blkid_partlist pl;
660 int r, generic_nr = -1, n_partitions;
661
662 assert(m);
663 assert(fd >= 0);
664 assert(devname);
665 assert(!verity || verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
666 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
667 assert(!verity || verity->root_hash_sig || verity->root_hash_sig_size == 0);
668 assert(!verity || (verity->root_hash || !verity->root_hash_sig));
669 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
670 assert(m->sector_size > 0);
671
672 /* Probes a disk image, and returns information about what it found in *ret.
673 *
674 * Returns -ENOPKG if no suitable partition table or file system could be found.
675 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
676 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
677 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that
678 * Returns -ERFKILL if image doesn't match image policy
679 * Returns -EBADR if verity data was provided externally for an image that has a GPT partition table (i.e. is not just a naked fs)
680 * Returns -EPROTONOSUPPORT if DISSECT_IMAGE_ADD_PARTITION_DEVICES is set but the block device does not have partition logic enabled
681 * Returns -ENOMSG if we didn't find a single usable partition (and DISSECT_IMAGE_REFUSE_EMPTY is set) */
682
683 uint64_t diskseq = m->loop ? m->loop->diskseq : 0;
684
685 if (verity && verity->root_hash) {
686 sd_id128_t fsuuid, vuuid;
687
688 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
689 * first 128-bit of the root hash. And we use the verity partition that has a UUID that match
690 * the final 128-bit. */
691
692 if (verity->root_hash_size < sizeof(sd_id128_t))
693 return -EINVAL;
694
695 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
696 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
697
698 if (sd_id128_is_null(fsuuid))
699 return -EINVAL;
700 if (sd_id128_is_null(vuuid))
701 return -EINVAL;
702
703 /* If the verity data declares it's for the /usr partition, then search for that, in all
704 * other cases assume it's for the root partition. */
705 if (verity->designator == PARTITION_USR) {
706 usr_uuid = fsuuid;
707 usr_verity_uuid = vuuid;
708 } else {
709 root_uuid = fsuuid;
710 root_verity_uuid = vuuid;
711 }
712 }
713
714 b = blkid_new_probe();
715 if (!b)
716 return -ENOMEM;
717
718 errno = 0;
719 r = blkid_probe_set_device(b, fd, 0, 0);
720 if (r != 0)
721 return errno_or_else(ENOMEM);
722
723 errno = 0;
724 r = blkid_probe_set_sectorsize(b, m->sector_size);
725 if (r != 0)
726 return errno_or_else(EIO);
727
728 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
729 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
730 blkid_probe_enable_superblocks(b, 1);
731 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE|BLKID_SUBLKS_UUID);
732 }
733
734 blkid_probe_enable_partitions(b, 1);
735 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
736
737 errno = 0;
738 r = blkid_do_safeprobe(b);
739 if (r == _BLKID_SAFEPROBE_ERROR)
740 return errno_or_else(EIO);
741 if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
742 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
743
744 assert(r == _BLKID_SAFEPROBE_FOUND);
745
746 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
747 (flags & DISSECT_IMAGE_GENERIC_ROOT)) ||
748 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
749 const char *usage = NULL;
750
751 /* If flags permit this, also allow using non-partitioned single-filesystem images */
752
753 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
754 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
755 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
756 const char *fstype = NULL, *options = NULL, *suuid = NULL;
757 _cleanup_close_ int mount_node_fd = -EBADF;
758 sd_id128_t uuid = SD_ID128_NULL;
759 PartitionPolicyFlags found_flags;
760 bool encrypted;
761
762 /* OK, we have found a file system, that's our root partition then. */
763
764 r = image_policy_may_use(policy, PARTITION_ROOT);
765 if (r < 0)
766 return r;
767 if (r == 0) /* policy says ignore this, so we ignore it */
768 return -ENOPKG;
769
770 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
771 (void) blkid_probe_lookup_value(b, "UUID", &suuid, NULL);
772
773 encrypted = streq_ptr(fstype, "crypto_LUKS");
774
775 if (verity_settings_data_covers(verity, PARTITION_ROOT))
776 found_flags = verity->root_hash_sig ? PARTITION_POLICY_SIGNED : PARTITION_POLICY_VERITY;
777 else
778 found_flags = encrypted ? PARTITION_POLICY_ENCRYPTED : PARTITION_POLICY_UNPROTECTED;
779
780 r = image_policy_check_protection(policy, PARTITION_ROOT, found_flags);
781 if (r < 0)
782 return r;
783
784 r = image_policy_check_partition_flags(policy, PARTITION_ROOT, 0); /* we have no gpt partition flags, hence check against all bits off */
785 if (r < 0)
786 return r;
787
788 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
789 mount_node_fd = open_partition(devname, /* is_partition = */ false, m->loop);
790 if (mount_node_fd < 0)
791 return mount_node_fd;
792 }
793
794 if (fstype) {
795 t = strdup(fstype);
796 if (!t)
797 return -ENOMEM;
798 }
799
800 if (suuid) {
801 /* blkid will return FAT's serial number as UUID, hence it is quite possible
802 * that parsing this will fail. We'll ignore the ID, since it's just too
803 * short to be useful as true identifier. */
804 r = sd_id128_from_string(suuid, &uuid);
805 if (r < 0)
806 log_debug_errno(r, "Failed to parse file system UUID '%s', ignoring: %m", suuid);
807 }
808
809 r = make_partition_devname(devname, diskseq, -1, flags, &n);
810 if (r < 0)
811 return r;
812
813 m->single_file_system = true;
814 m->encrypted = encrypted;
815
816 m->has_verity = verity && verity->data_path;
817 m->verity_ready = verity_settings_data_covers(verity, PARTITION_ROOT);
818
819 m->has_verity_sig = false; /* signature not embedded, must be specified */
820 m->verity_sig_ready = m->verity_ready && verity->root_hash_sig;
821
822 m->image_uuid = uuid;
823
824 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
825 if (options) {
826 o = strdup(options);
827 if (!o)
828 return -ENOMEM;
829 }
830
831 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
832 .found = true,
833 .rw = !m->verity_ready && !fstype_is_ro(fstype),
834 .partno = -1,
835 .architecture = _ARCHITECTURE_INVALID,
836 .fstype = TAKE_PTR(t),
837 .node = TAKE_PTR(n),
838 .mount_options = TAKE_PTR(o),
839 .mount_node_fd = TAKE_FD(mount_node_fd),
840 .offset = 0,
841 .size = UINT64_MAX,
842 .fsmount_fd = -EBADF,
843 };
844
845 return 0;
846 }
847 }
848
849 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
850 if (!pttype)
851 return -ENOPKG;
852
853 is_gpt = streq_ptr(pttype, "gpt");
854 is_mbr = streq_ptr(pttype, "dos");
855
856 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
857 return -ENOPKG;
858
859 /* We support external verity data partitions only if the image has no partition table */
860 if (verity && verity->data_path)
861 return -EBADR;
862
863 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
864 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
865 * do partition scanning. */
866 r = blockdev_partscan_enabled(fd);
867 if (r < 0)
868 return r;
869 if (r == 0)
870 return -EPROTONOSUPPORT;
871 }
872
873 (void) blkid_probe_lookup_value(b, "PTUUID", &sptuuid, NULL);
874 if (sptuuid) {
875 r = sd_id128_from_string(sptuuid, &m->image_uuid);
876 if (r < 0)
877 log_debug_errno(r, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid);
878 }
879
880 errno = 0;
881 pl = blkid_probe_get_partitions(b);
882 if (!pl)
883 return errno_or_else(ENOMEM);
884
885 errno = 0;
886 n_partitions = blkid_partlist_numof_partitions(pl);
887 if (n_partitions < 0)
888 return errno_or_else(EIO);
889
890 for (int i = 0; i < n_partitions; i++) {
891 _cleanup_free_ char *node = NULL;
892 unsigned long long pflags;
893 blkid_loff_t start, size;
894 blkid_partition pp;
895 int nr;
896
897 errno = 0;
898 pp = blkid_partlist_get_partition(pl, i);
899 if (!pp)
900 return errno_or_else(EIO);
901
902 pflags = blkid_partition_get_flags(pp);
903
904 errno = 0;
905 nr = blkid_partition_get_partno(pp);
906 if (nr < 0)
907 return errno_or_else(EIO);
908
909 errno = 0;
910 start = blkid_partition_get_start(pp);
911 if (start < 0)
912 return errno_or_else(EIO);
913
914 assert((uint64_t) start < UINT64_MAX/512);
915
916 errno = 0;
917 size = blkid_partition_get_size(pp);
918 if (size < 0)
919 return errno_or_else(EIO);
920
921 assert((uint64_t) size < UINT64_MAX/512);
922
923 /* While probing we need the non-diskseq device node name to access the thing, hence mask off
924 * DISSECT_IMAGE_DISKSEQ_DEVNODE. */
925 r = make_partition_devname(devname, diskseq, nr, flags & ~DISSECT_IMAGE_DISKSEQ_DEVNODE, &node);
926 if (r < 0)
927 return r;
928
929 /* So here's the thing: after the main ("whole") block device popped up it might take a while
930 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
931 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
932 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
933 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
934 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
935 * also good as the outcome is the same: the partition block device exists, and we can use
936 * it.
937 *
938 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
939 * partition already existent. */
940
941 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
942 r = block_device_add_partition(fd, node, nr, (uint64_t) start * 512, (uint64_t) size * 512);
943 if (r < 0) {
944 if (r != -EBUSY)
945 return log_debug_errno(r, "BLKPG_ADD_PARTITION failed: %m");
946
947 log_debug_errno(r, "Kernel was quicker than us in adding partition %i.", nr);
948 } else
949 log_debug("We were quicker than kernel in adding partition %i.", nr);
950 }
951
952 if (is_gpt) {
953 const char *fstype = NULL, *label;
954 sd_id128_t type_id, id;
955 GptPartitionType type;
956 bool rw = true, growfs = false;
957
958 r = blkid_partition_get_uuid_id128(pp, &id);
959 if (r < 0) {
960 log_debug_errno(r, "Failed to read partition UUID, ignoring: %m");
961 continue;
962 }
963
964 r = blkid_partition_get_type_id128(pp, &type_id);
965 if (r < 0) {
966 log_debug_errno(r, "Failed to read partition type UUID, ignoring: %m");
967 continue;
968 }
969
970 type = gpt_partition_type_from_uuid(type_id);
971
972 label = blkid_partition_get_name(pp); /* libblkid returns NULL here if empty */
973
974 if (IN_SET(type.designator,
975 PARTITION_HOME,
976 PARTITION_SRV,
977 PARTITION_XBOOTLDR,
978 PARTITION_TMP)) {
979
980 check_partition_flags(node, pflags,
981 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
982
983 if (pflags & SD_GPT_FLAG_NO_AUTO)
984 continue;
985
986 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
987 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
988
989 } else if (type.designator == PARTITION_ESP) {
990
991 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
992 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
993 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
994 * Partitions"). */
995
996 if (pflags & SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
997 continue;
998
999 fstype = "vfat";
1000
1001 } else if (type.designator == PARTITION_ROOT) {
1002
1003 check_partition_flags(node, pflags,
1004 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1005
1006 if (pflags & SD_GPT_FLAG_NO_AUTO)
1007 continue;
1008
1009 /* If a root ID is specified, ignore everything but the root id */
1010 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
1011 continue;
1012
1013 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1014 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1015
1016 } else if (type.designator == PARTITION_ROOT_VERITY) {
1017
1018 check_partition_flags(node, pflags,
1019 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1020
1021 if (pflags & SD_GPT_FLAG_NO_AUTO)
1022 continue;
1023
1024 m->has_verity = true;
1025
1026 /* If no verity configuration is specified, then don't do verity */
1027 if (!verity)
1028 continue;
1029 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1030 continue;
1031
1032 /* If root hash is specified, then ignore everything but the root id */
1033 if (!sd_id128_is_null(root_verity_uuid) && !sd_id128_equal(root_verity_uuid, id))
1034 continue;
1035
1036 fstype = "DM_verity_hash";
1037 rw = false;
1038
1039 } else if (type.designator == PARTITION_ROOT_VERITY_SIG) {
1040
1041 check_partition_flags(node, pflags,
1042 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1043
1044 if (pflags & SD_GPT_FLAG_NO_AUTO)
1045 continue;
1046
1047 m->has_verity_sig = true;
1048
1049 if (!verity)
1050 continue;
1051 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1052 continue;
1053
1054 fstype = "verity_hash_signature";
1055 rw = false;
1056
1057 } else if (type.designator == PARTITION_USR) {
1058
1059 check_partition_flags(node, pflags,
1060 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1061
1062 if (pflags & SD_GPT_FLAG_NO_AUTO)
1063 continue;
1064
1065 /* If a usr ID is specified, ignore everything but the usr id */
1066 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1067 continue;
1068
1069 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1070 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1071
1072 } else if (type.designator == PARTITION_USR_VERITY) {
1073
1074 check_partition_flags(node, pflags,
1075 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1076
1077 if (pflags & SD_GPT_FLAG_NO_AUTO)
1078 continue;
1079
1080 m->has_verity = true;
1081
1082 if (!verity)
1083 continue;
1084 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1085 continue;
1086
1087 /* If usr hash is specified, then ignore everything but the usr id */
1088 if (!sd_id128_is_null(usr_verity_uuid) && !sd_id128_equal(usr_verity_uuid, id))
1089 continue;
1090
1091 fstype = "DM_verity_hash";
1092 rw = false;
1093
1094 } else if (type.designator == PARTITION_USR_VERITY_SIG) {
1095
1096 check_partition_flags(node, pflags,
1097 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1098
1099 if (pflags & SD_GPT_FLAG_NO_AUTO)
1100 continue;
1101
1102 m->has_verity_sig = true;
1103
1104 if (!verity)
1105 continue;
1106 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1107 continue;
1108
1109 fstype = "verity_hash_signature";
1110 rw = false;
1111
1112 } else if (type.designator == PARTITION_SWAP) {
1113
1114 check_partition_flags(node, pflags, SD_GPT_FLAG_NO_AUTO);
1115
1116 if (pflags & SD_GPT_FLAG_NO_AUTO)
1117 continue;
1118
1119 /* Note: we don't set fstype = "swap" here, because we still need to probe if
1120 * it might be encrypted (i.e. fstype "crypt_LUKS") or unencrypted
1121 * (i.e. fstype "swap"), and the only way to figure that out is via fstype
1122 * probing. */
1123
1124 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
1125 } else if (sd_id128_equal(type.uuid, SD_GPT_LINUX_GENERIC)) {
1126
1127 check_partition_flags(node, pflags,
1128 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1129
1130 if (pflags & SD_GPT_FLAG_NO_AUTO)
1131 continue;
1132
1133 if (generic_node)
1134 multiple_generic = true;
1135 else {
1136 generic_nr = nr;
1137 generic_rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1138 generic_growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1139 generic_uuid = id;
1140 generic_node = TAKE_PTR(node);
1141 }
1142
1143 } else if (type.designator == PARTITION_VAR) {
1144
1145 check_partition_flags(node, pflags,
1146 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1147
1148 if (pflags & SD_GPT_FLAG_NO_AUTO)
1149 continue;
1150
1151 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
1152 sd_id128_t var_uuid;
1153
1154 /* For /var we insist that the uuid of the partition matches the
1155 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1156 * ID. Why? Unlike the other partitions /var is inherently
1157 * installation specific, hence we need to be careful not to mount it
1158 * in the wrong installation. By hashing the partition UUID from
1159 * /etc/machine-id we can securely bind the partition to the
1160 * installation. */
1161
1162 r = sd_id128_get_machine_app_specific(SD_GPT_VAR, &var_uuid);
1163 if (r < 0)
1164 return r;
1165
1166 if (!sd_id128_equal(var_uuid, id)) {
1167 log_debug("Found a /var/ partition, but its UUID didn't match our expectations "
1168 "(found: " SD_ID128_UUID_FORMAT_STR ", expected: " SD_ID128_UUID_FORMAT_STR "), ignoring.",
1169 SD_ID128_FORMAT_VAL(id), SD_ID128_FORMAT_VAL(var_uuid));
1170 continue;
1171 }
1172 }
1173
1174 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1175 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1176 }
1177
1178 if (type.designator != _PARTITION_DESIGNATOR_INVALID) {
1179 _cleanup_free_ char *t = NULL, *o = NULL, *l = NULL, *n = NULL;
1180 _cleanup_close_ int mount_node_fd = -EBADF;
1181 const char *options = NULL;
1182
1183 r = image_policy_may_use(policy, type.designator);
1184 if (r < 0)
1185 return r;
1186 if (r == 0) {
1187 /* Policy says: ignore; Remember this fact, so that we later can distinguish between "found but ignored" and "not found at all" */
1188
1189 if (!m->partitions[type.designator].found)
1190 m->partitions[type.designator].ignored = true;
1191
1192 continue;
1193 }
1194
1195 if (m->partitions[type.designator].found) {
1196 int c;
1197
1198 /* For most partition types the first one we see wins. Except for the
1199 * rootfs and /usr, where we do a version compare of the label, and
1200 * let the newest version win. This permits a simple A/B versioning
1201 * scheme in OS images. */
1202
1203 c = compare_arch(type.arch, m->partitions[type.designator].architecture);
1204 if (c < 0) /* the arch we already found is better than the one we found now */
1205 continue;
1206 if (c == 0 && /* same arch? then go by version in label */
1207 (!partition_designator_is_versioned(type.designator) ||
1208 strverscmp_improved(label, m->partitions[type.designator].label) <= 0))
1209 continue;
1210
1211 dissected_partition_done(m->partitions + type.designator);
1212 }
1213
1214 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES) &&
1215 type.designator != PARTITION_SWAP) {
1216 mount_node_fd = open_partition(node, /* is_partition = */ true, m->loop);
1217 if (mount_node_fd < 0)
1218 return mount_node_fd;
1219 }
1220
1221 r = make_partition_devname(devname, diskseq, nr, flags, &n);
1222 if (r < 0)
1223 return r;
1224
1225 if (fstype) {
1226 t = strdup(fstype);
1227 if (!t)
1228 return -ENOMEM;
1229 }
1230
1231 if (label) {
1232 l = strdup(label);
1233 if (!l)
1234 return -ENOMEM;
1235 }
1236
1237 options = mount_options_from_designator(mount_options, type.designator);
1238 if (options) {
1239 o = strdup(options);
1240 if (!o)
1241 return -ENOMEM;
1242 }
1243
1244 m->partitions[type.designator] = (DissectedPartition) {
1245 .found = true,
1246 .partno = nr,
1247 .rw = rw,
1248 .growfs = growfs,
1249 .architecture = type.arch,
1250 .node = TAKE_PTR(n),
1251 .fstype = TAKE_PTR(t),
1252 .label = TAKE_PTR(l),
1253 .uuid = id,
1254 .mount_options = TAKE_PTR(o),
1255 .mount_node_fd = TAKE_FD(mount_node_fd),
1256 .offset = (uint64_t) start * 512,
1257 .size = (uint64_t) size * 512,
1258 .gpt_flags = pflags,
1259 .fsmount_fd = -EBADF,
1260 };
1261 }
1262
1263 } else if (is_mbr) {
1264
1265 switch (blkid_partition_get_type(pp)) {
1266
1267 case 0x83: /* Linux partition */
1268
1269 if (pflags != 0x80) /* Bootable flag */
1270 continue;
1271
1272 if (generic_node)
1273 multiple_generic = true;
1274 else {
1275 generic_nr = nr;
1276 generic_rw = true;
1277 generic_growfs = false;
1278 generic_node = TAKE_PTR(node);
1279 }
1280
1281 break;
1282
1283 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1284 _cleanup_close_ int mount_node_fd = -EBADF;
1285 _cleanup_free_ char *o = NULL, *n = NULL;
1286 sd_id128_t id = SD_ID128_NULL;
1287 const char *options = NULL;
1288
1289 r = image_policy_may_use(policy, PARTITION_XBOOTLDR);
1290 if (r < 0)
1291 return r;
1292 if (r == 0) { /* policy says: ignore */
1293 if (!m->partitions[PARTITION_XBOOTLDR].found)
1294 m->partitions[PARTITION_XBOOTLDR].ignored = true;
1295
1296 continue;
1297 }
1298
1299 /* First one wins */
1300 if (m->partitions[PARTITION_XBOOTLDR].found)
1301 continue;
1302
1303 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
1304 mount_node_fd = open_partition(node, /* is_partition = */ true, m->loop);
1305 if (mount_node_fd < 0)
1306 return mount_node_fd;
1307 }
1308
1309 (void) blkid_partition_get_uuid_id128(pp, &id);
1310
1311 r = make_partition_devname(devname, diskseq, nr, flags, &n);
1312 if (r < 0)
1313 return r;
1314
1315 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
1316 if (options) {
1317 o = strdup(options);
1318 if (!o)
1319 return -ENOMEM;
1320 }
1321
1322 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1323 .found = true,
1324 .partno = nr,
1325 .rw = true,
1326 .growfs = false,
1327 .architecture = _ARCHITECTURE_INVALID,
1328 .node = TAKE_PTR(n),
1329 .uuid = id,
1330 .mount_options = TAKE_PTR(o),
1331 .mount_node_fd = TAKE_FD(mount_node_fd),
1332 .offset = (uint64_t) start * 512,
1333 .size = (uint64_t) size * 512,
1334 .fsmount_fd = -EBADF,
1335 };
1336
1337 break;
1338 }}
1339 }
1340 }
1341
1342 if (!m->partitions[PARTITION_ROOT].found &&
1343 (m->partitions[PARTITION_ROOT_VERITY].found ||
1344 m->partitions[PARTITION_ROOT_VERITY_SIG].found))
1345 return -EADDRNOTAVAIL; /* Verity found but no matching rootfs? Something is off, refuse. */
1346
1347 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1348 if (m->partitions[PARTITION_ROOT_VERITY_SIG].found && !m->partitions[PARTITION_ROOT_VERITY].found)
1349 return -EADDRNOTAVAIL;
1350
1351 if (!m->partitions[PARTITION_USR].found &&
1352 (m->partitions[PARTITION_USR_VERITY].found ||
1353 m->partitions[PARTITION_USR_VERITY_SIG].found))
1354 return -EADDRNOTAVAIL; /* as above */
1355
1356 /* as above */
1357 if (m->partitions[PARTITION_USR_VERITY_SIG].found && !m->partitions[PARTITION_USR_VERITY].found)
1358 return -EADDRNOTAVAIL;
1359
1360 /* If root and /usr are combined then insist that the architecture matches */
1361 if (m->partitions[PARTITION_ROOT].found &&
1362 m->partitions[PARTITION_USR].found &&
1363 (m->partitions[PARTITION_ROOT].architecture >= 0 &&
1364 m->partitions[PARTITION_USR].architecture >= 0 &&
1365 m->partitions[PARTITION_ROOT].architecture != m->partitions[PARTITION_USR].architecture))
1366 return -EADDRNOTAVAIL;
1367
1368 if (!m->partitions[PARTITION_ROOT].found &&
1369 !m->partitions[PARTITION_USR].found &&
1370 (flags & DISSECT_IMAGE_GENERIC_ROOT) &&
1371 (!verity || !verity->root_hash || verity->designator != PARTITION_USR)) {
1372
1373 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1374 * that. If the root hash was set however, then we won't fall back to a generic node, because
1375 * the root hash decides. */
1376
1377 /* If we didn't find a properly marked root partition, but we did find a single suitable
1378 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1379 if (multiple_generic)
1380 return -ENOTUNIQ;
1381
1382 /* If we didn't find a generic node, then we can't fix this up either */
1383 if (generic_node) {
1384 r = image_policy_may_use(policy, PARTITION_ROOT);
1385 if (r < 0)
1386 return r;
1387 if (r == 0)
1388 /* Policy says: ignore; remember that we did */
1389 m->partitions[PARTITION_ROOT].ignored = true;
1390 else {
1391 _cleanup_close_ int mount_node_fd = -EBADF;
1392 _cleanup_free_ char *o = NULL, *n = NULL;
1393 const char *options;
1394
1395 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
1396 mount_node_fd = open_partition(generic_node, /* is_partition = */ true, m->loop);
1397 if (mount_node_fd < 0)
1398 return mount_node_fd;
1399 }
1400
1401 r = make_partition_devname(devname, diskseq, generic_nr, flags, &n);
1402 if (r < 0)
1403 return r;
1404
1405 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
1406 if (options) {
1407 o = strdup(options);
1408 if (!o)
1409 return -ENOMEM;
1410 }
1411
1412 assert(generic_nr >= 0);
1413 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1414 .found = true,
1415 .rw = generic_rw,
1416 .growfs = generic_growfs,
1417 .partno = generic_nr,
1418 .architecture = _ARCHITECTURE_INVALID,
1419 .node = TAKE_PTR(n),
1420 .uuid = generic_uuid,
1421 .mount_options = TAKE_PTR(o),
1422 .mount_node_fd = TAKE_FD(mount_node_fd),
1423 .offset = UINT64_MAX,
1424 .size = UINT64_MAX,
1425 .fsmount_fd = -EBADF,
1426 };
1427 }
1428 }
1429 }
1430
1431 /* 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 */
1432 if (FLAGS_SET(flags, DISSECT_IMAGE_REQUIRE_ROOT) &&
1433 !(m->partitions[PARTITION_ROOT].found || (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1434 return -ENXIO;
1435
1436 if (m->partitions[PARTITION_ROOT_VERITY].found) {
1437 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1438 if (m->partitions[PARTITION_USR_VERITY].found)
1439 return -ENOTUNIQ;
1440
1441 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1442 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1443 if (m->partitions[PARTITION_USR].found)
1444 return -EADDRNOTAVAIL;
1445 }
1446
1447 if (verity) {
1448 /* If a verity designator is specified, then insist that the matching partition exists */
1449 if (verity->designator >= 0 && !m->partitions[verity->designator].found)
1450 return -EADDRNOTAVAIL;
1451
1452 bool have_verity_sig_partition;
1453 if (verity->designator >= 0)
1454 have_verity_sig_partition = m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR_VERITY_SIG : PARTITION_ROOT_VERITY_SIG].found;
1455 else
1456 have_verity_sig_partition = m->partitions[PARTITION_USR_VERITY_SIG].found || m->partitions[PARTITION_ROOT_VERITY_SIG].found;
1457
1458 if (verity->root_hash) {
1459 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1460 * Verity, set things up for it */
1461
1462 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1463 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1464 return -EADDRNOTAVAIL;
1465
1466 /* If we found a verity setup, then the root partition is necessarily read-only. */
1467 m->partitions[PARTITION_ROOT].rw = false;
1468 m->verity_ready = true;
1469
1470 } else {
1471 assert(verity->designator == PARTITION_USR);
1472
1473 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1474 return -EADDRNOTAVAIL;
1475
1476 m->partitions[PARTITION_USR].rw = false;
1477 m->verity_ready = true;
1478 }
1479
1480 if (m->verity_ready)
1481 m->verity_sig_ready = verity->root_hash_sig || have_verity_sig_partition;
1482
1483 } else if (have_verity_sig_partition) {
1484
1485 /* If we found an embedded signature partition, we are ready, too. */
1486
1487 m->verity_ready = m->verity_sig_ready = true;
1488 if (verity->designator >= 0)
1489 m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR : PARTITION_ROOT].rw = false;
1490 else if (m->partitions[PARTITION_USR_VERITY_SIG].found)
1491 m->partitions[PARTITION_USR].rw = false;
1492 else if (m->partitions[PARTITION_ROOT_VERITY_SIG].found)
1493 m->partitions[PARTITION_ROOT].rw = false;
1494 }
1495 }
1496
1497 bool any = false;
1498
1499 /* After we discovered all partitions let's see if the verity requirements match the policy. (Note:
1500 * we don't check encryption requirements here, because we haven't probed the file system yet, hence
1501 * don't know if this is encrypted or not) */
1502 for (PartitionDesignator di = 0; di < _PARTITION_DESIGNATOR_MAX; di++) {
1503 PartitionDesignator vi, si;
1504 PartitionPolicyFlags found_flags;
1505
1506 any = any || m->partitions[di].found;
1507
1508 vi = partition_verity_of(di);
1509 si = partition_verity_sig_of(di);
1510
1511 /* Determine the verity protection level for this partition. */
1512 found_flags = m->partitions[di].found ?
1513 (vi >= 0 && m->partitions[vi].found ?
1514 (si >= 0 && m->partitions[si].found ? PARTITION_POLICY_SIGNED : PARTITION_POLICY_VERITY) :
1515 PARTITION_POLICY_ENCRYPTED|PARTITION_POLICY_UNPROTECTED) :
1516 (m->partitions[di].ignored ? PARTITION_POLICY_UNUSED : PARTITION_POLICY_ABSENT);
1517
1518 r = image_policy_check_protection(policy, di, found_flags);
1519 if (r < 0)
1520 return r;
1521
1522 if (m->partitions[di].found) {
1523 r = image_policy_check_partition_flags(policy, di, m->partitions[di].gpt_flags);
1524 if (r < 0)
1525 return r;
1526 }
1527 }
1528
1529 if (!any && !FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_EMPTY))
1530 return -ENOMSG;
1531
1532 r = dissected_image_probe_filesystems(m, fd, policy);
1533 if (r < 0)
1534 return r;
1535
1536 return 0;
1537 }
1538 #endif
1539
1540 int dissect_image_file(
1541 const char *path,
1542 const VeritySettings *verity,
1543 const MountOptions *mount_options,
1544 const ImagePolicy *image_policy,
1545 DissectImageFlags flags,
1546 DissectedImage **ret) {
1547
1548 #if HAVE_BLKID
1549 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
1550 _cleanup_close_ int fd = -EBADF;
1551 struct stat st;
1552 int r;
1553
1554 assert(path);
1555
1556 fd = open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1557 if (fd < 0)
1558 return -errno;
1559
1560 if (fstat(fd, &st) < 0)
1561 return -errno;
1562
1563 r = stat_verify_regular(&st);
1564 if (r < 0)
1565 return r;
1566
1567 r = dissected_image_new(path, &m);
1568 if (r < 0)
1569 return r;
1570
1571 m->image_size = st.st_size;
1572
1573 r = probe_sector_size(fd, &m->sector_size);
1574 if (r < 0)
1575 return r;
1576
1577 r = dissect_image(m, fd, path, verity, mount_options, image_policy, flags);
1578 if (r < 0)
1579 return r;
1580
1581 if (ret)
1582 *ret = TAKE_PTR(m);
1583 return 0;
1584 #else
1585 return -EOPNOTSUPP;
1586 #endif
1587 }
1588
1589 int dissect_log_error(int log_level, int r, const char *name, const VeritySettings *verity) {
1590 assert(log_level >= 0 && log_level <= LOG_DEBUG);
1591 assert(name);
1592
1593 switch (r) {
1594
1595 case 0 ... INT_MAX: /* success! */
1596 return r;
1597
1598 case -EOPNOTSUPP:
1599 return log_full_errno(log_level, r, "Dissecting images is not supported, compiled without blkid support.");
1600
1601 case -ENOPKG:
1602 return log_full_errno(log_level, r, "%s: Couldn't identify a suitable partition table or file system.", name);
1603
1604 case -ENOMEDIUM:
1605 return log_full_errno(log_level, r, "%s: The image does not pass os-release/extension-release validation.", name);
1606
1607 case -EADDRNOTAVAIL:
1608 return log_full_errno(log_level, r, "%s: No root partition for specified root hash found.", name);
1609
1610 case -ENOTUNIQ:
1611 return log_full_errno(log_level, r, "%s: Multiple suitable root partitions found in image.", name);
1612
1613 case -ENXIO:
1614 return log_full_errno(log_level, r, "%s: No suitable root partition found in image.", name);
1615
1616 case -EPROTONOSUPPORT:
1617 return log_full_errno(log_level, r, "Device '%s' is a loopback block device with partition scanning turned off, please turn it on.", name);
1618
1619 case -ENOTBLK:
1620 return log_full_errno(log_level, r, "%s: Image is not a block device.", name);
1621
1622 case -EBADR:
1623 return log_full_errno(log_level, r,
1624 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
1625 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
1626 name, strna(verity ? verity->data_path : NULL));
1627
1628 case -ERFKILL:
1629 return log_full_errno(log_level, r, "%s: image does not match image policy.", name);
1630
1631 case -ENOMSG:
1632 return log_full_errno(log_level, r, "%s: no suitable partitions found.", name);
1633
1634 default:
1635 return log_full_errno(log_level, r, "%s: cannot dissect image: %m", name);
1636 }
1637 }
1638
1639 int dissect_image_file_and_warn(
1640 const char *path,
1641 const VeritySettings *verity,
1642 const MountOptions *mount_options,
1643 const ImagePolicy *image_policy,
1644 DissectImageFlags flags,
1645 DissectedImage **ret) {
1646
1647 return dissect_log_error(
1648 LOG_ERR,
1649 dissect_image_file(path, verity, mount_options, image_policy, flags, ret),
1650 path,
1651 verity);
1652 }
1653
1654 DissectedImage* dissected_image_unref(DissectedImage *m) {
1655 if (!m)
1656 return NULL;
1657
1658 /* First, clear dissected partitions. */
1659 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
1660 dissected_partition_done(m->partitions + i);
1661
1662 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1663 * DecryptedImage may try to deactivate partitions. */
1664 decrypted_image_unref(m->decrypted_image);
1665
1666 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1667 * remove existing partitions on the loopback block device. */
1668 loop_device_unref(m->loop);
1669
1670 free(m->image_name);
1671 free(m->hostname);
1672 strv_free(m->machine_info);
1673 strv_free(m->os_release);
1674 strv_free(m->initrd_release);
1675 strv_free(m->confext_release);
1676 strv_free(m->sysext_release);
1677
1678 return mfree(m);
1679 }
1680
1681 static int is_loop_device(const char *path) {
1682 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
1683 struct stat st;
1684
1685 assert(path);
1686
1687 if (stat(path, &st) < 0)
1688 return -errno;
1689
1690 if (!S_ISBLK(st.st_mode))
1691 return -ENOTBLK;
1692
1693 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
1694 if (access(s, F_OK) < 0) {
1695 if (errno != ENOENT)
1696 return -errno;
1697
1698 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1699 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
1700 if (access(s, F_OK) < 0)
1701 return errno == ENOENT ? false : -errno;
1702 }
1703
1704 return true;
1705 }
1706
1707 static int run_fsck(int node_fd, const char *fstype) {
1708 int r, exit_status;
1709 pid_t pid;
1710
1711 assert(node_fd >= 0);
1712 assert(fstype);
1713
1714 r = fsck_exists_for_fstype(fstype);
1715 if (r < 0) {
1716 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1717 return 0;
1718 }
1719 if (r == 0) {
1720 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd), fstype);
1721 return 0;
1722 }
1723
1724 r = safe_fork_full(
1725 "(fsck)",
1726 NULL,
1727 &node_fd, 1, /* Leave the node fd open */
1728 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_CLOEXEC_OFF,
1729 &pid);
1730 if (r < 0)
1731 return log_debug_errno(r, "Failed to fork off fsck: %m");
1732 if (r == 0) {
1733 /* Child */
1734 execlp("fsck", "fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd), NULL);
1735 log_open();
1736 log_debug_errno(errno, "Failed to execl() fsck: %m");
1737 _exit(FSCK_OPERATIONAL_ERROR);
1738 }
1739
1740 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1741 if (exit_status < 0)
1742 return log_debug_errno(exit_status, "Failed to fork off fsck: %m");
1743
1744 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1745 log_debug("fsck failed with exit status %i.", exit_status);
1746
1747 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1748 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1749
1750 log_debug("Ignoring fsck error.");
1751 }
1752
1753 return 0;
1754 }
1755
1756 static int fs_grow(const char *node_path, int mount_fd, const char *mount_path) {
1757 _cleanup_close_ int _mount_fd = -EBADF, node_fd = -EBADF;
1758 uint64_t size, newsize;
1759 const char *id;
1760 int r;
1761
1762 assert(node_path);
1763 assert(mount_fd >= 0 || mount_path);
1764
1765 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1766 if (node_fd < 0)
1767 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
1768
1769 r = blockdev_get_device_size(node_fd, &size);
1770 if (r < 0)
1771 return log_debug_errno(r, "Failed to get block device size of %s: %m", node_path);
1772
1773 if (mount_fd < 0) {
1774 assert(mount_path);
1775
1776 _mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1777 if (_mount_fd < 0)
1778 return log_debug_errno(errno, "Failed to open mounted file system %s: %m", mount_path);
1779
1780 mount_fd = _mount_fd;
1781 } else {
1782 mount_fd = fd_reopen_condition(mount_fd, O_RDONLY|O_DIRECTORY|O_CLOEXEC, O_RDONLY|O_DIRECTORY|O_CLOEXEC, &_mount_fd);
1783 if (mount_fd < 0)
1784 return log_debug_errno(errno, "Failed to reopen mount node: %m");
1785 }
1786
1787 id = mount_path ?: node_path;
1788
1789 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", id, size);
1790 r = resize_fs(mount_fd, size, &newsize);
1791 if (r < 0)
1792 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", id, size);
1793
1794 if (newsize == size)
1795 log_debug("Successfully resized \"%s\" to %s bytes.",
1796 id, FORMAT_BYTES(newsize));
1797 else {
1798 assert(newsize < size);
1799 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
1800 id, FORMAT_BYTES(newsize), size - newsize);
1801 }
1802
1803 return 0;
1804 }
1805
1806 int partition_pick_mount_options(
1807 PartitionDesignator d,
1808 const char *fstype,
1809 bool rw,
1810 bool discard,
1811 char **ret_options,
1812 unsigned long *ret_ms_flags) {
1813
1814 _cleanup_free_ char *options = NULL;
1815
1816 assert(ret_options);
1817
1818 /* Selects a baseline of bind mount flags, that should always apply.
1819 *
1820 * Firstly, we set MS_NODEV universally on all mounts, since we don't want to allow device nodes outside of /dev/.
1821 *
1822 * On /var/tmp/ we'll also set MS_NOSUID, same as we set for /tmp/ on the host.
1823 *
1824 * On the ESP and XBOOTLDR partitions we'll also disable symlinks, and execution. These file systems
1825 * are generally untrusted (i.e. not encrypted or authenticated), and typically VFAT hence we should
1826 * be as restrictive as possible, and this shouldn't hurt, since the functionality is not available
1827 * there anyway. */
1828
1829 unsigned long flags = MS_NODEV;
1830
1831 if (!rw)
1832 flags |= MS_RDONLY;
1833
1834 switch (d) {
1835
1836 case PARTITION_ESP:
1837 case PARTITION_XBOOTLDR:
1838 flags |= MS_NOSUID|MS_NOEXEC|ms_nosymfollow_supported();
1839
1840 /* The ESP might contain a pre-boot random seed. Let's make this unaccessible to regular
1841 * userspace. ESP/XBOOTLDR is almost certainly VFAT, hence if we don't know assume it is. */
1842 if (!fstype || fstype_can_umask(fstype))
1843 if (!strextend_with_separator(&options, ",", "umask=0077"))
1844 return -ENOMEM;
1845 break;
1846
1847 case PARTITION_TMP:
1848 flags |= MS_NOSUID;
1849 break;
1850
1851 default:
1852 break;
1853 }
1854
1855 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1856 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1857 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1858 * from the upper file system still get propagated through to the underlying file system,
1859 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1860 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1861 * carry a per file system table here.
1862 *
1863 * Note that this means that we might not be able to mount corrupted file systems as read-only
1864 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1865 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1866 * mount options for loopback devices this is the right choice, since otherwise using the same
1867 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The use case of
1868 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1869 * access that actually modifies stuff work on such image files. Or to say this differently: if
1870 * people want their file systems to be fixed up they should just open them in writable mode, where
1871 * all these problems don't exist. */
1872 if (!rw && fstype && fstype_can_norecovery(fstype))
1873 if (!strextend_with_separator(&options, ",", "norecovery"))
1874 return -ENOMEM;
1875
1876 if (discard && fstype && fstype_can_discard(fstype))
1877 if (!strextend_with_separator(&options, ",", "discard"))
1878 return -ENOMEM;
1879
1880 if (!ret_ms_flags) /* Fold flags into option string if ret_flags specified as NULL */
1881 if (!strextend_with_separator(&options, ",",
1882 FLAGS_SET(flags, MS_RDONLY) ? "ro" : "rw",
1883 FLAGS_SET(flags, MS_NODEV) ? "nodev" : "dev",
1884 FLAGS_SET(flags, MS_NOSUID) ? "nosuid" : "suid",
1885 FLAGS_SET(flags, MS_NOEXEC) ? "noexec" : "exec",
1886 FLAGS_SET(flags, MS_NOSYMFOLLOW) ? "nosymfollow" : NULL))
1887 /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
1888 return -ENOMEM;
1889
1890 if (ret_ms_flags)
1891 *ret_ms_flags = flags;
1892
1893 *ret_options = TAKE_PTR(options);
1894 return 0;
1895 }
1896
1897 static bool need_user_mapping(uid_t uid_shift, uid_t uid_range) {
1898
1899 if (!uid_is_valid(uid_shift))
1900 return false;
1901
1902 return uid_shift != 0 || uid_range != UINT32_MAX;
1903 }
1904
1905 static int mount_partition(
1906 PartitionDesignator d,
1907 DissectedPartition *m,
1908 const char *where,
1909 const char *directory,
1910 uid_t uid_shift,
1911 uid_t uid_range,
1912 int userns_fd,
1913 DissectImageFlags flags) {
1914
1915 _cleanup_free_ char *chased = NULL, *options = NULL;
1916 const char *p = NULL, *node, *fstype = NULL;
1917 bool rw, discard, grow;
1918 unsigned long ms_flags;
1919 int r;
1920
1921 assert(m);
1922
1923 if (!m->found)
1924 return 0;
1925
1926 /* Check the various combinations when we can't do anything anymore */
1927 if (m->fsmount_fd < 0 && m->mount_node_fd < 0)
1928 return 0;
1929 if (m->fsmount_fd >= 0 && !where)
1930 return 0;
1931 if (!where && m->mount_node_fd < 0)
1932 return 0;
1933
1934 if (m->fsmount_fd < 0) {
1935 fstype = dissected_partition_fstype(m);
1936 if (!fstype)
1937 return -EAFNOSUPPORT;
1938
1939 /* We are looking at an encrypted partition? This either means stacked encryption, or the
1940 * caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error
1941 * for this case. */
1942 if (streq(fstype, "crypto_LUKS"))
1943 return -EUNATCH;
1944
1945 r = dissect_fstype_ok(fstype);
1946 if (r < 0)
1947 return r;
1948 if (!r)
1949 return -EIDRM; /* Recognizable error */
1950 }
1951
1952 node = m->mount_node_fd < 0 ? NULL : FORMAT_PROC_FD_PATH(m->mount_node_fd);
1953 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
1954
1955 discard = ((flags & DISSECT_IMAGE_DISCARD) ||
1956 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && (m->node && is_loop_device(m->node) > 0)));
1957
1958 grow = rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS);
1959
1960 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw && m->mount_node_fd >= 0 && m->fsmount_fd < 0) {
1961 r = run_fsck(m->mount_node_fd, fstype);
1962 if (r < 0)
1963 return r;
1964 }
1965
1966 if (where) {
1967 if (directory) {
1968 /* Automatically create missing mount points inside the image, if necessary. */
1969 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755, NULL);
1970 if (r < 0 && r != -EROFS)
1971 return r;
1972
1973 r = chase(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
1974 if (r < 0)
1975 return r;
1976
1977 p = chased;
1978 } else {
1979 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1980 * image (as the branch above does) but the host hierarchy, and the created directory might
1981 * survive our mount in the host hierarchy hence. */
1982 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1983 r = mkdir_p(where, 0755);
1984 if (r < 0)
1985 return r;
1986 }
1987
1988 p = where;
1989 }
1990 }
1991
1992 if (m->fsmount_fd < 0) {
1993 r = partition_pick_mount_options(d, fstype, rw, discard, &options, &ms_flags);
1994 if (r < 0)
1995 return r;
1996
1997 if (need_user_mapping(uid_shift, uid_range) && fstype_can_uid_gid(fstype)) {
1998 _cleanup_free_ char *uid_option = NULL;
1999
2000 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
2001 return -ENOMEM;
2002
2003 if (!strextend_with_separator(&options, ",", uid_option))
2004 return -ENOMEM;
2005
2006 userns_fd = -EBADF; /* Not needed */
2007 }
2008
2009 if (!isempty(m->mount_options))
2010 if (!strextend_with_separator(&options, ",", m->mount_options))
2011 return -ENOMEM;
2012 }
2013
2014 if (p) {
2015 if (m->fsmount_fd >= 0) {
2016 /* Case #1: Attach existing fsmount fd to the file system */
2017
2018 r = mount_exchange_graceful(
2019 m->fsmount_fd,
2020 p,
2021 FLAGS_SET(flags, DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE));
2022 if (r < 0)
2023 return log_debug_errno(r, "Failed to mount image on '%s': %m", p);
2024
2025 } else {
2026 assert(node);
2027
2028 /* Case #2: Mount directly into place */
2029 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, ms_flags, options);
2030 if (r < 0)
2031 return r;
2032
2033 if (grow)
2034 (void) fs_grow(node, -EBADF, p);
2035
2036 if (userns_fd >= 0) {
2037 r = remount_idmap_fd(STRV_MAKE(p), userns_fd);
2038 if (r < 0)
2039 return r;
2040 }
2041 }
2042 } else {
2043 assert(node);
2044
2045 /* Case #3: Create fsmount fd */
2046
2047 m->fsmount_fd = make_fsmount(LOG_DEBUG, node, fstype, ms_flags, options, userns_fd);
2048 if (m->fsmount_fd < 0)
2049 return m->fsmount_fd;
2050
2051 if (grow)
2052 (void) fs_grow(node, m->fsmount_fd, NULL);
2053 }
2054
2055 return 1;
2056 }
2057
2058 static int mount_root_tmpfs(const char *where, uid_t uid_shift, uid_t uid_range, DissectImageFlags flags) {
2059 _cleanup_free_ char *options = NULL;
2060 int r;
2061
2062 assert(where);
2063
2064 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
2065
2066 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
2067 r = mkdir_p(where, 0755);
2068 if (r < 0)
2069 return r;
2070 }
2071
2072 if (need_user_mapping(uid_shift, uid_range)) {
2073 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
2074 return -ENOMEM;
2075 }
2076
2077 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
2078 if (r < 0)
2079 return r;
2080
2081 return 1;
2082 }
2083
2084 static int mount_point_is_available(const char *where, const char *path, bool missing_ok) {
2085 _cleanup_free_ char *p = NULL;
2086 int r;
2087
2088 /* Check whether <path> is suitable as a mountpoint, i.e. is an empty directory
2089 * or does not exist at all (when missing_ok). */
2090
2091 r = chase(path, where, CHASE_PREFIX_ROOT, &p, NULL);
2092 if (r == -ENOENT)
2093 return missing_ok;
2094 if (r < 0)
2095 return log_debug_errno(r, "Failed to chase \"%s\": %m", path);
2096
2097 r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
2098 if (r == -ENOTDIR)
2099 return false;
2100 if (r < 0)
2101 return log_debug_errno(r, "Failed to check directory \"%s\": %m", p);
2102 return r > 0;
2103 }
2104
2105 int dissected_image_mount(
2106 DissectedImage *m,
2107 const char *where,
2108 uid_t uid_shift,
2109 uid_t uid_range,
2110 int userns_fd,
2111 DissectImageFlags flags) {
2112
2113 _cleanup_close_ int my_userns_fd = -EBADF;
2114 int r;
2115
2116 assert(m);
2117
2118 /* If 'where' is NULL then we'll use the new mount API to create fsmount() fds for the mounts and
2119 * store them in DissectedPartition.fsmount_fd.
2120 *
2121 * If 'where' is not NULL then we'll either mount the partitions to the right places ourselves,
2122 * or use DissectedPartition.fsmount_fd and bind it to the right places.
2123 *
2124 * This allows splitting the setting up up the superblocks and the binding to file systems paths into
2125 * two distinct and differently privileged components: one that gets the fsmount fds, and the other
2126 * that then applies them.
2127 *
2128 * Returns:
2129 *
2130 * -ENXIO → No root partition found
2131 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
2132 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
2133 * -EUCLEAN → fsck for file system failed
2134 * -EBUSY → File system already mounted/used elsewhere (kernel)
2135 * -EAFNOSUPPORT → File system type not supported or not known
2136 * -EIDRM → File system is not among allowlisted "common" file systems
2137 */
2138
2139 if (!where && (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0)
2140 return -EOPNOTSUPP; /* for now, not supported */
2141
2142 if (!(m->partitions[PARTITION_ROOT].found ||
2143 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
2144 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
2145
2146 if (userns_fd < 0 && need_user_mapping(uid_shift, uid_range) && FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED)) {
2147
2148 my_userns_fd = make_userns(uid_shift, uid_range, UID_INVALID, UID_INVALID, REMOUNT_IDMAPPING_HOST_ROOT);
2149 if (my_userns_fd < 0)
2150 return my_userns_fd;
2151
2152 userns_fd = my_userns_fd;
2153 }
2154
2155 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
2156
2157 /* First mount the root fs. If there's none we use a tmpfs. */
2158 if (m->partitions[PARTITION_ROOT].found) {
2159 r = mount_partition(PARTITION_ROOT, m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, userns_fd, flags);
2160 if (r < 0)
2161 return r;
2162
2163 } else if (where) {
2164 r = mount_root_tmpfs(where, uid_shift, uid_range, flags);
2165 if (r < 0)
2166 return r;
2167 }
2168
2169 /* For us mounting root always means mounting /usr as well */
2170 r = mount_partition(PARTITION_USR, m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, userns_fd, flags);
2171 if (r < 0)
2172 return r;
2173 }
2174
2175 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0 &&
2176 (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
2177 /* If either one of the validation flags are set, ensure that the image qualifies as
2178 * one or the other (or both). */
2179 bool ok = false;
2180
2181 assert(where);
2182
2183 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
2184 r = path_is_os_tree(where);
2185 if (r < 0)
2186 return r;
2187 if (r > 0)
2188 ok = true;
2189 }
2190 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT) && m->image_name) {
2191 r = extension_has_forbidden_content(where);
2192 if (r < 0)
2193 return r;
2194 if (r == 0) {
2195 r = path_is_extension_tree(IMAGE_SYSEXT, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
2196 if (r == 0)
2197 r = path_is_extension_tree(IMAGE_CONFEXT, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
2198 if (r < 0)
2199 return r;
2200 if (r > 0)
2201 ok = true;
2202 }
2203 }
2204
2205 if (!ok)
2206 return -ENOMEDIUM;
2207 }
2208
2209 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2210 return 0;
2211
2212 r = mount_partition(PARTITION_HOME, m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, userns_fd, flags);
2213 if (r < 0)
2214 return r;
2215
2216 r = mount_partition(PARTITION_SRV, m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, userns_fd, flags);
2217 if (r < 0)
2218 return r;
2219
2220 r = mount_partition(PARTITION_VAR, m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, userns_fd, flags);
2221 if (r < 0)
2222 return r;
2223
2224 r = mount_partition(PARTITION_TMP, m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, userns_fd, flags);
2225 if (r < 0)
2226 return r;
2227
2228 int slash_boot_is_available = 0;
2229 if (where) {
2230 r = slash_boot_is_available = mount_point_is_available(where, "/boot", /* missing_ok = */ true);
2231 if (r < 0)
2232 return r;
2233 }
2234 if (!where || slash_boot_is_available) {
2235 r = mount_partition(PARTITION_XBOOTLDR, m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, userns_fd, flags);
2236 if (r < 0)
2237 return r;
2238 slash_boot_is_available = !r;
2239 }
2240
2241 if (m->partitions[PARTITION_ESP].found) {
2242 const char *esp_path = NULL;
2243
2244 if (where) {
2245 /* Mount the ESP to /boot/ if it exists and is empty and we didn't already mount the
2246 * XBOOTLDR partition into it. Otherwise, use /efi instead, but only if it exists
2247 * and is empty. */
2248
2249 if (slash_boot_is_available) {
2250 r = mount_point_is_available(where, "/boot", /* missing_ok = */ false);
2251 if (r < 0)
2252 return r;
2253 if (r > 0)
2254 esp_path = "/boot";
2255 }
2256
2257 if (!esp_path) {
2258 r = mount_point_is_available(where, "/efi", /* missing_ok = */ true);
2259 if (r < 0)
2260 return r;
2261 if (r > 0)
2262 esp_path = "/efi";
2263 }
2264 }
2265
2266 /* OK, let's mount the ESP now (possibly creating the dir if missing) */
2267 r = mount_partition(PARTITION_ESP, m->partitions + PARTITION_ESP, where, esp_path, uid_shift, uid_range, userns_fd, flags);
2268 if (r < 0)
2269 return r;
2270 }
2271
2272 return 0;
2273 }
2274
2275 int dissected_image_mount_and_warn(
2276 DissectedImage *m,
2277 const char *where,
2278 uid_t uid_shift,
2279 uid_t uid_range,
2280 int userns_fd,
2281 DissectImageFlags flags) {
2282
2283 int r;
2284
2285 assert(m);
2286
2287 r = dissected_image_mount(m, where, uid_shift, uid_range, userns_fd, flags);
2288 if (r == -ENXIO)
2289 return log_error_errno(r, "Not root file system found in image.");
2290 if (r == -EMEDIUMTYPE)
2291 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
2292 if (r == -EUNATCH)
2293 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
2294 if (r == -EUCLEAN)
2295 return log_error_errno(r, "File system check on image failed.");
2296 if (r == -EBUSY)
2297 return log_error_errno(r, "File system already mounted elsewhere.");
2298 if (r == -EAFNOSUPPORT)
2299 return log_error_errno(r, "File system type not supported or not known.");
2300 if (r == -EIDRM)
2301 return log_error_errno(r, "File system is too uncommon, refused.");
2302 if (r < 0)
2303 return log_error_errno(r, "Failed to mount image: %m");
2304
2305 return r;
2306 }
2307
2308 #if HAVE_LIBCRYPTSETUP
2309 struct DecryptedPartition {
2310 struct crypt_device *device;
2311 char *name;
2312 bool relinquished;
2313 };
2314 #endif
2315
2316 typedef struct DecryptedPartition DecryptedPartition;
2317
2318 struct DecryptedImage {
2319 unsigned n_ref;
2320 DecryptedPartition *decrypted;
2321 size_t n_decrypted;
2322 };
2323
2324 static DecryptedImage* decrypted_image_free(DecryptedImage *d) {
2325 #if HAVE_LIBCRYPTSETUP
2326 int r;
2327
2328 if (!d)
2329 return NULL;
2330
2331 for (size_t i = 0; i < d->n_decrypted; i++) {
2332 DecryptedPartition *p = d->decrypted + i;
2333
2334 if (p->device && p->name && !p->relinquished) {
2335 _cleanup_free_ char *node = NULL;
2336
2337 node = path_join("/dev/mapper", p->name);
2338 if (node) {
2339 r = btrfs_forget_device(node);
2340 if (r < 0 && r != -ENOENT)
2341 log_debug_errno(r, "Failed to forget btrfs device %s, ignoring: %m", node);
2342 } else
2343 log_oom_debug();
2344
2345 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
2346 r = sym_crypt_deactivate_by_name(p->device, p->name, CRYPT_DEACTIVATE_DEFERRED);
2347 if (r < 0)
2348 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
2349 }
2350
2351 if (p->device)
2352 sym_crypt_free(p->device);
2353 free(p->name);
2354 }
2355
2356 free(d->decrypted);
2357 free(d);
2358 #endif
2359 return NULL;
2360 }
2361
2362 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage, decrypted_image, decrypted_image_free);
2363
2364 #if HAVE_LIBCRYPTSETUP
2365 static int decrypted_image_new(DecryptedImage **ret) {
2366 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2367
2368 assert(ret);
2369
2370 d = new(DecryptedImage, 1);
2371 if (!d)
2372 return -ENOMEM;
2373
2374 *d = (DecryptedImage) {
2375 .n_ref = 1,
2376 };
2377
2378 *ret = TAKE_PTR(d);
2379 return 0;
2380 }
2381
2382 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
2383 _cleanup_free_ char *name = NULL, *node = NULL;
2384 const char *base;
2385
2386 assert(original_node);
2387 assert(suffix);
2388 assert(ret_name);
2389 assert(ret_node);
2390
2391 base = strrchr(original_node, '/');
2392 if (!base)
2393 base = original_node;
2394 else
2395 base++;
2396 if (isempty(base))
2397 return -EINVAL;
2398
2399 name = strjoin(base, suffix);
2400 if (!name)
2401 return -ENOMEM;
2402 if (!filename_is_valid(name))
2403 return -EINVAL;
2404
2405 node = path_join(sym_crypt_get_dir(), name);
2406 if (!node)
2407 return -ENOMEM;
2408
2409 *ret_name = TAKE_PTR(name);
2410 *ret_node = TAKE_PTR(node);
2411
2412 return 0;
2413 }
2414
2415 static int decrypt_partition(
2416 DissectedPartition *m,
2417 const char *passphrase,
2418 DissectImageFlags flags,
2419 DecryptedImage *d) {
2420
2421 _cleanup_free_ char *node = NULL, *name = NULL;
2422 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2423 _cleanup_close_ int fd = -EBADF;
2424 int r;
2425
2426 assert(m);
2427 assert(d);
2428
2429 if (!m->found || !m->node || !m->fstype)
2430 return 0;
2431
2432 if (!streq(m->fstype, "crypto_LUKS"))
2433 return 0;
2434
2435 if (!passphrase)
2436 return -ENOKEY;
2437
2438 r = dlopen_cryptsetup();
2439 if (r < 0)
2440 return r;
2441
2442 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
2443 if (r < 0)
2444 return r;
2445
2446 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2447 return -ENOMEM;
2448
2449 r = sym_crypt_init(&cd, m->node);
2450 if (r < 0)
2451 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
2452
2453 cryptsetup_enable_logging(cd);
2454
2455 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
2456 if (r < 0)
2457 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
2458
2459 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
2460 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
2461 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
2462 if (r < 0) {
2463 log_debug_errno(r, "Failed to activate LUKS device: %m");
2464 return r == -EPERM ? -EKEYREJECTED : r;
2465 }
2466
2467 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2468 if (fd < 0)
2469 return log_debug_errno(errno, "Failed to open %s: %m", node);
2470
2471 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2472 .name = TAKE_PTR(name),
2473 .device = TAKE_PTR(cd),
2474 };
2475
2476 m->decrypted_node = TAKE_PTR(node);
2477 close_and_replace(m->mount_node_fd, fd);
2478
2479 return 0;
2480 }
2481
2482 static int verity_can_reuse(
2483 const VeritySettings *verity,
2484 const char *name,
2485 struct crypt_device **ret_cd) {
2486
2487 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2488 _cleanup_free_ char *root_hash_existing = NULL;
2489 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2490 struct crypt_params_verity crypt_params = {};
2491 size_t root_hash_existing_size;
2492 int r;
2493
2494 assert(verity);
2495 assert(name);
2496 assert(ret_cd);
2497
2498 r = sym_crypt_init_by_name(&cd, name);
2499 if (r < 0)
2500 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
2501
2502 cryptsetup_enable_logging(cd);
2503
2504 r = sym_crypt_get_verity_info(cd, &crypt_params);
2505 if (r < 0)
2506 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
2507
2508 root_hash_existing_size = verity->root_hash_size;
2509 root_hash_existing = malloc0(root_hash_existing_size);
2510 if (!root_hash_existing)
2511 return -ENOMEM;
2512
2513 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
2514 if (r < 0)
2515 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
2516 if (verity->root_hash_size != root_hash_existing_size ||
2517 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
2518 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
2519
2520 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2521 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2522 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2523 * signing for the new one, and vice versa. */
2524 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
2525 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
2526 #endif
2527
2528 *ret_cd = TAKE_PTR(cd);
2529 return 0;
2530 }
2531
2532 static char* dm_deferred_remove_clean(char *name) {
2533 if (!name)
2534 return NULL;
2535
2536 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
2537 return mfree(name);
2538 }
2539 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
2540
2541 static int validate_signature_userspace(const VeritySettings *verity, DissectImageFlags flags) {
2542 int r;
2543
2544 if (!FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_USERSPACE_VERITY)) {
2545 log_debug("Userspace dm-verity signature authentication disabled via flag.");
2546 return 0;
2547 }
2548
2549 r = getenv_bool_secure("SYSTEMD_ALLOW_USERSPACE_VERITY");
2550 if (r < 0 && r != -ENXIO) {
2551 log_debug_errno(r, "Failed to parse $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable, refusing userspace dm-verity signature authentication.");
2552 return 0;
2553 }
2554 if (!r) {
2555 log_debug("Userspace dm-verity signature authentication disabled via $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable.");
2556 return 0;
2557 }
2558
2559 bool b;
2560 r = proc_cmdline_get_bool("systemd.allow_userspace_verity", PROC_CMDLINE_TRUE_WHEN_MISSING, &b);
2561 if (r < 0) {
2562 log_debug_errno(r, "Failed to parse systemd.allow_userspace_verity= kernel command line option, refusing userspace dm-verity signature authentication.");
2563 return 0;
2564 }
2565 if (!b) {
2566 log_debug("Userspace dm-verity signature authentication disabled via systemd.allow_userspace_verity= kernel command line variable.");
2567 return 0;
2568 }
2569
2570 #if HAVE_OPENSSL
2571 _cleanup_(sk_X509_free_allp) STACK_OF(X509) *sk = NULL;
2572 _cleanup_strv_free_ char **certs = NULL;
2573 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
2574 _cleanup_free_ char *s = NULL;
2575 _cleanup_(BIO_freep) BIO *bio = NULL; /* 'bio' must be freed first, 's' second, hence keep this order
2576 * of declaration in place, please */
2577 const unsigned char *d;
2578
2579 assert(verity);
2580 assert(verity->root_hash);
2581 assert(verity->root_hash_sig);
2582
2583 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
2584 * userspace validation. */
2585
2586 r = conf_files_list_nulstr(&certs, ".crt", NULL, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, CONF_PATHS_NULSTR("verity.d"));
2587 if (r < 0)
2588 return log_debug_errno(r, "Failed to enumerate certificates: %m");
2589 if (strv_isempty(certs)) {
2590 log_debug("No userspace dm-verity certificates found.");
2591 return 0;
2592 }
2593
2594 d = verity->root_hash_sig;
2595 p7 = d2i_PKCS7(NULL, &d, (long) verity->root_hash_sig_size);
2596 if (!p7)
2597 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PKCS7 DER signature data.");
2598
2599 s = hexmem(verity->root_hash, verity->root_hash_size);
2600 if (!s)
2601 return log_oom_debug();
2602
2603 bio = BIO_new_mem_buf(s, strlen(s));
2604 if (!bio)
2605 return log_oom_debug();
2606
2607 sk = sk_X509_new_null();
2608 if (!sk)
2609 return log_oom_debug();
2610
2611 STRV_FOREACH(i, certs) {
2612 _cleanup_(X509_freep) X509 *c = NULL;
2613 _cleanup_fclose_ FILE *f = NULL;
2614
2615 f = fopen(*i, "re");
2616 if (!f) {
2617 log_debug_errno(errno, "Failed to open '%s', ignoring: %m", *i);
2618 continue;
2619 }
2620
2621 c = PEM_read_X509(f, NULL, NULL, NULL);
2622 if (!c) {
2623 log_debug("Failed to load X509 certificate '%s', ignoring.", *i);
2624 continue;
2625 }
2626
2627 if (sk_X509_push(sk, c) == 0)
2628 return log_oom_debug();
2629
2630 TAKE_PTR(c);
2631 }
2632
2633 r = PKCS7_verify(p7, sk, NULL, bio, NULL, PKCS7_NOINTERN|PKCS7_NOVERIFY);
2634 if (r)
2635 log_debug("Userspace PKCS#7 validation succeeded.");
2636 else
2637 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL));
2638
2639 return r;
2640 #else
2641 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2642 return 0;
2643 #endif
2644 }
2645
2646 static int do_crypt_activate_verity(
2647 struct crypt_device *cd,
2648 const char *name,
2649 const VeritySettings *verity,
2650 DissectImageFlags flags) {
2651
2652 bool check_signature;
2653 int r, k;
2654
2655 assert(cd);
2656 assert(name);
2657 assert(verity);
2658
2659 if (verity->root_hash_sig) {
2660 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2661 if (r < 0 && r != -ENXIO)
2662 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2663
2664 check_signature = r != 0;
2665 } else
2666 check_signature = false;
2667
2668 if (check_signature) {
2669
2670 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2671 /* First, if we have support for signed keys in the kernel, then try that first. */
2672 r = sym_crypt_activate_by_signed_key(
2673 cd,
2674 name,
2675 verity->root_hash,
2676 verity->root_hash_size,
2677 verity->root_hash_sig,
2678 verity->root_hash_sig_size,
2679 CRYPT_ACTIVATE_READONLY);
2680 if (r >= 0)
2681 return r;
2682
2683 log_debug_errno(r, "Validation of dm-verity signature failed via the kernel, trying userspace validation instead: %m");
2684 #else
2685 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.",
2686 program_invocation_short_name);
2687 r = 0; /* Set for the propagation below */
2688 #endif
2689
2690 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2691 * works we'll try to activate without telling the kernel the signature. */
2692
2693 /* Preferably propagate the original kernel error, so that the fallback logic can work,
2694 * as the device-mapper is finicky around concurrent activations of the same volume */
2695 k = validate_signature_userspace(verity, flags);
2696 if (k < 0)
2697 return r < 0 ? r : k;
2698 if (k == 0)
2699 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(ENOKEY),
2700 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2701 }
2702
2703 return sym_crypt_activate_by_volume_key(
2704 cd,
2705 name,
2706 verity->root_hash,
2707 verity->root_hash_size,
2708 CRYPT_ACTIVATE_READONLY);
2709 }
2710
2711 static usec_t verity_timeout(void) {
2712 usec_t t = 100 * USEC_PER_MSEC;
2713 const char *e;
2714 int r;
2715
2716 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2717 * Let's make the timeout configurable. */
2718
2719 e = getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2720 if (!e)
2721 return t;
2722
2723 r = parse_sec(e, &t);
2724 if (r < 0)
2725 log_debug_errno(r,
2726 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2727 "using the default timeout (%s).",
2728 FORMAT_TIMESPAN(t, USEC_PER_MSEC));
2729
2730 return t;
2731 }
2732
2733 static int verity_partition(
2734 PartitionDesignator designator,
2735 DissectedPartition *m,
2736 DissectedPartition *v,
2737 const VeritySettings *verity,
2738 DissectImageFlags flags,
2739 DecryptedImage *d) {
2740
2741 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2742 _cleanup_free_ char *node = NULL, *name = NULL;
2743 _cleanup_close_ int mount_node_fd = -EBADF;
2744 int r;
2745
2746 assert(m);
2747 assert(v || (verity && verity->data_path));
2748
2749 if (!verity || !verity->root_hash)
2750 return 0;
2751 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2752 (verity->designator == designator)))
2753 return 0;
2754
2755 if (!m->found || !m->node || !m->fstype)
2756 return 0;
2757 if (!verity->data_path) {
2758 if (!v->found || !v->node || !v->fstype)
2759 return 0;
2760
2761 if (!streq(v->fstype, "DM_verity_hash"))
2762 return 0;
2763 }
2764
2765 r = dlopen_cryptsetup();
2766 if (r < 0)
2767 return r;
2768
2769 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2770 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2771 _cleanup_free_ char *root_hash_encoded = NULL;
2772
2773 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
2774 if (!root_hash_encoded)
2775 return -ENOMEM;
2776
2777 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2778 } else
2779 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
2780 if (r < 0)
2781 return r;
2782
2783 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
2784 if (r < 0)
2785 return r;
2786
2787 cryptsetup_enable_logging(cd);
2788
2789 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
2790 if (r < 0)
2791 return r;
2792
2793 r = sym_crypt_set_data_device(cd, m->node);
2794 if (r < 0)
2795 return r;
2796
2797 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2798 return -ENOMEM;
2799
2800 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2801 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2802 * retry a few times before giving up. */
2803 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
2804 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
2805 _cleanup_(sym_crypt_freep) struct crypt_device *existing_cd = NULL;
2806 _cleanup_close_ int fd = -EBADF;
2807
2808 /* First, check if the device already exists. */
2809 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2810 if (fd < 0 && !ERRNO_IS_DEVICE_ABSENT(errno))
2811 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2812 if (fd >= 0)
2813 goto check; /* The device already exists. Let's check it. */
2814
2815 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2816 r = do_crypt_activate_verity(cd, name, verity, flags);
2817 if (r >= 0)
2818 goto try_open; /* The device is activated. Let's open it. */
2819 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2820 * There's no way to distinguish this situation from a genuine error due to invalid
2821 * parameters, so immediately fall back to activating the device with a unique name.
2822 * Improvements in libcrypsetup can ensure this never happens:
2823 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2824 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2825 break;
2826 /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again if
2827 * sharing is enabled. */
2828 if (r == -ENODEV && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2829 goto try_again;
2830 if (!IN_SET(r,
2831 -EEXIST, /* Volume has already been opened and ready to be used. */
2832 -EBUSY /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2833 return log_debug_errno(r, "Failed to activate verity device %s: %m", node);
2834
2835 check:
2836 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2837 r = dm_deferred_remove_cancel(name);
2838 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2839 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2840 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2841 if (IN_SET(r, -EBUSY, -ENXIO))
2842 goto try_again;
2843 if (r < 0)
2844 return log_debug_errno(r, "Failed to disable automated deferred removal for verity device %s: %m", node);
2845
2846 restore_deferred_remove = strdup(name);
2847 if (!restore_deferred_remove)
2848 return log_oom_debug();
2849
2850 r = verity_can_reuse(verity, name, &existing_cd);
2851 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2852 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2853 break;
2854 if (IN_SET(r,
2855 -ENOENT, /* Removed?? */
2856 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2857 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2858 goto try_again;
2859 if (r < 0)
2860 return log_debug_errno(r, "Failed to check if existing verity device %s can be reused: %m", node);
2861
2862 if (fd < 0) {
2863 /* devmapper might say that the device exists, but the devlink might not yet have been
2864 * created. Check and wait for the udev event in that case. */
2865 r = device_wait_for_devlink(node, "block", verity_timeout(), NULL);
2866 /* Fallback to activation with a unique device if it's taking too long */
2867 if (r == -ETIMEDOUT && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2868 break;
2869 if (r < 0)
2870 return log_debug_errno(r, "Failed to wait device node symlink %s: %m", node);
2871 }
2872
2873 try_open:
2874 if (fd < 0) {
2875 /* Now, the device is activated and devlink is created. Let's open it. */
2876 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2877 if (fd < 0) {
2878 if (!ERRNO_IS_DEVICE_ABSENT(errno))
2879 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2880
2881 /* The device has already been removed?? */
2882 goto try_again;
2883 }
2884 }
2885
2886 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2887 restore_deferred_remove = mfree(restore_deferred_remove);
2888
2889 mount_node_fd = TAKE_FD(fd);
2890 if (existing_cd)
2891 crypt_free_and_replace(cd, existing_cd);
2892
2893 goto success;
2894
2895 try_again:
2896 /* Device is being removed by another process. Let's wait for a while. */
2897 (void) usleep_safe(2 * USEC_PER_MSEC);
2898 }
2899
2900 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2901 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2902 /* Before trying to activate with unique name, we need to free crypt_device object.
2903 * Otherwise, we get error from libcryptsetup like the following:
2904 * ------
2905 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2906 * ------
2907 */
2908 sym_crypt_free(cd);
2909 cd = NULL;
2910 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2911 }
2912
2913 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All attempts to activate verity device %s failed.", name);
2914
2915 success:
2916 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2917 .name = TAKE_PTR(name),
2918 .device = TAKE_PTR(cd),
2919 };
2920
2921 m->decrypted_node = TAKE_PTR(node);
2922 close_and_replace(m->mount_node_fd, mount_node_fd);
2923
2924 return 0;
2925 }
2926 #endif
2927
2928 int dissected_image_decrypt(
2929 DissectedImage *m,
2930 const char *passphrase,
2931 const VeritySettings *verity,
2932 DissectImageFlags flags) {
2933
2934 #if HAVE_LIBCRYPTSETUP
2935 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2936 int r;
2937 #endif
2938
2939 assert(m);
2940 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
2941
2942 /* Returns:
2943 *
2944 * = 0 → There was nothing to decrypt
2945 * > 0 → Decrypted successfully
2946 * -ENOKEY → There's something to decrypt but no key was supplied
2947 * -EKEYREJECTED → Passed key was not correct
2948 */
2949
2950 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
2951 return -EINVAL;
2952
2953 if (!m->encrypted && !m->verity_ready)
2954 return 0;
2955
2956 #if HAVE_LIBCRYPTSETUP
2957 r = decrypted_image_new(&d);
2958 if (r < 0)
2959 return r;
2960
2961 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
2962 DissectedPartition *p = m->partitions + i;
2963 PartitionDesignator k;
2964
2965 if (!p->found)
2966 continue;
2967
2968 r = decrypt_partition(p, passphrase, flags, d);
2969 if (r < 0)
2970 return r;
2971
2972 k = partition_verity_of(i);
2973 if (k >= 0) {
2974 flags |= getenv_bool("SYSTEMD_VERITY_SHARING") != 0 ? DISSECT_IMAGE_VERITY_SHARE : 0;
2975
2976 r = verity_partition(i, p, m->partitions + k, verity, flags, d);
2977 if (r < 0)
2978 return r;
2979 }
2980
2981 if (!p->decrypted_fstype && p->mount_node_fd >= 0 && p->decrypted_node) {
2982 r = probe_filesystem_full(p->mount_node_fd, p->decrypted_node, 0, UINT64_MAX, &p->decrypted_fstype);
2983 if (r < 0 && r != -EUCLEAN)
2984 return r;
2985 }
2986 }
2987
2988 m->decrypted_image = TAKE_PTR(d);
2989
2990 return 1;
2991 #else
2992 return -EOPNOTSUPP;
2993 #endif
2994 }
2995
2996 int dissected_image_decrypt_interactively(
2997 DissectedImage *m,
2998 const char *passphrase,
2999 const VeritySettings *verity,
3000 DissectImageFlags flags) {
3001
3002 _cleanup_strv_free_erase_ char **z = NULL;
3003 int n = 3, r;
3004
3005 if (passphrase)
3006 n--;
3007
3008 for (;;) {
3009 r = dissected_image_decrypt(m, passphrase, verity, flags);
3010 if (r >= 0)
3011 return r;
3012 if (r == -EKEYREJECTED)
3013 log_error_errno(r, "Incorrect passphrase, try again!");
3014 else if (r != -ENOKEY)
3015 return log_error_errno(r, "Failed to decrypt image: %m");
3016
3017 if (--n < 0)
3018 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
3019 "Too many retries.");
3020
3021 z = strv_free_erase(z);
3022
3023 static const AskPasswordRequest req = {
3024 .message = "Please enter image passphrase:",
3025 .id = "dissect",
3026 .keyring = "dissect",
3027 .credential = "dissect.passphrase",
3028 };
3029
3030 r = ask_password_auto(&req, USEC_INFINITY, /* flags= */ 0, &z);
3031 if (r < 0)
3032 return log_error_errno(r, "Failed to query for passphrase: %m");
3033
3034 passphrase = z[0];
3035 }
3036 }
3037
3038 static int decrypted_image_relinquish(DecryptedImage *d) {
3039 assert(d);
3040
3041 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
3042 * boolean so that we don't clean it up ourselves either anymore */
3043
3044 #if HAVE_LIBCRYPTSETUP
3045 int r;
3046
3047 for (size_t i = 0; i < d->n_decrypted; i++) {
3048 DecryptedPartition *p = d->decrypted + i;
3049
3050 if (p->relinquished)
3051 continue;
3052
3053 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
3054 if (r < 0)
3055 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
3056
3057 p->relinquished = true;
3058 }
3059 #endif
3060
3061 return 0;
3062 }
3063
3064 int dissected_image_relinquish(DissectedImage *m) {
3065 int r;
3066
3067 assert(m);
3068
3069 if (m->decrypted_image) {
3070 r = decrypted_image_relinquish(m->decrypted_image);
3071 if (r < 0)
3072 return r;
3073 }
3074
3075 if (m->loop)
3076 loop_device_relinquish(m->loop);
3077
3078 return 0;
3079 }
3080
3081 static char *build_auxiliary_path(const char *image, const char *suffix) {
3082 const char *e;
3083 char *n;
3084
3085 assert(image);
3086 assert(suffix);
3087
3088 e = endswith(image, ".raw");
3089 if (!e)
3090 return strjoin(e, suffix);
3091
3092 n = new(char, e - image + strlen(suffix) + 1);
3093 if (!n)
3094 return NULL;
3095
3096 strcpy(mempcpy(n, image, e - image), suffix);
3097 return n;
3098 }
3099
3100 void verity_settings_done(VeritySettings *v) {
3101 assert(v);
3102
3103 v->root_hash = mfree(v->root_hash);
3104 v->root_hash_size = 0;
3105
3106 v->root_hash_sig = mfree(v->root_hash_sig);
3107 v->root_hash_sig_size = 0;
3108
3109 v->data_path = mfree(v->data_path);
3110 }
3111
3112 int verity_settings_load(
3113 VeritySettings *verity,
3114 const char *image,
3115 const char *root_hash_path,
3116 const char *root_hash_sig_path) {
3117
3118 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
3119 size_t root_hash_size = 0, root_hash_sig_size = 0;
3120 _cleanup_free_ char *verity_data_path = NULL;
3121 PartitionDesignator designator;
3122 int r;
3123
3124 assert(verity);
3125 assert(image);
3126 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
3127
3128 /* If we are asked to load the root hash for a device node, exit early */
3129 if (is_device_path(image))
3130 return 0;
3131
3132 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIDECAR");
3133 if (r < 0 && r != -ENXIO)
3134 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
3135 if (r == 0)
3136 return 0;
3137
3138 designator = verity->designator;
3139
3140 /* We only fill in what isn't already filled in */
3141
3142 if (!verity->root_hash) {
3143 _cleanup_free_ char *text = NULL;
3144
3145 if (root_hash_path) {
3146 /* If explicitly specified it takes precedence */
3147 r = read_one_line_file(root_hash_path, &text);
3148 if (r < 0)
3149 return r;
3150
3151 if (designator < 0)
3152 designator = PARTITION_ROOT;
3153 } else {
3154 /* Otherwise look for xattr and separate file, and first for the data for root and if
3155 * that doesn't exist for /usr */
3156
3157 if (designator < 0 || designator == PARTITION_ROOT) {
3158 r = getxattr_malloc(image, "user.verity.roothash", &text);
3159 if (r < 0) {
3160 _cleanup_free_ char *p = NULL;
3161
3162 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
3163 return r;
3164
3165 p = build_auxiliary_path(image, ".roothash");
3166 if (!p)
3167 return -ENOMEM;
3168
3169 r = read_one_line_file(p, &text);
3170 if (r < 0 && r != -ENOENT)
3171 return r;
3172 }
3173
3174 if (text)
3175 designator = PARTITION_ROOT;
3176 }
3177
3178 if (!text && (designator < 0 || designator == PARTITION_USR)) {
3179 /* So in the "roothash" xattr/file name above the "root" of course primarily
3180 * refers to the root of the Verity Merkle tree. But coincidentally it also
3181 * is the hash for the *root* file system, i.e. the "root" neatly refers to
3182 * two distinct concepts called "root". Taking benefit of this happy
3183 * coincidence we call the file with the root hash for the /usr/ file system
3184 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
3185 * confusing. We thus drop the reference to the root of the Merkle tree, and
3186 * just indicate which file system it's about. */
3187 r = getxattr_malloc(image, "user.verity.usrhash", &text);
3188 if (r < 0) {
3189 _cleanup_free_ char *p = NULL;
3190
3191 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
3192 return r;
3193
3194 p = build_auxiliary_path(image, ".usrhash");
3195 if (!p)
3196 return -ENOMEM;
3197
3198 r = read_one_line_file(p, &text);
3199 if (r < 0 && r != -ENOENT)
3200 return r;
3201 }
3202
3203 if (text)
3204 designator = PARTITION_USR;
3205 }
3206 }
3207
3208 if (text) {
3209 r = unhexmem(text, &root_hash, &root_hash_size);
3210 if (r < 0)
3211 return r;
3212 if (root_hash_size < sizeof(sd_id128_t))
3213 return -EINVAL;
3214 }
3215 }
3216
3217 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
3218 if (root_hash_sig_path) {
3219 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
3220 if (r < 0 && r != -ENOENT)
3221 return r;
3222
3223 if (designator < 0)
3224 designator = PARTITION_ROOT;
3225 } else {
3226 if (designator < 0 || designator == PARTITION_ROOT) {
3227 _cleanup_free_ char *p = NULL;
3228
3229 /* Follow naming convention recommended by the relevant RFC:
3230 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
3231 p = build_auxiliary_path(image, ".roothash.p7s");
3232 if (!p)
3233 return -ENOMEM;
3234
3235 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
3236 if (r < 0 && r != -ENOENT)
3237 return r;
3238 if (r >= 0)
3239 designator = PARTITION_ROOT;
3240 }
3241
3242 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
3243 _cleanup_free_ char *p = NULL;
3244
3245 p = build_auxiliary_path(image, ".usrhash.p7s");
3246 if (!p)
3247 return -ENOMEM;
3248
3249 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
3250 if (r < 0 && r != -ENOENT)
3251 return r;
3252 if (r >= 0)
3253 designator = PARTITION_USR;
3254 }
3255 }
3256
3257 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
3258 return -EINVAL;
3259 }
3260
3261 if (!verity->data_path) {
3262 _cleanup_free_ char *p = NULL;
3263
3264 p = build_auxiliary_path(image, ".verity");
3265 if (!p)
3266 return -ENOMEM;
3267
3268 if (access(p, F_OK) < 0) {
3269 if (errno != ENOENT)
3270 return -errno;
3271 } else
3272 verity_data_path = TAKE_PTR(p);
3273 }
3274
3275 if (root_hash) {
3276 verity->root_hash = TAKE_PTR(root_hash);
3277 verity->root_hash_size = root_hash_size;
3278 }
3279
3280 if (root_hash_sig) {
3281 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
3282 verity->root_hash_sig_size = root_hash_sig_size;
3283 }
3284
3285 if (verity_data_path)
3286 verity->data_path = TAKE_PTR(verity_data_path);
3287
3288 if (verity->designator < 0)
3289 verity->designator = designator;
3290
3291 return 1;
3292 }
3293
3294 int dissected_image_load_verity_sig_partition(
3295 DissectedImage *m,
3296 int fd,
3297 VeritySettings *verity) {
3298
3299 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
3300 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
3301 size_t root_hash_size, root_hash_sig_size;
3302 _cleanup_free_ char *buf = NULL;
3303 PartitionDesignator d;
3304 DissectedPartition *p;
3305 JsonVariant *rh, *sig;
3306 ssize_t n;
3307 char *e;
3308 int r;
3309
3310 assert(m);
3311 assert(fd >= 0);
3312 assert(verity);
3313
3314 if (verity->root_hash && verity->root_hash_sig) /* Already loaded? */
3315 return 0;
3316
3317 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_EMBEDDED");
3318 if (r < 0 && r != -ENXIO)
3319 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
3320 if (r == 0)
3321 return 0;
3322
3323 d = partition_verity_sig_of(verity->designator < 0 ? PARTITION_ROOT : verity->designator);
3324 assert(d >= 0);
3325
3326 p = m->partitions + d;
3327 if (!p->found)
3328 return 0;
3329 if (p->offset == UINT64_MAX || p->size == UINT64_MAX)
3330 return -EINVAL;
3331
3332 if (p->size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
3333 return log_debug_errno(SYNTHETIC_ERRNO(EFBIG), "Verity signature partition is larger than 4M, refusing.");
3334
3335 buf = new(char, p->size+1);
3336 if (!buf)
3337 return -ENOMEM;
3338
3339 n = pread(fd, buf, p->size, p->offset);
3340 if (n < 0)
3341 return -ENOMEM;
3342 if ((uint64_t) n != p->size)
3343 return -EIO;
3344
3345 e = memchr(buf, 0, p->size);
3346 if (e) {
3347 /* If we found a NUL byte then the rest of the data must be NUL too */
3348 if (!memeqzero(e, p->size - (e - buf)))
3349 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
3350 } else
3351 buf[p->size] = 0;
3352
3353 r = json_parse(buf, 0, &v, NULL, NULL);
3354 if (r < 0)
3355 return log_debug_errno(r, "Failed to parse signature JSON data: %m");
3356
3357 rh = json_variant_by_key(v, "rootHash");
3358 if (!rh)
3359 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
3360 if (!json_variant_is_string(rh))
3361 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'rootHash' field of signature JSON object is not a string.");
3362
3363 r = unhexmem(json_variant_string(rh), &root_hash, &root_hash_size);
3364 if (r < 0)
3365 return log_debug_errno(r, "Failed to parse root hash field: %m");
3366
3367 /* Check if specified root hash matches if it is specified */
3368 if (verity->root_hash &&
3369 memcmp_nn(verity->root_hash, verity->root_hash_size, root_hash, root_hash_size) != 0) {
3370 _cleanup_free_ char *a = NULL, *b = NULL;
3371
3372 a = hexmem(root_hash, root_hash_size);
3373 b = hexmem(verity->root_hash, verity->root_hash_size);
3374
3375 return log_debug_errno(r, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a), strna(b));
3376 }
3377
3378 sig = json_variant_by_key(v, "signature");
3379 if (!sig)
3380 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
3381 if (!json_variant_is_string(sig))
3382 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'signature' field of signature JSON object is not a string.");
3383
3384 r = unbase64mem(json_variant_string(sig), &root_hash_sig, &root_hash_sig_size);
3385 if (r < 0)
3386 return log_debug_errno(r, "Failed to parse signature field: %m");
3387
3388 free_and_replace(verity->root_hash, root_hash);
3389 verity->root_hash_size = root_hash_size;
3390
3391 free_and_replace(verity->root_hash_sig, root_hash_sig);
3392 verity->root_hash_sig_size = root_hash_sig_size;
3393
3394 return 1;
3395 }
3396
3397 int dissected_image_acquire_metadata(DissectedImage *m, DissectImageFlags extra_flags) {
3398
3399 enum {
3400 META_HOSTNAME,
3401 META_MACHINE_ID,
3402 META_MACHINE_INFO,
3403 META_OS_RELEASE,
3404 META_INITRD_RELEASE,
3405 META_SYSEXT_RELEASE,
3406 META_CONFEXT_RELEASE,
3407 META_HAS_INIT_SYSTEM,
3408 _META_MAX,
3409 };
3410
3411 static const char *const paths[_META_MAX] = {
3412 [META_HOSTNAME] = "/etc/hostname\0",
3413 [META_MACHINE_ID] = "/etc/machine-id\0",
3414 [META_MACHINE_INFO] = "/etc/machine-info\0",
3415 [META_OS_RELEASE] = "/etc/os-release\0"
3416 "/usr/lib/os-release\0",
3417 [META_INITRD_RELEASE] = "/etc/initrd-release\0"
3418 "/usr/lib/initrd-release\0",
3419 [META_SYSEXT_RELEASE] = "sysext-release\0", /* String used only for logging. */
3420 [META_CONFEXT_RELEASE] = "confext-release\0", /* ditto */
3421 [META_HAS_INIT_SYSTEM] = "has-init-system\0", /* ditto */
3422 };
3423
3424 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **initrd_release = NULL, **sysext_release = NULL, **confext_release = NULL;
3425 _cleanup_free_ char *hostname = NULL, *t = NULL;
3426 _cleanup_close_pair_ int error_pipe[2] = EBADF_PAIR;
3427 _cleanup_(sigkill_waitp) pid_t child = 0;
3428 sd_id128_t machine_id = SD_ID128_NULL;
3429 unsigned n_meta_initialized = 0;
3430 int fds[2 * _META_MAX], r, v;
3431 int has_init_system = -1;
3432 ssize_t n;
3433
3434 BLOCK_SIGNALS(SIGCHLD);
3435
3436 assert(m);
3437
3438 for (; n_meta_initialized < _META_MAX; n_meta_initialized++) {
3439 assert(paths[n_meta_initialized]);
3440
3441 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
3442 r = -errno;
3443 goto finish;
3444 }
3445 }
3446
3447 r = get_common_dissect_directory(&t);
3448 if (r < 0)
3449 goto finish;
3450
3451 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
3452 r = -errno;
3453 goto finish;
3454 }
3455
3456 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
3457 if (r < 0)
3458 goto finish;
3459 if (r == 0) {
3460 /* Child in a new mount namespace */
3461 error_pipe[0] = safe_close(error_pipe[0]);
3462
3463 r = dissected_image_mount(
3464 m,
3465 t,
3466 /* uid_shift= */ UID_INVALID,
3467 /* uid_range= */ UID_INVALID,
3468 /* userns_fd= */ -EBADF,
3469 extra_flags |
3470 DISSECT_IMAGE_READ_ONLY |
3471 DISSECT_IMAGE_MOUNT_ROOT_ONLY |
3472 DISSECT_IMAGE_USR_NO_ROOT);
3473 if (r < 0) {
3474 log_debug_errno(r, "Failed to mount dissected image: %m");
3475 goto inner_fail;
3476 }
3477
3478 for (unsigned k = 0; k < _META_MAX; k++) {
3479 _cleanup_close_ int fd = -ENOENT;
3480
3481 assert(paths[k]);
3482
3483 fds[2*k] = safe_close(fds[2*k]);
3484
3485 switch (k) {
3486
3487 case META_SYSEXT_RELEASE:
3488 if (!m->image_name)
3489 goto next;
3490
3491 /* As per the os-release spec, if the image is an extension it will have a
3492 * file named after the image name in extension-release.d/ - we use the image
3493 * name and try to resolve it with the extension-release helpers, as
3494 * sometimes the image names are mangled on deployment and do not match
3495 * anymore. Unlike other paths this is not fixed, and the image name can be
3496 * mangled on deployment, so by calling into the helper we allow a fallback
3497 * that matches on the first extension-release file found in the directory,
3498 * if one named after the image cannot be found first. */
3499 r = open_extension_release(
3500 t,
3501 IMAGE_SYSEXT,
3502 m->image_name,
3503 /* relax_extension_release_check= */ false,
3504 /* ret_path= */ NULL,
3505 &fd);
3506 if (r < 0)
3507 fd = r;
3508 break;
3509
3510 case META_CONFEXT_RELEASE:
3511 if (!m->image_name)
3512 goto next;
3513
3514 /* As above */
3515 r = open_extension_release(
3516 t,
3517 IMAGE_CONFEXT,
3518 m->image_name,
3519 /* relax_extension_release_check= */ false,
3520 /* ret_path= */ NULL,
3521 &fd);
3522 if (r < 0)
3523 fd = r;
3524
3525 break;
3526
3527 case META_HAS_INIT_SYSTEM: {
3528 bool found = false;
3529
3530 FOREACH_STRING(init,
3531 "/usr/lib/systemd/systemd", /* systemd on /usr/ merged system */
3532 "/lib/systemd/systemd", /* systemd on /usr/ non-merged systems */
3533 "/sbin/init") { /* traditional path the Linux kernel invokes */
3534
3535 r = chase(init, t, CHASE_PREFIX_ROOT, NULL, NULL);
3536 if (r < 0) {
3537 if (r != -ENOENT)
3538 log_debug_errno(r, "Failed to resolve %s, ignoring: %m", init);
3539 } else {
3540 found = true;
3541 break;
3542 }
3543 }
3544
3545 r = loop_write(fds[2*k+1], &found, sizeof(found));
3546 if (r < 0)
3547 goto inner_fail;
3548
3549 goto next;
3550 }
3551
3552 default:
3553 NULSTR_FOREACH(p, paths[k]) {
3554 fd = chase_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3555 if (fd >= 0)
3556 break;
3557 }
3558 }
3559
3560 if (fd < 0) {
3561 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
3562 goto next;
3563 }
3564
3565 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
3566 if (r < 0)
3567 goto inner_fail;
3568
3569 next:
3570 fds[2*k+1] = safe_close(fds[2*k+1]);
3571 }
3572
3573 _exit(EXIT_SUCCESS);
3574
3575 inner_fail:
3576 /* Let parent know the error */
3577 (void) write(error_pipe[1], &r, sizeof(r));
3578 _exit(EXIT_FAILURE);
3579 }
3580
3581 error_pipe[1] = safe_close(error_pipe[1]);
3582
3583 for (unsigned k = 0; k < _META_MAX; k++) {
3584 _cleanup_fclose_ FILE *f = NULL;
3585
3586 assert(paths[k]);
3587
3588 fds[2*k+1] = safe_close(fds[2*k+1]);
3589
3590 f = take_fdopen(&fds[2*k], "r");
3591 if (!f) {
3592 r = -errno;
3593 goto finish;
3594 }
3595
3596 switch (k) {
3597
3598 case META_HOSTNAME:
3599 r = read_etc_hostname_stream(f, &hostname);
3600 if (r < 0)
3601 log_debug_errno(r, "Failed to read /etc/hostname of image: %m");
3602
3603 break;
3604
3605 case META_MACHINE_ID: {
3606 _cleanup_free_ char *line = NULL;
3607
3608 r = read_line(f, LONG_LINE_MAX, &line);
3609 if (r < 0)
3610 log_debug_errno(r, "Failed to read /etc/machine-id of image: %m");
3611 else if (r == 33) {
3612 r = sd_id128_from_string(line, &machine_id);
3613 if (r < 0)
3614 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
3615 } else if (r == 0)
3616 log_debug("/etc/machine-id file of image is empty.");
3617 else if (streq(line, "uninitialized"))
3618 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3619 else
3620 log_debug("/etc/machine-id file of image has unexpected length %i.", r);
3621
3622 break;
3623 }
3624
3625 case META_MACHINE_INFO:
3626 r = load_env_file_pairs(f, "machine-info", &machine_info);
3627 if (r < 0)
3628 log_debug_errno(r, "Failed to read /etc/machine-info of image: %m");
3629
3630 break;
3631
3632 case META_OS_RELEASE:
3633 r = load_env_file_pairs(f, "os-release", &os_release);
3634 if (r < 0)
3635 log_debug_errno(r, "Failed to read OS release file of image: %m");
3636
3637 break;
3638
3639 case META_INITRD_RELEASE:
3640 r = load_env_file_pairs(f, "initrd-release", &initrd_release);
3641 if (r < 0)
3642 log_debug_errno(r, "Failed to read initrd release file of image: %m");
3643
3644 break;
3645
3646 case META_SYSEXT_RELEASE:
3647 r = load_env_file_pairs(f, "sysext-release", &sysext_release);
3648 if (r < 0)
3649 log_debug_errno(r, "Failed to read sysext release file of image: %m");
3650
3651 break;
3652
3653 case META_CONFEXT_RELEASE:
3654 r = load_env_file_pairs(f, "confext-release", &confext_release);
3655 if (r < 0)
3656 log_debug_errno(r, "Failed to read confext release file of image: %m");
3657
3658 break;
3659
3660 case META_HAS_INIT_SYSTEM: {
3661 bool b = false;
3662 size_t nr;
3663
3664 errno = 0;
3665 nr = fread(&b, 1, sizeof(b), f);
3666 if (nr != sizeof(b))
3667 log_debug_errno(errno_or_else(EIO), "Failed to read has-init-system boolean: %m");
3668 else
3669 has_init_system = b;
3670
3671 break;
3672 }}
3673 }
3674
3675 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3676 child = 0;
3677 if (r < 0)
3678 goto finish;
3679
3680 n = read(error_pipe[0], &v, sizeof(v));
3681 if (n < 0) {
3682 r = -errno;
3683 goto finish;
3684 }
3685 if (n == sizeof(v)) {
3686 r = v; /* propagate error sent to us from child */
3687 goto finish;
3688 }
3689 if (n != 0) {
3690 r = -EIO;
3691 goto finish;
3692 }
3693 if (r != EXIT_SUCCESS) {
3694 r = -EPROTO;
3695 goto finish;
3696 }
3697
3698 free_and_replace(m->hostname, hostname);
3699 m->machine_id = machine_id;
3700 strv_free_and_replace(m->machine_info, machine_info);
3701 strv_free_and_replace(m->os_release, os_release);
3702 strv_free_and_replace(m->initrd_release, initrd_release);
3703 strv_free_and_replace(m->sysext_release, sysext_release);
3704 strv_free_and_replace(m->confext_release, confext_release);
3705 m->has_init_system = has_init_system;
3706
3707 finish:
3708 for (unsigned k = 0; k < n_meta_initialized; k++)
3709 safe_close_pair(fds + 2*k);
3710
3711 return r;
3712 }
3713
3714 Architecture dissected_image_architecture(DissectedImage *img) {
3715 assert(img);
3716
3717 if (img->partitions[PARTITION_ROOT].found &&
3718 img->partitions[PARTITION_ROOT].architecture >= 0)
3719 return img->partitions[PARTITION_ROOT].architecture;
3720
3721 if (img->partitions[PARTITION_USR].found &&
3722 img->partitions[PARTITION_USR].architecture >= 0)
3723 return img->partitions[PARTITION_USR].architecture;
3724
3725 return _ARCHITECTURE_INVALID;
3726 }
3727
3728 int dissect_loop_device(
3729 LoopDevice *loop,
3730 const VeritySettings *verity,
3731 const MountOptions *mount_options,
3732 const ImagePolicy *image_policy,
3733 DissectImageFlags flags,
3734 DissectedImage **ret) {
3735
3736 #if HAVE_BLKID
3737 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
3738 int r;
3739
3740 assert(loop);
3741
3742 r = dissected_image_new(loop->backing_file ?: loop->node, &m);
3743 if (r < 0)
3744 return r;
3745
3746 m->loop = loop_device_ref(loop);
3747 m->image_size = m->loop->device_size;
3748 m->sector_size = m->loop->sector_size;
3749
3750 r = dissect_image(m, loop->fd, loop->node, verity, mount_options, image_policy, flags);
3751 if (r < 0)
3752 return r;
3753
3754 if (ret)
3755 *ret = TAKE_PTR(m);
3756
3757 return 0;
3758 #else
3759 return -EOPNOTSUPP;
3760 #endif
3761 }
3762
3763 int dissect_loop_device_and_warn(
3764 LoopDevice *loop,
3765 const VeritySettings *verity,
3766 const MountOptions *mount_options,
3767 const ImagePolicy *image_policy,
3768 DissectImageFlags flags,
3769 DissectedImage **ret) {
3770
3771 assert(loop);
3772
3773 return dissect_log_error(
3774 LOG_ERR,
3775 dissect_loop_device(loop, verity, mount_options, image_policy, flags, ret),
3776 loop->backing_file ?: loop->node,
3777 verity);
3778
3779 }
3780
3781 bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
3782 assert(image);
3783
3784 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3785 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3786 * images we only check the partition type.
3787 *
3788 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3789 * image. */
3790
3791 if (image->single_file_system)
3792 return partition_designator == PARTITION_ROOT && image->has_verity;
3793
3794 return partition_verity_of(partition_designator) >= 0;
3795 }
3796
3797 bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3798 PartitionDesignator k;
3799
3800 assert(image);
3801
3802 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3803 * works for the root partition, for others only if the associated verity partition was found. */
3804
3805 if (!image->verity_ready)
3806 return false;
3807
3808 if (image->single_file_system)
3809 return partition_designator == PARTITION_ROOT;
3810
3811 k = partition_verity_of(partition_designator);
3812 return k >= 0 && image->partitions[k].found;
3813 }
3814
3815 bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3816 PartitionDesignator k;
3817
3818 assert(image);
3819
3820 /* Checks if this partition has verity signature data available that we can use. */
3821
3822 if (!image->verity_sig_ready)
3823 return false;
3824
3825 if (image->single_file_system)
3826 return partition_designator == PARTITION_ROOT;
3827
3828 k = partition_verity_sig_of(partition_designator);
3829 return k >= 0 && image->partitions[k].found;
3830 }
3831
3832 MountOptions* mount_options_free_all(MountOptions *options) {
3833 MountOptions *m;
3834
3835 while ((m = LIST_POP(mount_options, options))) {
3836 free(m->options);
3837 free(m);
3838 }
3839
3840 return NULL;
3841 }
3842
3843 const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
3844 LIST_FOREACH(mount_options, m, options)
3845 if (designator == m->partition_designator && !isempty(m->options))
3846 return m->options;
3847
3848 return NULL;
3849 }
3850
3851 int mount_image_privately_interactively(
3852 const char *image,
3853 const ImagePolicy *image_policy,
3854 DissectImageFlags flags,
3855 char **ret_directory,
3856 int *ret_dir_fd,
3857 LoopDevice **ret_loop_device) {
3858
3859 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3860 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
3861 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3862 _cleanup_free_ char *dir = NULL;
3863 int r;
3864
3865 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3866 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3867 * easily. */
3868
3869 assert(image);
3870 assert(ret_loop_device);
3871
3872 /* We intend to mount this right-away, hence add the partitions if needed and pin them. */
3873 flags |= DISSECT_IMAGE_ADD_PARTITION_DEVICES |
3874 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
3875
3876 r = verity_settings_load(&verity, image, NULL, NULL);
3877 if (r < 0)
3878 return log_error_errno(r, "Failed to load root hash data: %m");
3879
3880 r = loop_device_make_by_path(
3881 image,
3882 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
3883 /* sector_size= */ UINT32_MAX,
3884 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
3885 LOCK_SH,
3886 &d);
3887 if (r < 0)
3888 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
3889
3890 r = dissect_loop_device_and_warn(
3891 d,
3892 &verity,
3893 /* mount_options= */ NULL,
3894 image_policy,
3895 flags,
3896 &dissected_image);
3897 if (r < 0)
3898 return r;
3899
3900 r = dissected_image_load_verity_sig_partition(dissected_image, d->fd, &verity);
3901 if (r < 0)
3902 return r;
3903
3904 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags);
3905 if (r < 0)
3906 return r;
3907
3908 r = detach_mount_namespace();
3909 if (r < 0)
3910 return log_error_errno(r, "Failed to detach mount namespace: %m");
3911
3912 r = mkdir_p("/run/systemd/mount-rootfs", 0555);
3913 if (r < 0)
3914 return log_error_errno(r, "Failed to create mount point: %m");
3915
3916 r = dissected_image_mount_and_warn(
3917 dissected_image,
3918 "/run/systemd/mount-rootfs",
3919 /* uid_shift= */ UID_INVALID,
3920 /* uid_range= */ UID_INVALID,
3921 /* userns_fd= */ -EBADF,
3922 flags);
3923 if (r < 0)
3924 return r;
3925
3926 r = loop_device_flock(d, LOCK_UN);
3927 if (r < 0)
3928 return r;
3929
3930 r = dissected_image_relinquish(dissected_image);
3931 if (r < 0)
3932 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
3933
3934 if (ret_directory) {
3935 dir = strdup("/run/systemd/mount-rootfs");
3936 if (!dir)
3937 return log_oom();
3938 }
3939
3940 if (ret_dir_fd) {
3941 _cleanup_close_ int dir_fd = -EBADF;
3942
3943 dir_fd = open("/run/systemd/mount-rootfs", O_CLOEXEC|O_DIRECTORY);
3944 if (dir_fd < 0)
3945 return log_error_errno(errno, "Failed to open mount point directory: %m");
3946
3947 *ret_dir_fd = TAKE_FD(dir_fd);
3948 }
3949
3950 if (ret_directory)
3951 *ret_directory = TAKE_PTR(dir);
3952
3953 *ret_loop_device = TAKE_PTR(d);
3954 return 0;
3955 }
3956
3957 static bool mount_options_relax_extension_release_checks(const MountOptions *options) {
3958 if (!options)
3959 return false;
3960
3961 return string_contains_word(mount_options_from_designator(options, PARTITION_ROOT), ",", "x-systemd.relax-extension-release-check") ||
3962 string_contains_word(mount_options_from_designator(options, PARTITION_USR), ",", "x-systemd.relax-extension-release-check") ||
3963 string_contains_word(options->options, ",", "x-systemd.relax-extension-release-check");
3964 }
3965
3966 int verity_dissect_and_mount(
3967 int src_fd,
3968 const char *src,
3969 const char *dest,
3970 const MountOptions *options,
3971 const ImagePolicy *image_policy,
3972 const char *required_host_os_release_id,
3973 const char *required_host_os_release_version_id,
3974 const char *required_host_os_release_sysext_level,
3975 const char *required_host_os_release_confext_level,
3976 const char *required_sysext_scope,
3977 DissectedImage **ret_image) {
3978
3979 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
3980 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3981 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3982 DissectImageFlags dissect_image_flags;
3983 bool relax_extension_release_check;
3984 int r;
3985
3986 assert(src);
3987 /* Verifying release metadata requires mounted image for now, so ensure the check is skipped when
3988 * opening an image without mounting it immediately (i.e.: 'dest' is NULL). */
3989 assert(!required_host_os_release_id || dest);
3990
3991 relax_extension_release_check = mount_options_relax_extension_release_checks(options);
3992
3993 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
3994 r = verity_settings_load(&verity, src, NULL, NULL);
3995 if (r < 0)
3996 return log_debug_errno(r, "Failed to load root hash: %m");
3997
3998 dissect_image_flags =
3999 (verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0) |
4000 (relax_extension_release_check ? DISSECT_IMAGE_RELAX_EXTENSION_CHECK : 0) |
4001 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
4002 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
4003 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
4004
4005 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
4006 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4007 r = loop_device_make_by_path(
4008 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
4009 /* open_flags= */ -1,
4010 /* sector_size= */ UINT32_MAX,
4011 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
4012 LOCK_SH,
4013 &loop_device);
4014 if (r < 0)
4015 return log_debug_errno(r, "Failed to create loop device for image: %m");
4016
4017 r = dissect_loop_device(
4018 loop_device,
4019 &verity,
4020 options,
4021 image_policy,
4022 dissect_image_flags,
4023 &dissected_image);
4024 /* No partition table? Might be a single-filesystem image, try again */
4025 if (!verity.data_path && r == -ENOPKG)
4026 r = dissect_loop_device(
4027 loop_device,
4028 &verity,
4029 options,
4030 image_policy,
4031 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
4032 &dissected_image);
4033 if (r < 0)
4034 return log_debug_errno(r, "Failed to dissect image: %m");
4035
4036 r = dissected_image_load_verity_sig_partition(dissected_image, loop_device->fd, &verity);
4037 if (r < 0)
4038 return r;
4039
4040 r = dissected_image_decrypt(
4041 dissected_image,
4042 NULL,
4043 &verity,
4044 dissect_image_flags);
4045 if (r < 0)
4046 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
4047
4048 if (dest) {
4049 r = mkdir_p_label(dest, 0755);
4050 if (r < 0)
4051 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
4052 r = umount_recursive(dest, 0);
4053 if (r < 0)
4054 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
4055 }
4056
4057 r = dissected_image_mount(
4058 dissected_image,
4059 dest,
4060 /* uid_shift= */ UID_INVALID,
4061 /* uid_range= */ UID_INVALID,
4062 /* userns_fd= */ -EBADF,
4063 dissect_image_flags);
4064 if (r < 0)
4065 return log_debug_errno(r, "Failed to mount image: %m");
4066
4067 r = loop_device_flock(loop_device, LOCK_UN);
4068 if (r < 0)
4069 return log_debug_errno(r, "Failed to unlock loopback device: %m");
4070
4071 /* If we got os-release values from the caller, then we need to match them with the image's
4072 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
4073 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
4074 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
4075 * then a simple match on the ID will be performed. */
4076 if (required_host_os_release_id) {
4077 _cleanup_strv_free_ char **extension_release = NULL;
4078 ImageClass class = IMAGE_SYSEXT;
4079
4080 assert(!isempty(required_host_os_release_id));
4081
4082 r = load_extension_release_pairs(dest, IMAGE_SYSEXT, dissected_image->image_name, relax_extension_release_check, &extension_release);
4083 if (r == -ENOENT) {
4084 r = load_extension_release_pairs(dest, IMAGE_CONFEXT, dissected_image->image_name, relax_extension_release_check, &extension_release);
4085 if (r >= 0)
4086 class = IMAGE_CONFEXT;
4087 }
4088 if (r < 0)
4089 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
4090
4091 r = extension_release_validate(
4092 dissected_image->image_name,
4093 required_host_os_release_id,
4094 required_host_os_release_version_id,
4095 class == IMAGE_SYSEXT ? required_host_os_release_sysext_level : required_host_os_release_confext_level,
4096 required_sysext_scope,
4097 extension_release,
4098 class);
4099 if (r == 0)
4100 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
4101 if (r < 0)
4102 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
4103 }
4104
4105 r = dissected_image_relinquish(dissected_image);
4106 if (r < 0)
4107 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
4108
4109 if (ret_image)
4110 *ret_image = TAKE_PTR(dissected_image);
4111
4112 return 0;
4113 }
4114
4115 int get_common_dissect_directory(char **ret) {
4116 _cleanup_free_ char *t = NULL;
4117 int r;
4118
4119 /* A common location we mount dissected images to. The assumption is that everyone who uses this
4120 * function runs in their own private mount namespace (with mount propagation off on /run/systemd/,
4121 * and thus can mount something here without affecting anyone else). */
4122
4123 t = strdup("/run/systemd/dissect-root");
4124 if (!t)
4125 return log_oom_debug();
4126
4127 r = mkdir_parents(t, 0755);
4128 if (r < 0)
4129 return log_debug_errno(r, "Failed to create parent dirs of mount point '%s': %m", t);
4130
4131 r = RET_NERRNO(mkdir(t, 0000)); /* It's supposed to be overmounted, hence let's make this inaccessible */
4132 if (r < 0 && r != -EEXIST)
4133 return log_debug_errno(r, "Failed to create mount point '%s': %m", t);
4134
4135 if (ret)
4136 *ret = TAKE_PTR(t);
4137
4138 return 0;
4139 }