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