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