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