]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
mkosi: mask isc-dhcp-server
[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 && fstype_can_norecovery(fstype))
1915 if (!strextend_with_separator(&options, ",", "norecovery"))
1916 return -ENOMEM;
1917
1918 if (discard && fstype && fstype_can_discard(fstype))
1919 if (!strextend_with_separator(&options, ",", "discard"))
1920 return -ENOMEM;
1921
1922 if (!ret_ms_flags) /* Fold flags into option string if ret_flags specified as NULL */
1923 if (!strextend_with_separator(&options, ",",
1924 FLAGS_SET(flags, MS_RDONLY) ? "ro" : "rw",
1925 FLAGS_SET(flags, MS_NODEV) ? "nodev" : "dev",
1926 FLAGS_SET(flags, MS_NOSUID) ? "nosuid" : "suid",
1927 FLAGS_SET(flags, MS_NOEXEC) ? "noexec" : "exec",
1928 FLAGS_SET(flags, MS_NOSYMFOLLOW) ? "nosymfollow" : NULL))
1929 /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
1930 return -ENOMEM;
1931
1932 if (ret_ms_flags)
1933 *ret_ms_flags = flags;
1934
1935 *ret_options = TAKE_PTR(options);
1936 return 0;
1937 }
1938
1939 static bool need_user_mapping(uid_t uid_shift, uid_t uid_range) {
1940
1941 if (!uid_is_valid(uid_shift))
1942 return false;
1943
1944 return uid_shift != 0 || uid_range != UINT32_MAX;
1945 }
1946
1947 static int mount_partition(
1948 PartitionDesignator d,
1949 DissectedPartition *m,
1950 const char *where,
1951 const char *directory,
1952 uid_t uid_shift,
1953 uid_t uid_range,
1954 int userns_fd,
1955 DissectImageFlags flags) {
1956
1957 _cleanup_free_ char *chased = NULL, *options = NULL;
1958 const char *p = NULL, *node, *fstype = NULL;
1959 bool rw, discard, grow;
1960 unsigned long ms_flags;
1961 int r;
1962
1963 assert(m);
1964
1965 if (!m->found)
1966 return 0;
1967
1968 /* Check the various combinations when we can't do anything anymore */
1969 if (m->fsmount_fd < 0 && m->mount_node_fd < 0)
1970 return 0;
1971 if (m->fsmount_fd >= 0 && !where)
1972 return 0;
1973 if (!where && m->mount_node_fd < 0)
1974 return 0;
1975
1976 if (m->fsmount_fd < 0) {
1977 fstype = dissected_partition_fstype(m);
1978 if (!fstype)
1979 return -EAFNOSUPPORT;
1980
1981 /* We are looking at an encrypted partition? This either means stacked encryption, or the
1982 * caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error
1983 * for this case. */
1984 if (streq(fstype, "crypto_LUKS"))
1985 return -EUNATCH;
1986
1987 r = dissect_fstype_ok(fstype);
1988 if (r < 0)
1989 return r;
1990 if (!r)
1991 return -EIDRM; /* Recognizable error */
1992 }
1993
1994 node = m->mount_node_fd < 0 ? NULL : FORMAT_PROC_FD_PATH(m->mount_node_fd);
1995 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
1996
1997 discard = ((flags & DISSECT_IMAGE_DISCARD) ||
1998 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && (m->node && is_loop_device(m->node) > 0)));
1999
2000 grow = rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS);
2001
2002 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw && m->mount_node_fd >= 0 && m->fsmount_fd < 0) {
2003 r = run_fsck(m->mount_node_fd, fstype);
2004 if (r < 0)
2005 return r;
2006 }
2007
2008 if (where) {
2009 if (directory) {
2010 /* Automatically create missing mount points inside the image, if necessary. */
2011 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755, NULL);
2012 if (r < 0 && r != -EROFS)
2013 return r;
2014
2015 r = chase(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2016 if (r < 0)
2017 return r;
2018
2019 p = chased;
2020 } else {
2021 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
2022 * image (as the branch above does) but the host hierarchy, and the created directory might
2023 * survive our mount in the host hierarchy hence. */
2024 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
2025 r = mkdir_p(where, 0755);
2026 if (r < 0)
2027 return r;
2028 }
2029
2030 p = where;
2031 }
2032 }
2033
2034 if (m->fsmount_fd < 0) {
2035 r = partition_pick_mount_options(d, fstype, rw, discard, &options, &ms_flags);
2036 if (r < 0)
2037 return r;
2038
2039 if (need_user_mapping(uid_shift, uid_range) && fstype_can_uid_gid(fstype)) {
2040 _cleanup_free_ char *uid_option = NULL;
2041
2042 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
2043 return -ENOMEM;
2044
2045 if (!strextend_with_separator(&options, ",", uid_option))
2046 return -ENOMEM;
2047
2048 userns_fd = -EBADF; /* Not needed */
2049 }
2050
2051 if (!isempty(m->mount_options))
2052 if (!strextend_with_separator(&options, ",", m->mount_options))
2053 return -ENOMEM;
2054 }
2055
2056 if (p) {
2057 if (m->fsmount_fd >= 0) {
2058 /* Case #1: Attach existing fsmount fd to the file system */
2059
2060 r = mount_exchange_graceful(
2061 m->fsmount_fd,
2062 p,
2063 FLAGS_SET(flags, DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE));
2064 if (r < 0)
2065 return log_debug_errno(r, "Failed to mount image on '%s': %m", p);
2066
2067 } else {
2068 assert(node);
2069
2070 /* Case #2: Mount directly into place */
2071 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, ms_flags, options);
2072 if (r < 0)
2073 return r;
2074
2075 if (grow)
2076 (void) fs_grow(node, -EBADF, p);
2077
2078 if (userns_fd >= 0) {
2079 r = remount_idmap_fd(STRV_MAKE(p), userns_fd);
2080 if (r < 0)
2081 return r;
2082 }
2083 }
2084 } else {
2085 assert(node);
2086
2087 /* Case #3: Create fsmount fd */
2088
2089 m->fsmount_fd = make_fsmount(LOG_DEBUG, node, fstype, ms_flags, options, userns_fd);
2090 if (m->fsmount_fd < 0)
2091 return m->fsmount_fd;
2092
2093 if (grow)
2094 (void) fs_grow(node, m->fsmount_fd, NULL);
2095 }
2096
2097 return 1;
2098 }
2099
2100 static int mount_root_tmpfs(const char *where, uid_t uid_shift, uid_t uid_range, DissectImageFlags flags) {
2101 _cleanup_free_ char *options = NULL;
2102 int r;
2103
2104 assert(where);
2105
2106 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
2107
2108 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
2109 r = mkdir_p(where, 0755);
2110 if (r < 0)
2111 return r;
2112 }
2113
2114 if (need_user_mapping(uid_shift, uid_range)) {
2115 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
2116 return -ENOMEM;
2117 }
2118
2119 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
2120 if (r < 0)
2121 return r;
2122
2123 return 1;
2124 }
2125
2126 static int mount_point_is_available(const char *where, const char *path, bool missing_ok) {
2127 _cleanup_free_ char *p = NULL;
2128 int r;
2129
2130 /* Check whether <path> is suitable as a mountpoint, i.e. is an empty directory
2131 * or does not exist at all (when missing_ok). */
2132
2133 r = chase(path, where, CHASE_PREFIX_ROOT, &p, NULL);
2134 if (r == -ENOENT)
2135 return missing_ok;
2136 if (r < 0)
2137 return log_debug_errno(r, "Failed to chase \"%s\": %m", path);
2138
2139 r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
2140 if (r == -ENOTDIR)
2141 return false;
2142 if (r < 0)
2143 return log_debug_errno(r, "Failed to check directory \"%s\": %m", p);
2144 return r > 0;
2145 }
2146
2147 int dissected_image_mount(
2148 DissectedImage *m,
2149 const char *where,
2150 uid_t uid_shift,
2151 uid_t uid_range,
2152 int userns_fd,
2153 DissectImageFlags flags) {
2154
2155 _cleanup_close_ int my_userns_fd = -EBADF;
2156 int r;
2157
2158 assert(m);
2159
2160 /* If 'where' is NULL then we'll use the new mount API to create fsmount() fds for the mounts and
2161 * store them in DissectedPartition.fsmount_fd.
2162 *
2163 * If 'where' is not NULL then we'll either mount the partitions to the right places ourselves,
2164 * or use DissectedPartition.fsmount_fd and bind it to the right places.
2165 *
2166 * This allows splitting the setting up up the superblocks and the binding to file systems paths into
2167 * two distinct and differently privileged components: one that gets the fsmount fds, and the other
2168 * that then applies them.
2169 *
2170 * Returns:
2171 *
2172 * -ENXIO → No root partition found
2173 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
2174 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
2175 * -EUCLEAN → fsck for file system failed
2176 * -EBUSY → File system already mounted/used elsewhere (kernel)
2177 * -EAFNOSUPPORT → File system type not supported or not known
2178 * -EIDRM → File system is not among allowlisted "common" file systems
2179 */
2180
2181 if (!where && (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0)
2182 return -EOPNOTSUPP; /* for now, not supported */
2183
2184 if (!(m->partitions[PARTITION_ROOT].found ||
2185 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
2186 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
2187
2188 if (userns_fd < 0 && need_user_mapping(uid_shift, uid_range) && FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED)) {
2189
2190 my_userns_fd = make_userns(uid_shift, uid_range, UID_INVALID, UID_INVALID, REMOUNT_IDMAPPING_HOST_ROOT);
2191 if (my_userns_fd < 0)
2192 return my_userns_fd;
2193
2194 userns_fd = my_userns_fd;
2195 }
2196
2197 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
2198
2199 /* First mount the root fs. If there's none we use a tmpfs. */
2200 if (m->partitions[PARTITION_ROOT].found) {
2201 r = mount_partition(PARTITION_ROOT, m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, userns_fd, flags);
2202 if (r < 0)
2203 return r;
2204
2205 } else if (where) {
2206 r = mount_root_tmpfs(where, uid_shift, uid_range, flags);
2207 if (r < 0)
2208 return r;
2209 }
2210
2211 /* For us mounting root always means mounting /usr as well */
2212 r = mount_partition(PARTITION_USR, m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, userns_fd, flags);
2213 if (r < 0)
2214 return r;
2215 }
2216
2217 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0 &&
2218 (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
2219 /* If either one of the validation flags are set, ensure that the image qualifies as
2220 * one or the other (or both). */
2221 bool ok = false;
2222
2223 assert(where);
2224
2225 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
2226 r = path_is_os_tree(where);
2227 if (r < 0)
2228 return r;
2229 if (r > 0)
2230 ok = true;
2231 }
2232 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT) && m->image_name) {
2233 r = extension_has_forbidden_content(where);
2234 if (r < 0)
2235 return r;
2236 if (r == 0) {
2237 r = path_is_extension_tree(IMAGE_SYSEXT, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
2238 if (r == 0)
2239 r = path_is_extension_tree(IMAGE_CONFEXT, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
2240 if (r < 0)
2241 return r;
2242 if (r > 0)
2243 ok = true;
2244 }
2245 }
2246
2247 if (!ok)
2248 return -ENOMEDIUM;
2249 }
2250
2251 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2252 return 0;
2253
2254 r = mount_partition(PARTITION_HOME, m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, userns_fd, flags);
2255 if (r < 0)
2256 return r;
2257
2258 r = mount_partition(PARTITION_SRV, m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, userns_fd, flags);
2259 if (r < 0)
2260 return r;
2261
2262 r = mount_partition(PARTITION_VAR, m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, userns_fd, flags);
2263 if (r < 0)
2264 return r;
2265
2266 r = mount_partition(PARTITION_TMP, m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, userns_fd, flags);
2267 if (r < 0)
2268 return r;
2269
2270 int slash_boot_is_available = 0;
2271 if (where) {
2272 r = slash_boot_is_available = mount_point_is_available(where, "/boot", /* missing_ok = */ true);
2273 if (r < 0)
2274 return r;
2275 }
2276 if (!where || slash_boot_is_available) {
2277 r = mount_partition(PARTITION_XBOOTLDR, m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, userns_fd, flags);
2278 if (r < 0)
2279 return r;
2280 slash_boot_is_available = !r;
2281 }
2282
2283 if (m->partitions[PARTITION_ESP].found) {
2284 const char *esp_path = NULL;
2285
2286 if (where) {
2287 /* Mount the ESP to /boot/ if it exists and is empty and we didn't already mount the
2288 * XBOOTLDR partition into it. Otherwise, use /efi instead, but only if it exists
2289 * and is empty. */
2290
2291 if (slash_boot_is_available) {
2292 r = mount_point_is_available(where, "/boot", /* missing_ok = */ false);
2293 if (r < 0)
2294 return r;
2295 if (r > 0)
2296 esp_path = "/boot";
2297 }
2298
2299 if (!esp_path) {
2300 r = mount_point_is_available(where, "/efi", /* missing_ok = */ true);
2301 if (r < 0)
2302 return r;
2303 if (r > 0)
2304 esp_path = "/efi";
2305 }
2306 }
2307
2308 /* OK, let's mount the ESP now (possibly creating the dir if missing) */
2309 r = mount_partition(PARTITION_ESP, m->partitions + PARTITION_ESP, where, esp_path, uid_shift, uid_range, userns_fd, flags);
2310 if (r < 0)
2311 return r;
2312 }
2313
2314 return 0;
2315 }
2316
2317 int dissected_image_mount_and_warn(
2318 DissectedImage *m,
2319 const char *where,
2320 uid_t uid_shift,
2321 uid_t uid_range,
2322 int userns_fd,
2323 DissectImageFlags flags) {
2324
2325 int r;
2326
2327 assert(m);
2328
2329 r = dissected_image_mount(m, where, uid_shift, uid_range, userns_fd, flags);
2330 if (r == -ENXIO)
2331 return log_error_errno(r, "Failed to mount image: No root file system found in image.");
2332 if (r == -EMEDIUMTYPE)
2333 return log_error_errno(r, "Failed to mount image: No suitable os-release/extension-release file in image found.");
2334 if (r == -EUNATCH)
2335 return log_error_errno(r, "Failed to mount image: Encrypted file system discovered, but decryption not requested.");
2336 if (r == -EUCLEAN)
2337 return log_error_errno(r, "Failed to mount image: File system check on image failed.");
2338 if (r == -EBUSY)
2339 return log_error_errno(r, "Failed to mount image: File system already mounted elsewhere.");
2340 if (r == -EAFNOSUPPORT)
2341 return log_error_errno(r, "Failed to mount image: File system type not supported or not known.");
2342 if (r == -EIDRM)
2343 return log_error_errno(r, "Failed to mount image: File system is too uncommon, refused.");
2344 if (r < 0)
2345 return log_error_errno(r, "Failed to mount image: %m");
2346
2347 return r;
2348 }
2349
2350 #if HAVE_LIBCRYPTSETUP
2351 struct DecryptedPartition {
2352 struct crypt_device *device;
2353 char *name;
2354 bool relinquished;
2355 };
2356 #endif
2357
2358 typedef struct DecryptedPartition DecryptedPartition;
2359
2360 struct DecryptedImage {
2361 unsigned n_ref;
2362 DecryptedPartition *decrypted;
2363 size_t n_decrypted;
2364 };
2365
2366 static DecryptedImage* decrypted_image_free(DecryptedImage *d) {
2367 #if HAVE_LIBCRYPTSETUP
2368 int r;
2369
2370 if (!d)
2371 return NULL;
2372
2373 for (size_t i = 0; i < d->n_decrypted; i++) {
2374 DecryptedPartition *p = d->decrypted + i;
2375
2376 if (p->device && p->name && !p->relinquished) {
2377 _cleanup_free_ char *node = NULL;
2378
2379 node = path_join("/dev/mapper", p->name);
2380 if (node) {
2381 r = btrfs_forget_device(node);
2382 if (r < 0 && r != -ENOENT)
2383 log_debug_errno(r, "Failed to forget btrfs device %s, ignoring: %m", node);
2384 } else
2385 log_oom_debug();
2386
2387 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
2388 r = sym_crypt_deactivate_by_name(p->device, p->name, CRYPT_DEACTIVATE_DEFERRED);
2389 if (r < 0)
2390 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
2391 }
2392
2393 if (p->device)
2394 sym_crypt_free(p->device);
2395 free(p->name);
2396 }
2397
2398 free(d->decrypted);
2399 free(d);
2400 #endif
2401 return NULL;
2402 }
2403
2404 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage, decrypted_image, decrypted_image_free);
2405
2406 #if HAVE_LIBCRYPTSETUP
2407 static int decrypted_image_new(DecryptedImage **ret) {
2408 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2409
2410 assert(ret);
2411
2412 d = new(DecryptedImage, 1);
2413 if (!d)
2414 return -ENOMEM;
2415
2416 *d = (DecryptedImage) {
2417 .n_ref = 1,
2418 };
2419
2420 *ret = TAKE_PTR(d);
2421 return 0;
2422 }
2423
2424 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
2425 _cleanup_free_ char *name = NULL, *node = NULL;
2426 const char *base;
2427
2428 assert(original_node);
2429 assert(suffix);
2430 assert(ret_name);
2431 assert(ret_node);
2432
2433 base = strrchr(original_node, '/');
2434 if (!base)
2435 base = original_node;
2436 else
2437 base++;
2438 if (isempty(base))
2439 return -EINVAL;
2440
2441 name = strjoin(base, suffix);
2442 if (!name)
2443 return -ENOMEM;
2444 if (!filename_is_valid(name))
2445 return -EINVAL;
2446
2447 node = path_join(sym_crypt_get_dir(), name);
2448 if (!node)
2449 return -ENOMEM;
2450
2451 *ret_name = TAKE_PTR(name);
2452 *ret_node = TAKE_PTR(node);
2453
2454 return 0;
2455 }
2456
2457 static int decrypt_partition(
2458 DissectedPartition *m,
2459 const char *passphrase,
2460 DissectImageFlags flags,
2461 DecryptedImage *d) {
2462
2463 _cleanup_free_ char *node = NULL, *name = NULL;
2464 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2465 _cleanup_close_ int fd = -EBADF;
2466 int r;
2467
2468 assert(m);
2469 assert(d);
2470
2471 if (!m->found || !m->node || !m->fstype)
2472 return 0;
2473
2474 if (!streq(m->fstype, "crypto_LUKS"))
2475 return 0;
2476
2477 if (!passphrase)
2478 return -ENOKEY;
2479
2480 r = dlopen_cryptsetup();
2481 if (r < 0)
2482 return r;
2483
2484 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
2485 if (r < 0)
2486 return r;
2487
2488 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2489 return -ENOMEM;
2490
2491 r = sym_crypt_init(&cd, m->node);
2492 if (r < 0)
2493 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
2494
2495 cryptsetup_enable_logging(cd);
2496
2497 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
2498 if (r < 0)
2499 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
2500
2501 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
2502 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
2503 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
2504 if (r < 0) {
2505 log_debug_errno(r, "Failed to activate LUKS device: %m");
2506 return r == -EPERM ? -EKEYREJECTED : r;
2507 }
2508
2509 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2510 if (fd < 0)
2511 return log_debug_errno(errno, "Failed to open %s: %m", node);
2512
2513 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2514 .name = TAKE_PTR(name),
2515 .device = TAKE_PTR(cd),
2516 };
2517
2518 m->decrypted_node = TAKE_PTR(node);
2519 close_and_replace(m->mount_node_fd, fd);
2520
2521 return 0;
2522 }
2523
2524 static int verity_can_reuse(
2525 const VeritySettings *verity,
2526 const char *name,
2527 struct crypt_device **ret_cd) {
2528
2529 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2530 _cleanup_free_ char *root_hash_existing = NULL;
2531 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2532 struct crypt_params_verity crypt_params = {};
2533 size_t root_hash_existing_size;
2534 int r;
2535
2536 assert(verity);
2537 assert(name);
2538 assert(ret_cd);
2539
2540 r = sym_crypt_init_by_name(&cd, name);
2541 if (r < 0)
2542 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
2543
2544 cryptsetup_enable_logging(cd);
2545
2546 r = sym_crypt_get_verity_info(cd, &crypt_params);
2547 if (r < 0)
2548 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
2549
2550 root_hash_existing_size = verity->root_hash_size;
2551 root_hash_existing = malloc0(root_hash_existing_size);
2552 if (!root_hash_existing)
2553 return -ENOMEM;
2554
2555 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
2556 if (r < 0)
2557 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
2558 if (verity->root_hash_size != root_hash_existing_size ||
2559 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
2560 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
2561
2562 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2563 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2564 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2565 * signing for the new one, and vice versa. */
2566 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
2567 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
2568 #endif
2569
2570 *ret_cd = TAKE_PTR(cd);
2571 return 0;
2572 }
2573
2574 static char* dm_deferred_remove_clean(char *name) {
2575 if (!name)
2576 return NULL;
2577
2578 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
2579 return mfree(name);
2580 }
2581 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
2582
2583 static int validate_signature_userspace(const VeritySettings *verity, DissectImageFlags flags) {
2584 int r;
2585
2586 if (!FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_USERSPACE_VERITY)) {
2587 log_debug("Userspace dm-verity signature authentication disabled via flag.");
2588 return 0;
2589 }
2590
2591 r = secure_getenv_bool("SYSTEMD_ALLOW_USERSPACE_VERITY");
2592 if (r < 0 && r != -ENXIO) {
2593 log_debug_errno(r, "Failed to parse $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable, refusing userspace dm-verity signature authentication.");
2594 return 0;
2595 }
2596 if (!r) {
2597 log_debug("Userspace dm-verity signature authentication disabled via $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable.");
2598 return 0;
2599 }
2600
2601 bool b;
2602 r = proc_cmdline_get_bool("systemd.allow_userspace_verity", PROC_CMDLINE_TRUE_WHEN_MISSING, &b);
2603 if (r < 0) {
2604 log_debug_errno(r, "Failed to parse systemd.allow_userspace_verity= kernel command line option, refusing userspace dm-verity signature authentication.");
2605 return 0;
2606 }
2607 if (!b) {
2608 log_debug("Userspace dm-verity signature authentication disabled via systemd.allow_userspace_verity= kernel command line variable.");
2609 return 0;
2610 }
2611
2612 #if HAVE_OPENSSL
2613 _cleanup_(sk_X509_free_allp) STACK_OF(X509) *sk = NULL;
2614 _cleanup_strv_free_ char **certs = NULL;
2615 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
2616 _cleanup_free_ char *s = NULL;
2617 _cleanup_(BIO_freep) BIO *bio = NULL; /* 'bio' must be freed first, 's' second, hence keep this order
2618 * of declaration in place, please */
2619 const unsigned char *d;
2620
2621 assert(verity);
2622 assert(verity->root_hash);
2623 assert(verity->root_hash_sig);
2624
2625 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
2626 * userspace validation. */
2627
2628 r = conf_files_list_nulstr(&certs, ".crt", NULL, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, CONF_PATHS_NULSTR("verity.d"));
2629 if (r < 0)
2630 return log_debug_errno(r, "Failed to enumerate certificates: %m");
2631 if (strv_isempty(certs)) {
2632 log_debug("No userspace dm-verity certificates found.");
2633 return 0;
2634 }
2635
2636 d = verity->root_hash_sig;
2637 p7 = d2i_PKCS7(NULL, &d, (long) verity->root_hash_sig_size);
2638 if (!p7)
2639 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PKCS7 DER signature data.");
2640
2641 s = hexmem(verity->root_hash, verity->root_hash_size);
2642 if (!s)
2643 return log_oom_debug();
2644
2645 bio = BIO_new_mem_buf(s, strlen(s));
2646 if (!bio)
2647 return log_oom_debug();
2648
2649 sk = sk_X509_new_null();
2650 if (!sk)
2651 return log_oom_debug();
2652
2653 STRV_FOREACH(i, certs) {
2654 _cleanup_(X509_freep) X509 *c = NULL;
2655 _cleanup_fclose_ FILE *f = NULL;
2656
2657 f = fopen(*i, "re");
2658 if (!f) {
2659 log_debug_errno(errno, "Failed to open '%s', ignoring: %m", *i);
2660 continue;
2661 }
2662
2663 c = PEM_read_X509(f, NULL, NULL, NULL);
2664 if (!c) {
2665 log_debug("Failed to load X509 certificate '%s', ignoring.", *i);
2666 continue;
2667 }
2668
2669 if (sk_X509_push(sk, c) == 0)
2670 return log_oom_debug();
2671
2672 TAKE_PTR(c);
2673 }
2674
2675 r = PKCS7_verify(p7, sk, NULL, bio, NULL, PKCS7_NOINTERN|PKCS7_NOVERIFY);
2676 if (r)
2677 log_debug("Userspace PKCS#7 validation succeeded.");
2678 else
2679 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL));
2680
2681 return r;
2682 #else
2683 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2684 return 0;
2685 #endif
2686 }
2687
2688 static int do_crypt_activate_verity(
2689 struct crypt_device *cd,
2690 const char *name,
2691 const VeritySettings *verity,
2692 DissectImageFlags flags) {
2693
2694 bool check_signature;
2695 int r, k;
2696
2697 assert(cd);
2698 assert(name);
2699 assert(verity);
2700
2701 if (verity->root_hash_sig) {
2702 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2703 if (r < 0 && r != -ENXIO)
2704 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2705
2706 check_signature = r != 0;
2707 } else
2708 check_signature = false;
2709
2710 if (check_signature) {
2711
2712 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2713 /* First, if we have support for signed keys in the kernel, then try that first. */
2714 r = sym_crypt_activate_by_signed_key(
2715 cd,
2716 name,
2717 verity->root_hash,
2718 verity->root_hash_size,
2719 verity->root_hash_sig,
2720 verity->root_hash_sig_size,
2721 CRYPT_ACTIVATE_READONLY);
2722 if (r >= 0)
2723 return r;
2724
2725 log_debug_errno(r, "Validation of dm-verity signature failed via the kernel, trying userspace validation instead: %m");
2726 #else
2727 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.",
2728 program_invocation_short_name);
2729 r = 0; /* Set for the propagation below */
2730 #endif
2731
2732 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2733 * works we'll try to activate without telling the kernel the signature. */
2734
2735 /* Preferably propagate the original kernel error, so that the fallback logic can work,
2736 * as the device-mapper is finicky around concurrent activations of the same volume */
2737 k = validate_signature_userspace(verity, flags);
2738 if (k < 0)
2739 return r < 0 ? r : k;
2740 if (k == 0)
2741 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(ENOKEY),
2742 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2743 }
2744
2745 return sym_crypt_activate_by_volume_key(
2746 cd,
2747 name,
2748 verity->root_hash,
2749 verity->root_hash_size,
2750 CRYPT_ACTIVATE_READONLY);
2751 }
2752
2753 static usec_t verity_timeout(void) {
2754 usec_t t = 100 * USEC_PER_MSEC;
2755 const char *e;
2756 int r;
2757
2758 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2759 * Let's make the timeout configurable. */
2760
2761 e = getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2762 if (!e)
2763 return t;
2764
2765 r = parse_sec(e, &t);
2766 if (r < 0)
2767 log_debug_errno(r,
2768 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2769 "using the default timeout (%s).",
2770 FORMAT_TIMESPAN(t, USEC_PER_MSEC));
2771
2772 return t;
2773 }
2774
2775 static int verity_partition(
2776 PartitionDesignator designator,
2777 DissectedPartition *m,
2778 DissectedPartition *v,
2779 const VeritySettings *verity,
2780 DissectImageFlags flags,
2781 DecryptedImage *d) {
2782
2783 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2784 _cleanup_free_ char *node = NULL, *name = NULL;
2785 _cleanup_close_ int mount_node_fd = -EBADF;
2786 int r;
2787
2788 assert(m);
2789 assert(v || (verity && verity->data_path));
2790
2791 if (!verity || !verity->root_hash)
2792 return 0;
2793 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2794 (verity->designator == designator)))
2795 return 0;
2796
2797 if (!m->found || !m->node || !m->fstype)
2798 return 0;
2799 if (!verity->data_path) {
2800 if (!v->found || !v->node || !v->fstype)
2801 return 0;
2802
2803 if (!streq(v->fstype, "DM_verity_hash"))
2804 return 0;
2805 }
2806
2807 r = dlopen_cryptsetup();
2808 if (r < 0)
2809 return r;
2810
2811 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2812 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2813 _cleanup_free_ char *root_hash_encoded = NULL;
2814
2815 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
2816 if (!root_hash_encoded)
2817 return -ENOMEM;
2818
2819 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2820 } else
2821 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
2822 if (r < 0)
2823 return r;
2824
2825 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
2826 if (r < 0)
2827 return r;
2828
2829 cryptsetup_enable_logging(cd);
2830
2831 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
2832 if (r < 0)
2833 return r;
2834
2835 r = sym_crypt_set_data_device(cd, m->node);
2836 if (r < 0)
2837 return r;
2838
2839 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2840 return -ENOMEM;
2841
2842 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2843 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2844 * retry a few times before giving up. */
2845 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
2846 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
2847 _cleanup_(sym_crypt_freep) struct crypt_device *existing_cd = NULL;
2848 _cleanup_close_ int fd = -EBADF;
2849
2850 /* First, check if the device already exists. */
2851 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2852 if (fd < 0 && !ERRNO_IS_DEVICE_ABSENT(errno))
2853 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2854 if (fd >= 0)
2855 goto check; /* The device already exists. Let's check it. */
2856
2857 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2858 r = do_crypt_activate_verity(cd, name, verity, flags);
2859 if (r >= 0)
2860 goto try_open; /* The device is activated. Let's open it. */
2861 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2862 * There's no way to distinguish this situation from a genuine error due to invalid
2863 * parameters, so immediately fall back to activating the device with a unique name.
2864 * Improvements in libcrypsetup can ensure this never happens:
2865 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2866 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2867 break;
2868 /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again if
2869 * sharing is enabled. */
2870 if (r == -ENODEV && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2871 goto try_again;
2872 if (!IN_SET(r,
2873 -EEXIST, /* Volume has already been opened and ready to be used. */
2874 -EBUSY /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2875 return log_debug_errno(r, "Failed to activate verity device %s: %m", node);
2876
2877 check:
2878 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2879 r = dm_deferred_remove_cancel(name);
2880 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2881 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2882 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2883 if (IN_SET(r, -EBUSY, -ENXIO))
2884 goto try_again;
2885 if (r < 0)
2886 return log_debug_errno(r, "Failed to disable automated deferred removal for verity device %s: %m", node);
2887
2888 restore_deferred_remove = strdup(name);
2889 if (!restore_deferred_remove)
2890 return log_oom_debug();
2891
2892 r = verity_can_reuse(verity, name, &existing_cd);
2893 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2894 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2895 break;
2896 if (IN_SET(r,
2897 -ENOENT, /* Removed?? */
2898 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2899 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2900 goto try_again;
2901 if (r < 0)
2902 return log_debug_errno(r, "Failed to check if existing verity device %s can be reused: %m", node);
2903
2904 if (fd < 0) {
2905 /* devmapper might say that the device exists, but the devlink might not yet have been
2906 * created. Check and wait for the udev event in that case. */
2907 r = device_wait_for_devlink(node, "block", verity_timeout(), NULL);
2908 /* Fallback to activation with a unique device if it's taking too long */
2909 if (r == -ETIMEDOUT && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2910 break;
2911 if (r < 0)
2912 return log_debug_errno(r, "Failed to wait device node symlink %s: %m", node);
2913 }
2914
2915 try_open:
2916 if (fd < 0) {
2917 /* Now, the device is activated and devlink is created. Let's open it. */
2918 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2919 if (fd < 0) {
2920 if (!ERRNO_IS_DEVICE_ABSENT(errno))
2921 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2922
2923 /* The device has already been removed?? */
2924 goto try_again;
2925 }
2926 }
2927
2928 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2929 restore_deferred_remove = mfree(restore_deferred_remove);
2930
2931 mount_node_fd = TAKE_FD(fd);
2932 if (existing_cd)
2933 crypt_free_and_replace(cd, existing_cd);
2934
2935 goto success;
2936
2937 try_again:
2938 /* Device is being removed by another process. Let's wait for a while. */
2939 (void) usleep_safe(2 * USEC_PER_MSEC);
2940 }
2941
2942 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2943 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2944 /* Before trying to activate with unique name, we need to free crypt_device object.
2945 * Otherwise, we get error from libcryptsetup like the following:
2946 * ------
2947 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2948 * ------
2949 */
2950 sym_crypt_free(cd);
2951 cd = NULL;
2952 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2953 }
2954
2955 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All attempts to activate verity device %s failed.", name);
2956
2957 success:
2958 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2959 .name = TAKE_PTR(name),
2960 .device = TAKE_PTR(cd),
2961 };
2962
2963 m->decrypted_node = TAKE_PTR(node);
2964 close_and_replace(m->mount_node_fd, mount_node_fd);
2965
2966 return 0;
2967 }
2968 #endif
2969
2970 int dissected_image_decrypt(
2971 DissectedImage *m,
2972 const char *passphrase,
2973 const VeritySettings *verity,
2974 DissectImageFlags flags) {
2975
2976 #if HAVE_LIBCRYPTSETUP
2977 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2978 int r;
2979 #endif
2980
2981 assert(m);
2982 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
2983
2984 /* Returns:
2985 *
2986 * = 0 → There was nothing to decrypt
2987 * > 0 → Decrypted successfully
2988 * -ENOKEY → There's something to decrypt but no key was supplied
2989 * -EKEYREJECTED → Passed key was not correct
2990 * -EBUSY → Generic Verity error (kernel is not very explanatory)
2991 */
2992
2993 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
2994 return -EINVAL;
2995
2996 if (!m->encrypted && !m->verity_ready)
2997 return 0;
2998
2999 #if HAVE_LIBCRYPTSETUP
3000 r = decrypted_image_new(&d);
3001 if (r < 0)
3002 return r;
3003
3004 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
3005 DissectedPartition *p = m->partitions + i;
3006 PartitionDesignator k;
3007
3008 if (!p->found)
3009 continue;
3010
3011 r = decrypt_partition(p, passphrase, flags, d);
3012 if (r < 0)
3013 return r;
3014
3015 k = partition_verity_of(i);
3016 if (k >= 0) {
3017 flags |= getenv_bool("SYSTEMD_VERITY_SHARING") != 0 ? DISSECT_IMAGE_VERITY_SHARE : 0;
3018
3019 r = verity_partition(i, p, m->partitions + k, verity, flags, d);
3020 if (r < 0)
3021 return r;
3022 }
3023
3024 if (!p->decrypted_fstype && p->mount_node_fd >= 0 && p->decrypted_node) {
3025 r = probe_filesystem_full(p->mount_node_fd, p->decrypted_node, 0, UINT64_MAX, &p->decrypted_fstype);
3026 if (r < 0 && r != -EUCLEAN)
3027 return r;
3028 }
3029 }
3030
3031 m->decrypted_image = TAKE_PTR(d);
3032
3033 return 1;
3034 #else
3035 return -EOPNOTSUPP;
3036 #endif
3037 }
3038
3039 int dissected_image_decrypt_interactively(
3040 DissectedImage *m,
3041 const char *passphrase,
3042 const VeritySettings *verity,
3043 DissectImageFlags flags) {
3044
3045 _cleanup_strv_free_erase_ char **z = NULL;
3046 int n = 3, r;
3047
3048 if (passphrase)
3049 n--;
3050
3051 for (;;) {
3052 r = dissected_image_decrypt(m, passphrase, verity, flags);
3053 if (r >= 0)
3054 return r;
3055 if (r == -EKEYREJECTED)
3056 log_error_errno(r, "Incorrect passphrase, try again!");
3057 else if (r != -ENOKEY)
3058 return log_error_errno(r, "Failed to decrypt image: %m");
3059
3060 if (--n < 0)
3061 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
3062 "Too many retries.");
3063
3064 z = strv_free_erase(z);
3065
3066 static const AskPasswordRequest req = {
3067 .message = "Please enter image passphrase:",
3068 .id = "dissect",
3069 .keyring = "dissect",
3070 .credential = "dissect.passphrase",
3071 };
3072
3073 r = ask_password_auto(&req, USEC_INFINITY, /* flags= */ 0, &z);
3074 if (r < 0)
3075 return log_error_errno(r, "Failed to query for passphrase: %m");
3076
3077 passphrase = z[0];
3078 }
3079 }
3080
3081 static int decrypted_image_relinquish(DecryptedImage *d) {
3082 assert(d);
3083
3084 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
3085 * boolean so that we don't clean it up ourselves either anymore */
3086
3087 #if HAVE_LIBCRYPTSETUP
3088 int r;
3089
3090 for (size_t i = 0; i < d->n_decrypted; i++) {
3091 DecryptedPartition *p = d->decrypted + i;
3092
3093 if (p->relinquished)
3094 continue;
3095
3096 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
3097 if (r < 0)
3098 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
3099
3100 p->relinquished = true;
3101 }
3102 #endif
3103
3104 return 0;
3105 }
3106
3107 int dissected_image_relinquish(DissectedImage *m) {
3108 int r;
3109
3110 assert(m);
3111
3112 if (m->decrypted_image) {
3113 r = decrypted_image_relinquish(m->decrypted_image);
3114 if (r < 0)
3115 return r;
3116 }
3117
3118 if (m->loop)
3119 loop_device_relinquish(m->loop);
3120
3121 return 0;
3122 }
3123
3124 static char *build_auxiliary_path(const char *image, const char *suffix) {
3125 const char *e;
3126 char *n;
3127
3128 assert(image);
3129 assert(suffix);
3130
3131 e = endswith(image, ".raw");
3132 if (!e)
3133 return strjoin(e, suffix);
3134
3135 n = new(char, e - image + strlen(suffix) + 1);
3136 if (!n)
3137 return NULL;
3138
3139 strcpy(mempcpy(n, image, e - image), suffix);
3140 return n;
3141 }
3142
3143 void verity_settings_done(VeritySettings *v) {
3144 assert(v);
3145
3146 v->root_hash = mfree(v->root_hash);
3147 v->root_hash_size = 0;
3148
3149 v->root_hash_sig = mfree(v->root_hash_sig);
3150 v->root_hash_sig_size = 0;
3151
3152 v->data_path = mfree(v->data_path);
3153 }
3154
3155 int verity_settings_load(
3156 VeritySettings *verity,
3157 const char *image,
3158 const char *root_hash_path,
3159 const char *root_hash_sig_path) {
3160
3161 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
3162 size_t root_hash_size = 0, root_hash_sig_size = 0;
3163 _cleanup_free_ char *verity_data_path = NULL;
3164 PartitionDesignator designator;
3165 int r;
3166
3167 assert(verity);
3168 assert(image);
3169 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
3170
3171 /* If we are asked to load the root hash for a device node, exit early */
3172 if (is_device_path(image))
3173 return 0;
3174
3175 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIDECAR");
3176 if (r < 0 && r != -ENXIO)
3177 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
3178 if (r == 0)
3179 return 0;
3180
3181 designator = verity->designator;
3182
3183 /* We only fill in what isn't already filled in */
3184
3185 if (!verity->root_hash) {
3186 _cleanup_free_ char *text = NULL;
3187
3188 if (root_hash_path) {
3189 /* If explicitly specified it takes precedence */
3190 r = read_one_line_file(root_hash_path, &text);
3191 if (r < 0)
3192 return r;
3193
3194 if (designator < 0)
3195 designator = PARTITION_ROOT;
3196 } else {
3197 /* Otherwise look for xattr and separate file, and first for the data for root and if
3198 * that doesn't exist for /usr */
3199
3200 if (designator < 0 || designator == PARTITION_ROOT) {
3201 r = getxattr_malloc(image, "user.verity.roothash", &text);
3202 if (r < 0) {
3203 _cleanup_free_ char *p = NULL;
3204
3205 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
3206 return r;
3207
3208 p = build_auxiliary_path(image, ".roothash");
3209 if (!p)
3210 return -ENOMEM;
3211
3212 r = read_one_line_file(p, &text);
3213 if (r < 0 && r != -ENOENT)
3214 return r;
3215 }
3216
3217 if (text)
3218 designator = PARTITION_ROOT;
3219 }
3220
3221 if (!text && (designator < 0 || designator == PARTITION_USR)) {
3222 /* So in the "roothash" xattr/file name above the "root" of course primarily
3223 * refers to the root of the Verity Merkle tree. But coincidentally it also
3224 * is the hash for the *root* file system, i.e. the "root" neatly refers to
3225 * two distinct concepts called "root". Taking benefit of this happy
3226 * coincidence we call the file with the root hash for the /usr/ file system
3227 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
3228 * confusing. We thus drop the reference to the root of the Merkle tree, and
3229 * just indicate which file system it's about. */
3230 r = getxattr_malloc(image, "user.verity.usrhash", &text);
3231 if (r < 0) {
3232 _cleanup_free_ char *p = NULL;
3233
3234 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
3235 return r;
3236
3237 p = build_auxiliary_path(image, ".usrhash");
3238 if (!p)
3239 return -ENOMEM;
3240
3241 r = read_one_line_file(p, &text);
3242 if (r < 0 && r != -ENOENT)
3243 return r;
3244 }
3245
3246 if (text)
3247 designator = PARTITION_USR;
3248 }
3249 }
3250
3251 if (text) {
3252 r = unhexmem(text, &root_hash, &root_hash_size);
3253 if (r < 0)
3254 return r;
3255 if (root_hash_size < sizeof(sd_id128_t))
3256 return -EINVAL;
3257 }
3258 }
3259
3260 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
3261 if (root_hash_sig_path) {
3262 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
3263 if (r < 0 && r != -ENOENT)
3264 return r;
3265
3266 if (designator < 0)
3267 designator = PARTITION_ROOT;
3268 } else {
3269 if (designator < 0 || designator == PARTITION_ROOT) {
3270 _cleanup_free_ char *p = NULL;
3271
3272 /* Follow naming convention recommended by the relevant RFC:
3273 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
3274 p = build_auxiliary_path(image, ".roothash.p7s");
3275 if (!p)
3276 return -ENOMEM;
3277
3278 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
3279 if (r < 0 && r != -ENOENT)
3280 return r;
3281 if (r >= 0)
3282 designator = PARTITION_ROOT;
3283 }
3284
3285 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
3286 _cleanup_free_ char *p = NULL;
3287
3288 p = build_auxiliary_path(image, ".usrhash.p7s");
3289 if (!p)
3290 return -ENOMEM;
3291
3292 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
3293 if (r < 0 && r != -ENOENT)
3294 return r;
3295 if (r >= 0)
3296 designator = PARTITION_USR;
3297 }
3298 }
3299
3300 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
3301 return -EINVAL;
3302 }
3303
3304 if (!verity->data_path) {
3305 _cleanup_free_ char *p = NULL;
3306
3307 p = build_auxiliary_path(image, ".verity");
3308 if (!p)
3309 return -ENOMEM;
3310
3311 if (access(p, F_OK) < 0) {
3312 if (errno != ENOENT)
3313 return -errno;
3314 } else
3315 verity_data_path = TAKE_PTR(p);
3316 }
3317
3318 if (root_hash) {
3319 verity->root_hash = TAKE_PTR(root_hash);
3320 verity->root_hash_size = root_hash_size;
3321 }
3322
3323 if (root_hash_sig) {
3324 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
3325 verity->root_hash_sig_size = root_hash_sig_size;
3326 }
3327
3328 if (verity_data_path)
3329 verity->data_path = TAKE_PTR(verity_data_path);
3330
3331 if (verity->designator < 0)
3332 verity->designator = designator;
3333
3334 return 1;
3335 }
3336
3337 int dissected_image_load_verity_sig_partition(
3338 DissectedImage *m,
3339 int fd,
3340 VeritySettings *verity) {
3341
3342 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
3343 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
3344 size_t root_hash_size, root_hash_sig_size;
3345 _cleanup_free_ char *buf = NULL;
3346 PartitionDesignator d;
3347 DissectedPartition *p;
3348 JsonVariant *rh, *sig;
3349 ssize_t n;
3350 char *e;
3351 int r;
3352
3353 assert(m);
3354 assert(fd >= 0);
3355 assert(verity);
3356
3357 if (verity->root_hash && verity->root_hash_sig) /* Already loaded? */
3358 return 0;
3359
3360 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_EMBEDDED");
3361 if (r < 0 && r != -ENXIO)
3362 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
3363 if (r == 0)
3364 return 0;
3365
3366 d = partition_verity_sig_of(verity->designator < 0 ? PARTITION_ROOT : verity->designator);
3367 assert(d >= 0);
3368
3369 p = m->partitions + d;
3370 if (!p->found)
3371 return 0;
3372 if (p->offset == UINT64_MAX || p->size == UINT64_MAX)
3373 return -EINVAL;
3374
3375 if (p->size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
3376 return log_debug_errno(SYNTHETIC_ERRNO(EFBIG), "Verity signature partition is larger than 4M, refusing.");
3377
3378 buf = new(char, p->size+1);
3379 if (!buf)
3380 return -ENOMEM;
3381
3382 n = pread(fd, buf, p->size, p->offset);
3383 if (n < 0)
3384 return -ENOMEM;
3385 if ((uint64_t) n != p->size)
3386 return -EIO;
3387
3388 e = memchr(buf, 0, p->size);
3389 if (e) {
3390 /* If we found a NUL byte then the rest of the data must be NUL too */
3391 if (!memeqzero(e, p->size - (e - buf)))
3392 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
3393 } else
3394 buf[p->size] = 0;
3395
3396 r = json_parse(buf, 0, &v, NULL, NULL);
3397 if (r < 0)
3398 return log_debug_errno(r, "Failed to parse signature JSON data: %m");
3399
3400 rh = json_variant_by_key(v, "rootHash");
3401 if (!rh)
3402 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
3403 if (!json_variant_is_string(rh))
3404 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'rootHash' field of signature JSON object is not a string.");
3405
3406 r = unhexmem(json_variant_string(rh), &root_hash, &root_hash_size);
3407 if (r < 0)
3408 return log_debug_errno(r, "Failed to parse root hash field: %m");
3409
3410 /* Check if specified root hash matches if it is specified */
3411 if (verity->root_hash &&
3412 memcmp_nn(verity->root_hash, verity->root_hash_size, root_hash, root_hash_size) != 0) {
3413 _cleanup_free_ char *a = NULL, *b = NULL;
3414
3415 a = hexmem(root_hash, root_hash_size);
3416 b = hexmem(verity->root_hash, verity->root_hash_size);
3417
3418 return log_debug_errno(r, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a), strna(b));
3419 }
3420
3421 sig = json_variant_by_key(v, "signature");
3422 if (!sig)
3423 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
3424 if (!json_variant_is_string(sig))
3425 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'signature' field of signature JSON object is not a string.");
3426
3427 r = unbase64mem(json_variant_string(sig), &root_hash_sig, &root_hash_sig_size);
3428 if (r < 0)
3429 return log_debug_errno(r, "Failed to parse signature field: %m");
3430
3431 free_and_replace(verity->root_hash, root_hash);
3432 verity->root_hash_size = root_hash_size;
3433
3434 free_and_replace(verity->root_hash_sig, root_hash_sig);
3435 verity->root_hash_sig_size = root_hash_sig_size;
3436
3437 return 1;
3438 }
3439
3440 int dissected_image_acquire_metadata(
3441 DissectedImage *m,
3442 int userns_fd,
3443 DissectImageFlags extra_flags) {
3444
3445 enum {
3446 META_HOSTNAME,
3447 META_MACHINE_ID,
3448 META_MACHINE_INFO,
3449 META_OS_RELEASE,
3450 META_INITRD_RELEASE,
3451 META_SYSEXT_RELEASE,
3452 META_CONFEXT_RELEASE,
3453 META_HAS_INIT_SYSTEM,
3454 _META_MAX,
3455 };
3456
3457 static const char *const paths[_META_MAX] = {
3458 [META_HOSTNAME] = "/etc/hostname\0",
3459 [META_MACHINE_ID] = "/etc/machine-id\0",
3460 [META_MACHINE_INFO] = "/etc/machine-info\0",
3461 [META_OS_RELEASE] = "/etc/os-release\0"
3462 "/usr/lib/os-release\0",
3463 [META_INITRD_RELEASE] = "/etc/initrd-release\0"
3464 "/usr/lib/initrd-release\0",
3465 [META_SYSEXT_RELEASE] = "sysext-release\0", /* String used only for logging. */
3466 [META_CONFEXT_RELEASE] = "confext-release\0", /* ditto */
3467 [META_HAS_INIT_SYSTEM] = "has-init-system\0", /* ditto */
3468 };
3469
3470 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **initrd_release = NULL, **sysext_release = NULL, **confext_release = NULL;
3471 _cleanup_free_ char *hostname = NULL, *t = NULL;
3472 _cleanup_close_pair_ int error_pipe[2] = EBADF_PAIR;
3473 _cleanup_(sigkill_waitp) pid_t child = 0;
3474 sd_id128_t machine_id = SD_ID128_NULL;
3475 unsigned n_meta_initialized = 0;
3476 int fds[2 * _META_MAX], r, v;
3477 int has_init_system = -1;
3478 ssize_t n;
3479
3480 BLOCK_SIGNALS(SIGCHLD);
3481
3482 assert(m);
3483
3484 for (; n_meta_initialized < _META_MAX; n_meta_initialized++) {
3485 assert(paths[n_meta_initialized]);
3486
3487 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
3488 r = -errno;
3489 goto finish;
3490 }
3491 }
3492
3493 r = get_common_dissect_directory(&t);
3494 if (r < 0)
3495 goto finish;
3496
3497 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
3498 r = -errno;
3499 goto finish;
3500 }
3501
3502 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM, &child);
3503 if (r < 0)
3504 goto finish;
3505 if (r == 0) {
3506 /* Child */
3507 error_pipe[0] = safe_close(error_pipe[0]);
3508
3509 if (userns_fd < 0)
3510 r = detach_mount_namespace_harder(0, 0);
3511 else
3512 r = detach_mount_namespace_userns(userns_fd);
3513 if (r < 0) {
3514 log_debug_errno(r, "Failed to detach mount namespace: %m");
3515 goto inner_fail;
3516 }
3517
3518 r = dissected_image_mount(
3519 m,
3520 t,
3521 /* uid_shift= */ UID_INVALID,
3522 /* uid_range= */ UID_INVALID,
3523 /* userns_fd= */ -EBADF,
3524 extra_flags |
3525 DISSECT_IMAGE_READ_ONLY |
3526 DISSECT_IMAGE_MOUNT_ROOT_ONLY |
3527 DISSECT_IMAGE_USR_NO_ROOT);
3528 if (r < 0) {
3529 log_debug_errno(r, "Failed to mount dissected image: %m");
3530 goto inner_fail;
3531 }
3532
3533 for (unsigned k = 0; k < _META_MAX; k++) {
3534 _cleanup_close_ int fd = -ENOENT;
3535
3536 assert(paths[k]);
3537
3538 fds[2*k] = safe_close(fds[2*k]);
3539
3540 switch (k) {
3541
3542 case META_SYSEXT_RELEASE:
3543 if (!m->image_name)
3544 goto next;
3545
3546 /* As per the os-release spec, if the image is an extension it will have a
3547 * file named after the image name in extension-release.d/ - we use the image
3548 * name and try to resolve it with the extension-release helpers, as
3549 * sometimes the image names are mangled on deployment and do not match
3550 * anymore. Unlike other paths this is not fixed, and the image name can be
3551 * mangled on deployment, so by calling into the helper we allow a fallback
3552 * that matches on the first extension-release file found in the directory,
3553 * if one named after the image cannot be found first. */
3554 r = open_extension_release(
3555 t,
3556 IMAGE_SYSEXT,
3557 m->image_name,
3558 /* relax_extension_release_check= */ false,
3559 /* ret_path= */ NULL,
3560 &fd);
3561 if (r < 0)
3562 fd = r;
3563 break;
3564
3565 case META_CONFEXT_RELEASE:
3566 if (!m->image_name)
3567 goto next;
3568
3569 /* As above */
3570 r = open_extension_release(
3571 t,
3572 IMAGE_CONFEXT,
3573 m->image_name,
3574 /* relax_extension_release_check= */ false,
3575 /* ret_path= */ NULL,
3576 &fd);
3577 if (r < 0)
3578 fd = r;
3579
3580 break;
3581
3582 case META_HAS_INIT_SYSTEM: {
3583 bool found = false;
3584
3585 FOREACH_STRING(init,
3586 "/usr/lib/systemd/systemd", /* systemd on /usr/ merged system */
3587 "/lib/systemd/systemd", /* systemd on /usr/ non-merged systems */
3588 "/sbin/init") { /* traditional path the Linux kernel invokes */
3589
3590 r = chase(init, t, CHASE_PREFIX_ROOT, NULL, NULL);
3591 if (r < 0) {
3592 if (r != -ENOENT)
3593 log_debug_errno(r, "Failed to resolve %s, ignoring: %m", init);
3594 } else {
3595 found = true;
3596 break;
3597 }
3598 }
3599
3600 r = loop_write(fds[2*k+1], &found, sizeof(found));
3601 if (r < 0)
3602 goto inner_fail;
3603
3604 goto next;
3605 }
3606
3607 default:
3608 NULSTR_FOREACH(p, paths[k]) {
3609 fd = chase_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3610 if (fd >= 0)
3611 break;
3612 }
3613 }
3614
3615 if (fd < 0) {
3616 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
3617 goto next;
3618 }
3619
3620 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
3621 if (r < 0)
3622 goto inner_fail;
3623
3624 next:
3625 fds[2*k+1] = safe_close(fds[2*k+1]);
3626 }
3627
3628 _exit(EXIT_SUCCESS);
3629
3630 inner_fail:
3631 /* Let parent know the error */
3632 (void) write(error_pipe[1], &r, sizeof(r));
3633 _exit(EXIT_FAILURE);
3634 }
3635
3636 error_pipe[1] = safe_close(error_pipe[1]);
3637
3638 for (unsigned k = 0; k < _META_MAX; k++) {
3639 _cleanup_fclose_ FILE *f = NULL;
3640
3641 assert(paths[k]);
3642
3643 fds[2*k+1] = safe_close(fds[2*k+1]);
3644
3645 f = take_fdopen(&fds[2*k], "r");
3646 if (!f) {
3647 r = -errno;
3648 goto finish;
3649 }
3650
3651 switch (k) {
3652
3653 case META_HOSTNAME:
3654 r = read_etc_hostname_stream(f, &hostname);
3655 if (r < 0)
3656 log_debug_errno(r, "Failed to read /etc/hostname of image: %m");
3657
3658 break;
3659
3660 case META_MACHINE_ID: {
3661 _cleanup_free_ char *line = NULL;
3662
3663 r = read_line(f, LONG_LINE_MAX, &line);
3664 if (r < 0)
3665 log_debug_errno(r, "Failed to read /etc/machine-id of image: %m");
3666 else if (r == 33) {
3667 r = sd_id128_from_string(line, &machine_id);
3668 if (r < 0)
3669 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
3670 } else if (r == 0)
3671 log_debug("/etc/machine-id file of image is empty.");
3672 else if (streq(line, "uninitialized"))
3673 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3674 else
3675 log_debug("/etc/machine-id file of image has unexpected length %i.", r);
3676
3677 break;
3678 }
3679
3680 case META_MACHINE_INFO:
3681 r = load_env_file_pairs(f, "machine-info", &machine_info);
3682 if (r < 0)
3683 log_debug_errno(r, "Failed to read /etc/machine-info of image: %m");
3684
3685 break;
3686
3687 case META_OS_RELEASE:
3688 r = load_env_file_pairs(f, "os-release", &os_release);
3689 if (r < 0)
3690 log_debug_errno(r, "Failed to read OS release file of image: %m");
3691
3692 break;
3693
3694 case META_INITRD_RELEASE:
3695 r = load_env_file_pairs(f, "initrd-release", &initrd_release);
3696 if (r < 0)
3697 log_debug_errno(r, "Failed to read initrd release file of image: %m");
3698
3699 break;
3700
3701 case META_SYSEXT_RELEASE:
3702 r = load_env_file_pairs(f, "sysext-release", &sysext_release);
3703 if (r < 0)
3704 log_debug_errno(r, "Failed to read sysext release file of image: %m");
3705
3706 break;
3707
3708 case META_CONFEXT_RELEASE:
3709 r = load_env_file_pairs(f, "confext-release", &confext_release);
3710 if (r < 0)
3711 log_debug_errno(r, "Failed to read confext release file of image: %m");
3712
3713 break;
3714
3715 case META_HAS_INIT_SYSTEM: {
3716 bool b = false;
3717 size_t nr;
3718
3719 errno = 0;
3720 nr = fread(&b, 1, sizeof(b), f);
3721 if (nr != sizeof(b))
3722 log_debug_errno(errno_or_else(EIO), "Failed to read has-init-system boolean: %m");
3723 else
3724 has_init_system = b;
3725
3726 break;
3727 }}
3728 }
3729
3730 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3731 child = 0;
3732 if (r < 0)
3733 goto finish;
3734
3735 n = read(error_pipe[0], &v, sizeof(v));
3736 if (n < 0) {
3737 r = -errno;
3738 goto finish;
3739 }
3740 if (n == sizeof(v)) {
3741 r = v; /* propagate error sent to us from child */
3742 goto finish;
3743 }
3744 if (n != 0) {
3745 r = -EIO;
3746 goto finish;
3747 }
3748 if (r != EXIT_SUCCESS) {
3749 r = -EPROTO;
3750 goto finish;
3751 }
3752
3753 free_and_replace(m->hostname, hostname);
3754 m->machine_id = machine_id;
3755 strv_free_and_replace(m->machine_info, machine_info);
3756 strv_free_and_replace(m->os_release, os_release);
3757 strv_free_and_replace(m->initrd_release, initrd_release);
3758 strv_free_and_replace(m->sysext_release, sysext_release);
3759 strv_free_and_replace(m->confext_release, confext_release);
3760 m->has_init_system = has_init_system;
3761
3762 finish:
3763 for (unsigned k = 0; k < n_meta_initialized; k++)
3764 safe_close_pair(fds + 2*k);
3765
3766 return r;
3767 }
3768
3769 Architecture dissected_image_architecture(DissectedImage *img) {
3770 assert(img);
3771
3772 if (img->partitions[PARTITION_ROOT].found &&
3773 img->partitions[PARTITION_ROOT].architecture >= 0)
3774 return img->partitions[PARTITION_ROOT].architecture;
3775
3776 if (img->partitions[PARTITION_USR].found &&
3777 img->partitions[PARTITION_USR].architecture >= 0)
3778 return img->partitions[PARTITION_USR].architecture;
3779
3780 return _ARCHITECTURE_INVALID;
3781 }
3782
3783 int dissect_loop_device(
3784 LoopDevice *loop,
3785 const VeritySettings *verity,
3786 const MountOptions *mount_options,
3787 const ImagePolicy *image_policy,
3788 DissectImageFlags flags,
3789 DissectedImage **ret) {
3790
3791 #if HAVE_BLKID
3792 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
3793 int r;
3794
3795 assert(loop);
3796
3797 r = dissected_image_new(loop->backing_file ?: loop->node, &m);
3798 if (r < 0)
3799 return r;
3800
3801 m->loop = loop_device_ref(loop);
3802 m->image_size = m->loop->device_size;
3803 m->sector_size = m->loop->sector_size;
3804
3805 r = dissect_image(m, loop->fd, loop->node, verity, mount_options, image_policy, flags);
3806 if (r < 0)
3807 return r;
3808
3809 if (ret)
3810 *ret = TAKE_PTR(m);
3811
3812 return 0;
3813 #else
3814 return -EOPNOTSUPP;
3815 #endif
3816 }
3817
3818 int dissect_loop_device_and_warn(
3819 LoopDevice *loop,
3820 const VeritySettings *verity,
3821 const MountOptions *mount_options,
3822 const ImagePolicy *image_policy,
3823 DissectImageFlags flags,
3824 DissectedImage **ret) {
3825
3826 assert(loop);
3827
3828 return dissect_log_error(
3829 LOG_ERR,
3830 dissect_loop_device(loop, verity, mount_options, image_policy, flags, ret),
3831 loop->backing_file ?: loop->node,
3832 verity);
3833
3834 }
3835
3836 bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
3837 assert(image);
3838
3839 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3840 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3841 * images we only check the partition type.
3842 *
3843 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3844 * image. */
3845
3846 if (image->single_file_system)
3847 return partition_designator == PARTITION_ROOT && image->has_verity;
3848
3849 return partition_verity_of(partition_designator) >= 0;
3850 }
3851
3852 bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3853 PartitionDesignator k;
3854
3855 assert(image);
3856
3857 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3858 * works for the root partition, for others only if the associated verity partition was found. */
3859
3860 if (!image->verity_ready)
3861 return false;
3862
3863 if (image->single_file_system)
3864 return partition_designator == PARTITION_ROOT;
3865
3866 k = partition_verity_of(partition_designator);
3867 return k >= 0 && image->partitions[k].found;
3868 }
3869
3870 bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3871 PartitionDesignator k;
3872
3873 assert(image);
3874
3875 /* Checks if this partition has verity signature data available that we can use. */
3876
3877 if (!image->verity_sig_ready)
3878 return false;
3879
3880 if (image->single_file_system)
3881 return partition_designator == PARTITION_ROOT;
3882
3883 k = partition_verity_sig_of(partition_designator);
3884 return k >= 0 && image->partitions[k].found;
3885 }
3886
3887 MountOptions* mount_options_free_all(MountOptions *options) {
3888 MountOptions *m;
3889
3890 while ((m = LIST_POP(mount_options, options))) {
3891 free(m->options);
3892 free(m);
3893 }
3894
3895 return NULL;
3896 }
3897
3898 const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
3899 LIST_FOREACH(mount_options, m, options)
3900 if (designator == m->partition_designator && !isempty(m->options))
3901 return m->options;
3902
3903 return NULL;
3904 }
3905
3906 int mount_image_privately_interactively(
3907 const char *image,
3908 const ImagePolicy *image_policy,
3909 DissectImageFlags flags,
3910 char **ret_directory,
3911 int *ret_dir_fd,
3912 LoopDevice **ret_loop_device) {
3913
3914 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3915 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
3916 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3917 _cleanup_free_ char *dir = NULL;
3918 int r;
3919
3920 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3921 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3922 * easily. */
3923
3924 assert(image);
3925 assert(ret_loop_device);
3926
3927 /* We intend to mount this right-away, hence add the partitions if needed and pin them. */
3928 flags |= DISSECT_IMAGE_ADD_PARTITION_DEVICES |
3929 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
3930
3931 r = verity_settings_load(&verity, image, NULL, NULL);
3932 if (r < 0)
3933 return log_error_errno(r, "Failed to load root hash data: %m");
3934
3935 r = loop_device_make_by_path(
3936 image,
3937 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
3938 /* sector_size= */ UINT32_MAX,
3939 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
3940 LOCK_SH,
3941 &d);
3942 if (r < 0)
3943 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
3944
3945 r = dissect_loop_device_and_warn(
3946 d,
3947 &verity,
3948 /* mount_options= */ NULL,
3949 image_policy,
3950 flags,
3951 &dissected_image);
3952 if (r < 0)
3953 return r;
3954
3955 r = dissected_image_load_verity_sig_partition(dissected_image, d->fd, &verity);
3956 if (r < 0)
3957 return r;
3958
3959 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags);
3960 if (r < 0)
3961 return r;
3962
3963 r = detach_mount_namespace();
3964 if (r < 0)
3965 return log_error_errno(r, "Failed to detach mount namespace: %m");
3966
3967 r = mkdir_p("/run/systemd/mount-rootfs", 0555);
3968 if (r < 0)
3969 return log_error_errno(r, "Failed to create mount point: %m");
3970
3971 r = dissected_image_mount_and_warn(
3972 dissected_image,
3973 "/run/systemd/mount-rootfs",
3974 /* uid_shift= */ UID_INVALID,
3975 /* uid_range= */ UID_INVALID,
3976 /* userns_fd= */ -EBADF,
3977 flags);
3978 if (r < 0)
3979 return r;
3980
3981 r = loop_device_flock(d, LOCK_UN);
3982 if (r < 0)
3983 return r;
3984
3985 r = dissected_image_relinquish(dissected_image);
3986 if (r < 0)
3987 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
3988
3989 if (ret_directory) {
3990 dir = strdup("/run/systemd/mount-rootfs");
3991 if (!dir)
3992 return log_oom();
3993 }
3994
3995 if (ret_dir_fd) {
3996 _cleanup_close_ int dir_fd = -EBADF;
3997
3998 dir_fd = open("/run/systemd/mount-rootfs", O_CLOEXEC|O_DIRECTORY);
3999 if (dir_fd < 0)
4000 return log_error_errno(errno, "Failed to open mount point directory: %m");
4001
4002 *ret_dir_fd = TAKE_FD(dir_fd);
4003 }
4004
4005 if (ret_directory)
4006 *ret_directory = TAKE_PTR(dir);
4007
4008 *ret_loop_device = TAKE_PTR(d);
4009 return 0;
4010 }
4011
4012 static bool mount_options_relax_extension_release_checks(const MountOptions *options) {
4013 if (!options)
4014 return false;
4015
4016 return string_contains_word(mount_options_from_designator(options, PARTITION_ROOT), ",", "x-systemd.relax-extension-release-check") ||
4017 string_contains_word(mount_options_from_designator(options, PARTITION_USR), ",", "x-systemd.relax-extension-release-check") ||
4018 string_contains_word(options->options, ",", "x-systemd.relax-extension-release-check");
4019 }
4020
4021 int verity_dissect_and_mount(
4022 int src_fd,
4023 const char *src,
4024 const char *dest,
4025 const MountOptions *options,
4026 const ImagePolicy *image_policy,
4027 const char *required_host_os_release_id,
4028 const char *required_host_os_release_version_id,
4029 const char *required_host_os_release_sysext_level,
4030 const char *required_host_os_release_confext_level,
4031 const char *required_sysext_scope,
4032 DissectedImage **ret_image) {
4033
4034 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
4035 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
4036 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
4037 DissectImageFlags dissect_image_flags;
4038 bool relax_extension_release_check;
4039 int r;
4040
4041 assert(src);
4042 /* Verifying release metadata requires mounted image for now, so ensure the check is skipped when
4043 * opening an image without mounting it immediately (i.e.: 'dest' is NULL). */
4044 assert(!required_host_os_release_id || dest);
4045
4046 relax_extension_release_check = mount_options_relax_extension_release_checks(options);
4047
4048 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
4049 r = verity_settings_load(&verity, src, NULL, NULL);
4050 if (r < 0)
4051 return log_debug_errno(r, "Failed to load root hash: %m");
4052
4053 dissect_image_flags =
4054 (verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0) |
4055 (relax_extension_release_check ? DISSECT_IMAGE_RELAX_EXTENSION_CHECK : 0) |
4056 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
4057 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
4058 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
4059
4060 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
4061 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4062 r = loop_device_make_by_path(
4063 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
4064 /* open_flags= */ -1,
4065 /* sector_size= */ UINT32_MAX,
4066 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
4067 LOCK_SH,
4068 &loop_device);
4069 if (r < 0)
4070 return log_debug_errno(r, "Failed to create loop device for image: %m");
4071
4072 r = dissect_loop_device(
4073 loop_device,
4074 &verity,
4075 options,
4076 image_policy,
4077 dissect_image_flags,
4078 &dissected_image);
4079 /* No partition table? Might be a single-filesystem image, try again */
4080 if (!verity.data_path && r == -ENOPKG)
4081 r = dissect_loop_device(
4082 loop_device,
4083 &verity,
4084 options,
4085 image_policy,
4086 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
4087 &dissected_image);
4088 if (r < 0)
4089 return log_debug_errno(r, "Failed to dissect image: %m");
4090
4091 r = dissected_image_load_verity_sig_partition(dissected_image, loop_device->fd, &verity);
4092 if (r < 0)
4093 return r;
4094
4095 r = dissected_image_decrypt(
4096 dissected_image,
4097 NULL,
4098 &verity,
4099 dissect_image_flags);
4100 if (r < 0)
4101 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
4102
4103 if (dest) {
4104 r = mkdir_p_label(dest, 0755);
4105 if (r < 0)
4106 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
4107 r = umount_recursive(dest, 0);
4108 if (r < 0)
4109 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
4110 }
4111
4112 r = dissected_image_mount(
4113 dissected_image,
4114 dest,
4115 /* uid_shift= */ UID_INVALID,
4116 /* uid_range= */ UID_INVALID,
4117 /* userns_fd= */ -EBADF,
4118 dissect_image_flags);
4119 if (r < 0)
4120 return log_debug_errno(r, "Failed to mount image: %m");
4121
4122 r = loop_device_flock(loop_device, LOCK_UN);
4123 if (r < 0)
4124 return log_debug_errno(r, "Failed to unlock loopback device: %m");
4125
4126 /* If we got os-release values from the caller, then we need to match them with the image's
4127 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
4128 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
4129 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
4130 * then a simple match on the ID will be performed. */
4131 if (required_host_os_release_id) {
4132 _cleanup_strv_free_ char **extension_release = NULL;
4133 ImageClass class = IMAGE_SYSEXT;
4134
4135 assert(!isempty(required_host_os_release_id));
4136
4137 r = load_extension_release_pairs(dest, IMAGE_SYSEXT, dissected_image->image_name, relax_extension_release_check, &extension_release);
4138 if (r == -ENOENT) {
4139 r = load_extension_release_pairs(dest, IMAGE_CONFEXT, dissected_image->image_name, relax_extension_release_check, &extension_release);
4140 if (r >= 0)
4141 class = IMAGE_CONFEXT;
4142 }
4143 if (r < 0)
4144 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
4145
4146 r = extension_release_validate(
4147 dissected_image->image_name,
4148 required_host_os_release_id,
4149 required_host_os_release_version_id,
4150 class == IMAGE_SYSEXT ? required_host_os_release_sysext_level : required_host_os_release_confext_level,
4151 required_sysext_scope,
4152 extension_release,
4153 class);
4154 if (r == 0)
4155 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
4156 if (r < 0)
4157 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
4158 }
4159
4160 r = dissected_image_relinquish(dissected_image);
4161 if (r < 0)
4162 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
4163
4164 if (ret_image)
4165 *ret_image = TAKE_PTR(dissected_image);
4166
4167 return 0;
4168 }
4169
4170 int get_common_dissect_directory(char **ret) {
4171 _cleanup_free_ char *t = NULL;
4172 int r;
4173
4174 /* A common location we mount dissected images to. The assumption is that everyone who uses this
4175 * function runs in their own private mount namespace (with mount propagation off on /run/systemd/,
4176 * and thus can mount something here without affecting anyone else). */
4177
4178 t = strdup("/run/systemd/dissect-root");
4179 if (!t)
4180 return log_oom_debug();
4181
4182 r = mkdir_parents(t, 0755);
4183 if (r < 0)
4184 return log_debug_errno(r, "Failed to create parent dirs of mount point '%s': %m", t);
4185
4186 r = RET_NERRNO(mkdir(t, 0000)); /* It's supposed to be overmounted, hence let's make this inaccessible */
4187 if (r < 0 && r != -EEXIST)
4188 return log_debug_errno(r, "Failed to create mount point '%s': %m", t);
4189
4190 if (ret)
4191 *ret = TAKE_PTR(t);
4192
4193 return 0;
4194 }
4195
4196 #if HAVE_BLKID
4197
4198 static JSON_DISPATCH_ENUM_DEFINE(dispatch_architecture, Architecture, architecture_from_string);
4199 static JSON_DISPATCH_ENUM_DEFINE(dispatch_partition_designator, PartitionDesignator, partition_designator_from_string);
4200
4201 typedef struct PartitionFields {
4202 PartitionDesignator designator;
4203 bool rw;
4204 bool growfs;
4205 unsigned partno;
4206 Architecture architecture;
4207 sd_id128_t uuid;
4208 char *fstype;
4209 char *label;
4210 uint64_t size;
4211 uint64_t offset;
4212 unsigned fsmount_fd_idx;
4213 } PartitionFields;
4214
4215 static void partition_fields_done(PartitionFields *f) {
4216 assert(f);
4217
4218 f->fstype = mfree(f->fstype);
4219 f->label = mfree(f->label);
4220 }
4221
4222 typedef struct ReplyParameters {
4223 JsonVariant *partitions;
4224 char *image_policy;
4225 uint64_t image_size;
4226 uint32_t sector_size;
4227 sd_id128_t image_uuid;
4228 } ReplyParameters;
4229
4230 static void reply_parameters_done(ReplyParameters *p) {
4231 assert(p);
4232
4233 p->image_policy = mfree(p->image_policy);
4234 p->partitions = json_variant_unref(p->partitions);
4235 }
4236
4237 #endif
4238
4239 int mountfsd_mount_image(
4240 const char *path,
4241 int userns_fd,
4242 const ImagePolicy *image_policy,
4243 DissectImageFlags flags,
4244 DissectedImage **ret) {
4245
4246 #if HAVE_BLKID
4247 _cleanup_(reply_parameters_done) ReplyParameters p = {};
4248
4249 static const JsonDispatch dispatch_table[] = {
4250 { "partitions", JSON_VARIANT_ARRAY, json_dispatch_variant, offsetof(struct ReplyParameters, partitions), JSON_MANDATORY },
4251 { "imagePolicy", JSON_VARIANT_STRING, json_dispatch_string, offsetof(struct ReplyParameters, image_policy), 0 },
4252 { "imageSize", _JSON_VARIANT_TYPE_INVALID, json_dispatch_uint64, offsetof(struct ReplyParameters, image_size), JSON_MANDATORY },
4253 { "sectorSize", _JSON_VARIANT_TYPE_INVALID, json_dispatch_uint32, offsetof(struct ReplyParameters, sector_size), JSON_MANDATORY },
4254 { "imageUuid", JSON_VARIANT_STRING, json_dispatch_id128, offsetof(struct ReplyParameters, image_uuid), 0 },
4255 {}
4256 };
4257
4258 _cleanup_(dissected_image_unrefp) DissectedImage *di = NULL;
4259 _cleanup_close_ int image_fd = -EBADF;
4260 _cleanup_(varlink_unrefp) Varlink *vl = NULL;
4261 _cleanup_free_ char *ps = NULL;
4262 unsigned max_fd = UINT_MAX;
4263 const char *error_id;
4264 int r;
4265
4266 assert(path);
4267 assert(ret);
4268
4269 r = varlink_connect_address(&vl, "/run/systemd/io.systemd.MountFileSystem");
4270 if (r < 0)
4271 return log_error_errno(r, "Failed to connect to mountfsd: %m");
4272
4273 r = varlink_set_allow_fd_passing_input(vl, true);
4274 if (r < 0)
4275 return log_error_errno(r, "Failed to enable varlink fd passing for read: %m");
4276
4277 r = varlink_set_allow_fd_passing_output(vl, true);
4278 if (r < 0)
4279 return log_error_errno(r, "Failed to enable varlink fd passing for write: %m");
4280
4281 image_fd = open(path, O_RDONLY|O_CLOEXEC);
4282 if (image_fd < 0)
4283 return log_error_errno(errno, "Failed to open '%s': %m", path);
4284
4285 r = varlink_push_dup_fd(vl, image_fd);
4286 if (r < 0)
4287 return log_error_errno(r, "Failed to push image fd into varlink connection: %m");
4288
4289 if (userns_fd >= 0) {
4290 r = varlink_push_dup_fd(vl, userns_fd);
4291 if (r < 0)
4292 return log_error_errno(r, "Failed to push image fd into varlink connection: %m");
4293 }
4294
4295 if (image_policy) {
4296 r = image_policy_to_string(image_policy, /* simplify= */ false, &ps);
4297 if (r < 0)
4298 return log_error_errno(r, "Failed format image policy to string: %m");
4299 }
4300
4301 JsonVariant *reply = NULL;
4302 r = varlink_callb(
4303 vl,
4304 "io.systemd.MountFileSystem.MountImage",
4305 &reply,
4306 &error_id,
4307 JSON_BUILD_OBJECT(
4308 JSON_BUILD_PAIR("imageFileDescriptor", JSON_BUILD_UNSIGNED(0)),
4309 JSON_BUILD_PAIR_CONDITION(userns_fd >= 0, "userNamespaceFileDescriptor", JSON_BUILD_UNSIGNED(1)),
4310 JSON_BUILD_PAIR("readOnly", JSON_BUILD_BOOLEAN(FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_READ_ONLY))),
4311 JSON_BUILD_PAIR("growFileSystems", JSON_BUILD_BOOLEAN(FLAGS_SET(flags, DISSECT_IMAGE_GROWFS))),
4312 JSON_BUILD_PAIR_CONDITION(ps, "imagePolicy", JSON_BUILD_STRING(ps)),
4313 JSON_BUILD_PAIR("allowInteractiveAuthentication", JSON_BUILD_BOOLEAN(FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH)))));
4314 if (r < 0)
4315 return log_error_errno(r, "Failed to call MountImage() varlink call: %m");
4316 if (!isempty(error_id))
4317 return log_error_errno(varlink_error_to_errno(error_id, reply), "Failed to call MountImage() varlink call: %s", error_id);
4318
4319 r = json_dispatch(reply, dispatch_table, JSON_ALLOW_EXTENSIONS, &p);
4320 if (r < 0)
4321 return log_error_errno(r, "Failed to parse MountImage() reply: %m");
4322
4323 log_debug("Effective image policy: %s", p.image_policy);
4324
4325 JsonVariant *i;
4326 JSON_VARIANT_ARRAY_FOREACH(i, p.partitions) {
4327 _cleanup_close_ int fsmount_fd = -EBADF;
4328
4329 _cleanup_(partition_fields_done) PartitionFields pp = {
4330 .designator = _PARTITION_DESIGNATOR_INVALID,
4331 .architecture = _ARCHITECTURE_INVALID,
4332 .size = UINT64_MAX,
4333 .offset = UINT64_MAX,
4334 .fsmount_fd_idx = UINT_MAX,
4335 };
4336
4337 static const JsonDispatch partition_dispatch_table[] = {
4338 { "designator", JSON_VARIANT_STRING, dispatch_partition_designator, offsetof(struct PartitionFields, designator), JSON_MANDATORY },
4339 { "writable", JSON_VARIANT_BOOLEAN, json_dispatch_boolean, offsetof(struct PartitionFields, rw), JSON_MANDATORY },
4340 { "growFileSystem", JSON_VARIANT_BOOLEAN, json_dispatch_boolean, offsetof(struct PartitionFields, growfs), JSON_MANDATORY },
4341 { "partitionNumber", _JSON_VARIANT_TYPE_INVALID, json_dispatch_uint, offsetof(struct PartitionFields, partno), 0 },
4342 { "architecture", JSON_VARIANT_STRING, dispatch_architecture, offsetof(struct PartitionFields, architecture), 0 },
4343 { "partitionUuid", JSON_VARIANT_STRING, json_dispatch_id128, offsetof(struct PartitionFields, uuid), 0 },
4344 { "fileSystemType", JSON_VARIANT_STRING, json_dispatch_string, offsetof(struct PartitionFields, fstype), JSON_MANDATORY },
4345 { "partitionLabel", JSON_VARIANT_STRING, json_dispatch_string, offsetof(struct PartitionFields, label), 0 },
4346 { "size", _JSON_VARIANT_TYPE_INVALID, json_dispatch_uint64, offsetof(struct PartitionFields, size), JSON_MANDATORY },
4347 { "offset", _JSON_VARIANT_TYPE_INVALID, json_dispatch_uint64, offsetof(struct PartitionFields, offset), JSON_MANDATORY },
4348 { "mountFileDescriptor", _JSON_VARIANT_TYPE_INVALID, json_dispatch_uint, offsetof(struct PartitionFields, fsmount_fd_idx), JSON_MANDATORY },
4349 {}
4350 };
4351
4352 r = json_dispatch(i, partition_dispatch_table, JSON_ALLOW_EXTENSIONS, &pp);
4353 if (r < 0)
4354 return log_error_errno(r, "Failed to parse partition data: %m");
4355
4356 if (pp.fsmount_fd_idx != UINT_MAX) {
4357 if (max_fd == UINT_MAX || pp.fsmount_fd_idx > max_fd)
4358 max_fd = pp.fsmount_fd_idx;
4359
4360 fsmount_fd = varlink_take_fd(vl, pp.fsmount_fd_idx);
4361 if (fsmount_fd < 0)
4362 return fsmount_fd;
4363 }
4364
4365 assert(pp.designator >= 0);
4366
4367 if (!di) {
4368 r = dissected_image_new(path, &di);
4369 if (r < 0)
4370 return log_error_errno(r, "Failed to allocated new dissected image structure: %m");
4371 }
4372
4373 if (di->partitions[pp.designator].found)
4374 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Duplicate partition data for '%s'.", partition_designator_to_string(pp.designator));
4375
4376 di->partitions[pp.designator] = (DissectedPartition) {
4377 .found = true,
4378 .rw = pp.rw,
4379 .growfs = pp.growfs,
4380 .partno = pp.partno,
4381 .architecture = pp.architecture,
4382 .uuid = pp.uuid,
4383 .fstype = TAKE_PTR(pp.fstype),
4384 .label = TAKE_PTR(pp.label),
4385 .mount_node_fd = -EBADF,
4386 .size = pp.size,
4387 .offset = pp.offset,
4388 .fsmount_fd = TAKE_FD(fsmount_fd),
4389 };
4390 }
4391
4392 di->image_size = p.image_size;
4393 di->sector_size = p.sector_size;
4394 di->image_uuid = p.image_uuid;
4395
4396 *ret = TAKE_PTR(di);
4397 return 0;
4398 #else
4399 return -EOPNOTSUPP;
4400 #endif
4401 }