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