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