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