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