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