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