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