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