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