Debian Codegraph @

src/shared/dissect-image.c

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