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