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