]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
Merge pull request #16833 from JackFangXN/master
[thirdparty/systemd.git] / src / shared / dissect-image.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
5 #endif
6
7 #include <linux/dm-ioctl.h>
8 #include <linux/loop.h>
9 #include <sys/mount.h>
10 #include <sys/prctl.h>
11 #include <sys/wait.h>
12 #include <sysexits.h>
13
14 #include "sd-device.h"
15 #include "sd-id128.h"
16
17 #include "architecture.h"
18 #include "ask-password-api.h"
19 #include "blkid-util.h"
20 #include "blockdev-util.h"
21 #include "copy.h"
22 #include "crypt-util.h"
23 #include "def.h"
24 #include "device-nodes.h"
25 #include "device-util.h"
26 #include "dissect-image.h"
27 #include "dm-util.h"
28 #include "env-file.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "fsck-util.h"
33 #include "gpt.h"
34 #include "hexdecoct.h"
35 #include "hostname-util.h"
36 #include "id128-util.h"
37 #include "mkdir.h"
38 #include "mount-util.h"
39 #include "mountpoint-util.h"
40 #include "namespace-util.h"
41 #include "nulstr-util.h"
42 #include "os-util.h"
43 #include "path-util.h"
44 #include "process-util.h"
45 #include "raw-clone.h"
46 #include "signal-util.h"
47 #include "stat-util.h"
48 #include "stdio-util.h"
49 #include "string-table.h"
50 #include "string-util.h"
51 #include "strv.h"
52 #include "tmpfile-util.h"
53 #include "udev-util.h"
54 #include "user-util.h"
55 #include "xattr-util.h"
56
57 int probe_filesystem(const char *node, char **ret_fstype) {
58 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
59 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
60 * different error otherwise. */
61
62 #if HAVE_BLKID
63 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
64 const char *fstype;
65 int r;
66
67 errno = 0;
68 b = blkid_new_probe_from_filename(node);
69 if (!b)
70 return errno_or_else(ENOMEM);
71
72 blkid_probe_enable_superblocks(b, 1);
73 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
74
75 errno = 0;
76 r = blkid_do_safeprobe(b);
77 if (r == 1) {
78 log_debug("No type detected on partition %s", node);
79 goto not_found;
80 }
81 if (r == -2)
82 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
83 "Results ambiguous for partition %s", node);
84 if (r != 0)
85 return errno_or_else(EIO);
86
87 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
88
89 if (fstype) {
90 char *t;
91
92 t = strdup(fstype);
93 if (!t)
94 return -ENOMEM;
95
96 *ret_fstype = t;
97 return 1;
98 }
99
100 not_found:
101 *ret_fstype = NULL;
102 return 0;
103 #else
104 return -EOPNOTSUPP;
105 #endif
106 }
107
108 #if HAVE_BLKID
109 /* Detect RPMB and Boot partitions, which are not listed by blkid.
110 * See https://github.com/systemd/systemd/issues/5806. */
111 static bool device_is_mmc_special_partition(sd_device *d) {
112 const char *sysname;
113
114 assert(d);
115
116 if (sd_device_get_sysname(d, &sysname) < 0)
117 return false;
118
119 return startswith(sysname, "mmcblk") &&
120 (endswith(sysname, "rpmb") || endswith(sysname, "boot0") || endswith(sysname, "boot1"));
121 }
122
123 static bool device_is_block(sd_device *d) {
124 const char *ss;
125
126 assert(d);
127
128 if (sd_device_get_subsystem(d, &ss) < 0)
129 return false;
130
131 return streq(ss, "block");
132 }
133
134 static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
135 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
136 int r;
137
138 assert(d);
139 assert(ret);
140
141 r = sd_device_enumerator_new(&e);
142 if (r < 0)
143 return r;
144
145 r = sd_device_enumerator_allow_uninitialized(e);
146 if (r < 0)
147 return r;
148
149 r = sd_device_enumerator_add_match_parent(e, d);
150 if (r < 0)
151 return r;
152
153 *ret = TAKE_PTR(e);
154 return 0;
155 }
156
157 /* how many times to wait for the device nodes to appear */
158 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
159
160 static int wait_for_partitions_to_appear(
161 int fd,
162 sd_device *d,
163 unsigned num_partitions,
164 DissectImageFlags flags,
165 sd_device_enumerator **ret_enumerator) {
166
167 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
168 sd_device *q;
169 unsigned n;
170 int r;
171
172 assert(fd >= 0);
173 assert(d);
174 assert(ret_enumerator);
175
176 r = enumerator_for_parent(d, &e);
177 if (r < 0)
178 return r;
179
180 /* Count the partitions enumerated by the kernel */
181 n = 0;
182 FOREACH_DEVICE(e, q) {
183 if (sd_device_get_devnum(q, NULL) < 0)
184 continue;
185 if (!device_is_block(q))
186 continue;
187 if (device_is_mmc_special_partition(q))
188 continue;
189
190 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
191 r = device_wait_for_initialization(q, "block", USEC_INFINITY, NULL);
192 if (r < 0)
193 return r;
194 }
195
196 n++;
197 }
198
199 if (n == num_partitions + 1) {
200 *ret_enumerator = TAKE_PTR(e);
201 return 0; /* success! */
202 }
203 if (n > num_partitions + 1)
204 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
205 "blkid and kernel partition lists do not match.");
206
207 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
208 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
209 * call that waits until probing is complete. */
210
211 for (unsigned j = 0; ; j++) {
212 if (j++ > 20)
213 return -EBUSY;
214
215 if (ioctl(fd, BLKRRPART, 0) >= 0)
216 break;
217 r = -errno;
218 if (r == -EINVAL) {
219 /* If we are running on a block device that has partition scanning off, return an
220 * explicit recognizable error about this, so that callers can generate a proper
221 * message explaining the situation. */
222
223 r = blockdev_partscan_enabled(fd);
224 if (r < 0)
225 return r;
226 if (r == 0)
227 return log_debug_errno(EPROTONOSUPPORT,
228 "Device is a loop device and partition scanning is off!");
229
230 return -EINVAL; /* original error */
231 }
232 if (r != -EBUSY)
233 return r;
234
235 /* If something else has the device open, such as an udev rule, the ioctl will return
236 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
237 * and try again.
238 *
239 * This is really something they should fix in the kernel! */
240 (void) usleep(50 * USEC_PER_MSEC);
241
242 }
243
244 return -EAGAIN; /* no success yet, try again */
245 }
246
247 static int loop_wait_for_partitions_to_appear(
248 int fd,
249 sd_device *d,
250 unsigned num_partitions,
251 DissectImageFlags flags,
252 sd_device_enumerator **ret_enumerator) {
253 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
254 int r;
255
256 assert(fd >= 0);
257 assert(d);
258 assert(ret_enumerator);
259
260 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions);
261
262 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
263 r = device_wait_for_initialization(d, "block", USEC_INFINITY, &device);
264 if (r < 0)
265 return r;
266 } else
267 device = sd_device_ref(d);
268
269 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
270 r = wait_for_partitions_to_appear(fd, device, num_partitions, flags, ret_enumerator);
271 if (r != -EAGAIN)
272 return r;
273 }
274
275 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO),
276 "Kernel partitions dit not appear within %d attempts",
277 N_DEVICE_NODE_LIST_ATTEMPTS);
278 }
279
280 static void check_partition_flags(
281 const char *node,
282 unsigned long long pflags,
283 unsigned long long supported) {
284
285 assert(node);
286
287 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
288 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
289
290 if (pflags == 0)
291 return;
292
293 /* If there are other bits set, then log about it, to make things discoverable */
294 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
295 unsigned long long bit = 1ULL << i;
296 if (!FLAGS_SET(pflags, bit))
297 continue;
298
299 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
300 }
301 }
302
303 #endif
304
305 int dissect_image(
306 int fd,
307 const void *root_hash,
308 size_t root_hash_size,
309 const char *verity_data,
310 const MountOptions *mount_options,
311 DissectImageFlags flags,
312 DissectedImage **ret) {
313
314 #if HAVE_BLKID
315 sd_id128_t root_uuid = SD_ID128_NULL, verity_uuid = SD_ID128_NULL;
316 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
317 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
318 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
319 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
320 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
321 _cleanup_free_ char *generic_node = NULL;
322 sd_id128_t generic_uuid = SD_ID128_NULL;
323 const char *pttype = NULL;
324 blkid_partlist pl;
325 int r, generic_nr;
326 struct stat st;
327 sd_device *q;
328 unsigned i;
329
330 assert(fd >= 0);
331 assert(ret);
332 assert(root_hash || root_hash_size == 0);
333 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
334
335 /* Probes a disk image, and returns information about what it found in *ret.
336 *
337 * Returns -ENOPKG if no suitable partition table or file system could be found.
338 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
339
340 if (root_hash) {
341 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
342 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
343 * 128bit. */
344
345 if (root_hash_size < sizeof(sd_id128_t))
346 return -EINVAL;
347
348 memcpy(&root_uuid, root_hash, sizeof(sd_id128_t));
349 memcpy(&verity_uuid, (const uint8_t*) root_hash + root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
350
351 if (sd_id128_is_null(root_uuid))
352 return -EINVAL;
353 if (sd_id128_is_null(verity_uuid))
354 return -EINVAL;
355 }
356
357 if (fstat(fd, &st) < 0)
358 return -errno;
359
360 if (!S_ISBLK(st.st_mode))
361 return -ENOTBLK;
362
363 b = blkid_new_probe();
364 if (!b)
365 return -ENOMEM;
366
367 errno = 0;
368 r = blkid_probe_set_device(b, fd, 0, 0);
369 if (r != 0)
370 return errno_or_else(ENOMEM);
371
372 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
373 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
374 blkid_probe_enable_superblocks(b, 1);
375 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
376 }
377
378 blkid_probe_enable_partitions(b, 1);
379 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
380
381 errno = 0;
382 r = blkid_do_safeprobe(b);
383 if (IN_SET(r, -2, 1))
384 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
385 if (r != 0)
386 return errno_or_else(EIO);
387
388 m = new0(DissectedImage, 1);
389 if (!m)
390 return -ENOMEM;
391
392 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
393 if (r < 0)
394 return r;
395
396 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
397 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) ||
398 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
399 const char *usage = NULL;
400
401 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
402 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
403 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
404 const char *fstype = NULL, *options = NULL;
405
406 /* OK, we have found a file system, that's our root partition then. */
407 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
408
409 if (fstype) {
410 t = strdup(fstype);
411 if (!t)
412 return -ENOMEM;
413 }
414
415 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
416 if (r < 0)
417 return r;
418
419 m->single_file_system = true;
420 m->verity = root_hash && verity_data;
421 m->can_verity = !!verity_data;
422
423 options = mount_options_from_part(mount_options, PARTITION_ROOT);
424 if (options) {
425 o = strdup(options);
426 if (!o)
427 return -ENOMEM;
428 }
429
430 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
431 .found = true,
432 .rw = !m->verity,
433 .partno = -1,
434 .architecture = _ARCHITECTURE_INVALID,
435 .fstype = TAKE_PTR(t),
436 .node = TAKE_PTR(n),
437 .mount_options = TAKE_PTR(o),
438 };
439
440 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
441
442 /* Even on a single partition we need to wait for udev to create the
443 * /dev/block/X:Y symlink to /dev/loopZ */
444 r = loop_wait_for_partitions_to_appear(fd, d, 0, flags, &e);
445 if (r < 0)
446 return r;
447 *ret = TAKE_PTR(m);
448
449 return 0;
450 }
451 }
452
453 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
454 if (!pttype)
455 return -ENOPKG;
456
457 is_gpt = streq_ptr(pttype, "gpt");
458 is_mbr = streq_ptr(pttype, "dos");
459
460 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
461 return -ENOPKG;
462
463 errno = 0;
464 pl = blkid_probe_get_partitions(b);
465 if (!pl)
466 return errno_or_else(ENOMEM);
467
468 r = loop_wait_for_partitions_to_appear(fd, d, blkid_partlist_numof_partitions(pl), flags, &e);
469 if (r < 0)
470 return r;
471
472 FOREACH_DEVICE(e, q) {
473 unsigned long long pflags;
474 blkid_partition pp;
475 const char *node;
476 dev_t qn;
477 int nr;
478
479 r = sd_device_get_devnum(q, &qn);
480 if (r < 0)
481 continue;
482
483 if (st.st_rdev == qn)
484 continue;
485
486 if (!device_is_block(q))
487 continue;
488
489 if (device_is_mmc_special_partition(q))
490 continue;
491
492 r = sd_device_get_devname(q, &node);
493 if (r < 0)
494 continue;
495
496 pp = blkid_partlist_devno_to_partition(pl, qn);
497 if (!pp)
498 continue;
499
500 pflags = blkid_partition_get_flags(pp);
501
502 nr = blkid_partition_get_partno(pp);
503 if (nr < 0)
504 continue;
505
506 if (is_gpt) {
507 int designator = _PARTITION_DESIGNATOR_INVALID, architecture = _ARCHITECTURE_INVALID;
508 const char *stype, *sid, *fstype = NULL;
509 sd_id128_t type_id, id;
510 bool rw = true;
511
512 sid = blkid_partition_get_uuid(pp);
513 if (!sid)
514 continue;
515 if (sd_id128_from_string(sid, &id) < 0)
516 continue;
517
518 stype = blkid_partition_get_type_string(pp);
519 if (!stype)
520 continue;
521 if (sd_id128_from_string(stype, &type_id) < 0)
522 continue;
523
524 if (sd_id128_equal(type_id, GPT_HOME)) {
525
526 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
527
528 if (pflags & GPT_FLAG_NO_AUTO)
529 continue;
530
531 designator = PARTITION_HOME;
532 rw = !(pflags & GPT_FLAG_READ_ONLY);
533 } else if (sd_id128_equal(type_id, GPT_SRV)) {
534
535 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
536
537 if (pflags & GPT_FLAG_NO_AUTO)
538 continue;
539
540 designator = PARTITION_SRV;
541 rw = !(pflags & GPT_FLAG_READ_ONLY);
542 } else if (sd_id128_equal(type_id, GPT_ESP)) {
543
544 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
545 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
546 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
547
548 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
549 continue;
550
551 designator = PARTITION_ESP;
552 fstype = "vfat";
553
554 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
555
556 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
557
558 if (pflags & GPT_FLAG_NO_AUTO)
559 continue;
560
561 designator = PARTITION_XBOOTLDR;
562 rw = !(pflags & GPT_FLAG_READ_ONLY);
563 }
564 #ifdef GPT_ROOT_NATIVE
565 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
566
567 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
568
569 if (pflags & GPT_FLAG_NO_AUTO)
570 continue;
571
572 /* If a root ID is specified, ignore everything but the root id */
573 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
574 continue;
575
576 designator = PARTITION_ROOT;
577 architecture = native_architecture();
578 rw = !(pflags & GPT_FLAG_READ_ONLY);
579 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
580
581 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
582
583 if (pflags & GPT_FLAG_NO_AUTO)
584 continue;
585
586 m->can_verity = true;
587
588 /* Ignore verity unless a root hash is specified */
589 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
590 continue;
591
592 designator = PARTITION_ROOT_VERITY;
593 fstype = "DM_verity_hash";
594 architecture = native_architecture();
595 rw = false;
596 }
597 #endif
598 #ifdef GPT_ROOT_SECONDARY
599 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
600
601 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
602
603 if (pflags & GPT_FLAG_NO_AUTO)
604 continue;
605
606 /* If a root ID is specified, ignore everything but the root id */
607 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
608 continue;
609
610 designator = PARTITION_ROOT_SECONDARY;
611 architecture = SECONDARY_ARCHITECTURE;
612 rw = !(pflags & GPT_FLAG_READ_ONLY);
613 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
614
615 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
616
617 if (pflags & GPT_FLAG_NO_AUTO)
618 continue;
619
620 m->can_verity = true;
621
622 /* Ignore verity unless root has is specified */
623 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
624 continue;
625
626 designator = PARTITION_ROOT_SECONDARY_VERITY;
627 fstype = "DM_verity_hash";
628 architecture = SECONDARY_ARCHITECTURE;
629 rw = false;
630 }
631 #endif
632 else if (sd_id128_equal(type_id, GPT_SWAP)) {
633
634 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
635
636 if (pflags & GPT_FLAG_NO_AUTO)
637 continue;
638
639 designator = PARTITION_SWAP;
640 fstype = "swap";
641 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
642
643 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
644
645 if (pflags & GPT_FLAG_NO_AUTO)
646 continue;
647
648 if (generic_node)
649 multiple_generic = true;
650 else {
651 generic_nr = nr;
652 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
653 generic_uuid = id;
654 generic_node = strdup(node);
655 if (!generic_node)
656 return -ENOMEM;
657 }
658
659 } else if (sd_id128_equal(type_id, GPT_TMP)) {
660
661 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
662
663 if (pflags & GPT_FLAG_NO_AUTO)
664 continue;
665
666 designator = PARTITION_TMP;
667 rw = !(pflags & GPT_FLAG_READ_ONLY);
668
669 } else if (sd_id128_equal(type_id, GPT_VAR)) {
670
671 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
672
673 if (pflags & GPT_FLAG_NO_AUTO)
674 continue;
675
676 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
677 sd_id128_t var_uuid;
678
679 /* For /var we insist that the uuid of the partition matches the
680 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
681 * ID. Why? Unlike the other partitions /var is inherently
682 * installation specific, hence we need to be careful not to mount it
683 * in the wrong installation. By hashing the partition UUID from
684 * /etc/machine-id we can securely bind the partition to the
685 * installation. */
686
687 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
688 if (r < 0)
689 return r;
690
691 if (!sd_id128_equal(var_uuid, id)) {
692 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
693 continue;
694 }
695 }
696
697 designator = PARTITION_VAR;
698 rw = !(pflags & GPT_FLAG_READ_ONLY);
699 }
700
701 if (designator != _PARTITION_DESIGNATOR_INVALID) {
702 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
703 const char *options = NULL;
704
705 /* First one wins */
706 if (m->partitions[designator].found)
707 continue;
708
709 if (fstype) {
710 t = strdup(fstype);
711 if (!t)
712 return -ENOMEM;
713 }
714
715 n = strdup(node);
716 if (!n)
717 return -ENOMEM;
718
719 options = mount_options_from_part(mount_options, designator);
720 if (options) {
721 o = strdup(options);
722 if (!o)
723 return -ENOMEM;
724 }
725
726 m->partitions[designator] = (DissectedPartition) {
727 .found = true,
728 .partno = nr,
729 .rw = rw,
730 .architecture = architecture,
731 .node = TAKE_PTR(n),
732 .fstype = TAKE_PTR(t),
733 .uuid = id,
734 .mount_options = TAKE_PTR(o),
735 };
736 }
737
738 } else if (is_mbr) {
739
740 switch (blkid_partition_get_type(pp)) {
741
742 case 0x83: /* Linux partition */
743
744 if (pflags != 0x80) /* Bootable flag */
745 continue;
746
747 if (generic_node)
748 multiple_generic = true;
749 else {
750 generic_nr = nr;
751 generic_rw = true;
752 generic_node = strdup(node);
753 if (!generic_node)
754 return -ENOMEM;
755 }
756
757 break;
758
759 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
760 _cleanup_free_ char *n = NULL, *o = NULL;
761 sd_id128_t id = SD_ID128_NULL;
762 const char *sid, *options = NULL;
763
764 /* First one wins */
765 if (m->partitions[PARTITION_XBOOTLDR].found)
766 continue;
767
768 sid = blkid_partition_get_uuid(pp);
769 if (sid)
770 (void) sd_id128_from_string(sid, &id);
771
772 n = strdup(node);
773 if (!n)
774 return -ENOMEM;
775
776 options = mount_options_from_part(mount_options, PARTITION_XBOOTLDR);
777 if (options) {
778 o = strdup(options);
779 if (!o)
780 return -ENOMEM;
781 }
782
783 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
784 .found = true,
785 .partno = nr,
786 .rw = true,
787 .architecture = _ARCHITECTURE_INVALID,
788 .node = TAKE_PTR(n),
789 .uuid = id,
790 .mount_options = TAKE_PTR(o),
791 };
792
793 break;
794 }}
795 }
796 }
797
798 if (!m->partitions[PARTITION_ROOT].found) {
799 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
800 * either, then check if there's a single generic one, and use that. */
801
802 if (m->partitions[PARTITION_ROOT_VERITY].found)
803 return -EADDRNOTAVAIL;
804
805 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
806 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
807 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
808
809 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
810 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
811
812 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
813 _cleanup_free_ char *o = NULL;
814 const char *options = NULL;
815
816 /* If the root hash was set, then we won't fall back to a generic node, because the
817 * root hash decides. */
818 if (root_hash)
819 return -EADDRNOTAVAIL;
820
821 /* If we didn't find a generic node, then we can't fix this up either */
822 if (!generic_node)
823 return -ENXIO;
824
825 /* If we didn't find a properly marked root partition, but we did find a single suitable
826 * generic Linux partition, then use this as root partition, if the caller asked for it. */
827 if (multiple_generic)
828 return -ENOTUNIQ;
829
830 options = mount_options_from_part(mount_options, PARTITION_ROOT);
831 if (options) {
832 o = strdup(options);
833 if (!o)
834 return -ENOMEM;
835 }
836
837 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
838 .found = true,
839 .rw = generic_rw,
840 .partno = generic_nr,
841 .architecture = _ARCHITECTURE_INVALID,
842 .node = TAKE_PTR(generic_node),
843 .uuid = generic_uuid,
844 .mount_options = TAKE_PTR(o),
845 };
846 }
847 }
848
849 if (root_hash) {
850 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
851 return -EADDRNOTAVAIL;
852
853 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
854 * (which would be weird, after all the root hash should only be assigned to one pair of
855 * partitions... */
856 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
857 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
858
859 /* If we found a verity setup, then the root partition is necessarily read-only. */
860 m->partitions[PARTITION_ROOT].rw = false;
861
862 m->verity = true;
863 }
864
865 blkid_free_probe(b);
866 b = NULL;
867
868 /* Fill in file system types if we don't know them yet. */
869 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
870 DissectedPartition *p = m->partitions + i;
871
872 if (!p->found)
873 continue;
874
875 if (!p->fstype && p->node) {
876 r = probe_filesystem(p->node, &p->fstype);
877 if (r < 0 && r != -EUCLEAN)
878 return r;
879 }
880
881 if (streq_ptr(p->fstype, "crypto_LUKS"))
882 m->encrypted = true;
883
884 if (p->fstype && fstype_is_ro(p->fstype))
885 p->rw = false;
886 }
887
888 *ret = TAKE_PTR(m);
889
890 return 0;
891 #else
892 return -EOPNOTSUPP;
893 #endif
894 }
895
896 DissectedImage* dissected_image_unref(DissectedImage *m) {
897 unsigned i;
898
899 if (!m)
900 return NULL;
901
902 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
903 free(m->partitions[i].fstype);
904 free(m->partitions[i].node);
905 free(m->partitions[i].decrypted_fstype);
906 free(m->partitions[i].decrypted_node);
907 free(m->partitions[i].mount_options);
908 }
909
910 free(m->hostname);
911 strv_free(m->machine_info);
912 strv_free(m->os_release);
913
914 return mfree(m);
915 }
916
917 static int is_loop_device(const char *path) {
918 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
919 struct stat st;
920
921 assert(path);
922
923 if (stat(path, &st) < 0)
924 return -errno;
925
926 if (!S_ISBLK(st.st_mode))
927 return -ENOTBLK;
928
929 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
930 if (access(s, F_OK) < 0) {
931 if (errno != ENOENT)
932 return -errno;
933
934 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
935 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
936 if (access(s, F_OK) < 0)
937 return errno == ENOENT ? false : -errno;
938 }
939
940 return true;
941 }
942
943 static int run_fsck(const char *node, const char *fstype) {
944 int r, exit_status;
945 pid_t pid;
946
947 assert(node);
948 assert(fstype);
949
950 r = fsck_exists(fstype);
951 if (r < 0) {
952 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
953 return 0;
954 }
955 if (r == 0) {
956 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
957 return 0;
958 }
959
960 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
961 if (r < 0)
962 return log_debug_errno(r, "Failed to fork off fsck: %m");
963 if (r == 0) {
964 /* Child */
965 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
966 log_debug_errno(errno, "Failed to execl() fsck: %m");
967 _exit(FSCK_OPERATIONAL_ERROR);
968 }
969
970 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
971 if (exit_status < 0)
972 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
973
974 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
975 log_debug("fsck failed with exit status %i.", exit_status);
976
977 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
978 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
979
980 log_debug("Ignoring fsck error.");
981 }
982
983 return 0;
984 }
985
986 static int mount_partition(
987 DissectedPartition *m,
988 const char *where,
989 const char *directory,
990 uid_t uid_shift,
991 DissectImageFlags flags) {
992
993 _cleanup_free_ char *chased = NULL, *options = NULL;
994 const char *p, *node, *fstype;
995 bool rw;
996 int r;
997
998 assert(m);
999 assert(where);
1000
1001 node = m->decrypted_node ?: m->node;
1002 fstype = m->decrypted_fstype ?: m->fstype;
1003
1004 if (!m->found || !node || !fstype)
1005 return 0;
1006
1007 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this case. */
1008 if (streq_ptr(fstype, "crypto_LUKS"))
1009 return -EUNATCH;
1010
1011 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
1012
1013 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1014 r = run_fsck(node, fstype);
1015 if (r < 0)
1016 return r;
1017 }
1018
1019 if (directory) {
1020 if (!FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY)) {
1021 /* Automatically create missing mount points, if necessary. */
1022 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1023 if (r < 0)
1024 return r;
1025 }
1026
1027 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
1028 if (r < 0)
1029 return r;
1030
1031 p = chased;
1032 } else
1033 p = where;
1034
1035 /* If requested, turn on discard support. */
1036 if (fstype_can_discard(fstype) &&
1037 ((flags & DISSECT_IMAGE_DISCARD) ||
1038 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node)))) {
1039 options = strdup("discard");
1040 if (!options)
1041 return -ENOMEM;
1042 }
1043
1044 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
1045 _cleanup_free_ char *uid_option = NULL;
1046
1047 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1048 return -ENOMEM;
1049
1050 if (!strextend_with_separator(&options, ",", uid_option, NULL))
1051 return -ENOMEM;
1052 }
1053
1054 if (!isempty(m->mount_options))
1055 if (!strextend_with_separator(&options, ",", m->mount_options, NULL))
1056 return -ENOMEM;
1057
1058 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1059 r = mkdir_p(p, 0755);
1060 if (r < 0)
1061 return r;
1062 }
1063
1064 r = mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
1065 if (r < 0)
1066 return r;
1067
1068 return 1;
1069 }
1070
1071 int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1072 int r, xbootldr_mounted;
1073
1074 assert(m);
1075 assert(where);
1076
1077 /* Returns:
1078 *
1079 * -ENXIO → No root partition found
1080 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release file found
1081 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1082 * -EUCLEAN → fsck for file system failed
1083 * -EBUSY → File system already mounted/used elsewhere (kernel)
1084 */
1085
1086 if (!m->partitions[PARTITION_ROOT].found)
1087 return -ENXIO;
1088
1089 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1090 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
1091 if (r < 0)
1092 return r;
1093
1094 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
1095 r = path_is_os_tree(where);
1096 if (r < 0)
1097 return r;
1098 if (r == 0)
1099 return -EMEDIUMTYPE;
1100 }
1101 }
1102
1103 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
1104 return 0;
1105
1106 /* Mask DISSECT_IMAGE_MKDIR for all subdirs: the idea is that only the top-level mount point is
1107 * created if needed, but the image itself not modified. */
1108 flags &= ~DISSECT_IMAGE_MKDIR;
1109
1110 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
1111 if (r < 0)
1112 return r;
1113
1114 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
1115 if (r < 0)
1116 return r;
1117
1118 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, flags);
1119 if (r < 0)
1120 return r;
1121
1122 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, flags);
1123 if (r < 0)
1124 return r;
1125
1126 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, flags);
1127 if (xbootldr_mounted < 0)
1128 return xbootldr_mounted;
1129
1130 if (m->partitions[PARTITION_ESP].found) {
1131 int esp_done = false;
1132
1133 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1134 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1135
1136 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1137 if (r < 0) {
1138 if (r != -ENOENT)
1139 return r;
1140
1141 /* /efi doesn't exist. Let's see if /boot is suitable then */
1142
1143 if (!xbootldr_mounted) {
1144 _cleanup_free_ char *p = NULL;
1145
1146 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1147 if (r < 0) {
1148 if (r != -ENOENT)
1149 return r;
1150 } else if (dir_is_empty(p) > 0) {
1151 /* It exists and is an empty directory. Let's mount the ESP there. */
1152 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, flags);
1153 if (r < 0)
1154 return r;
1155
1156 esp_done = true;
1157 }
1158 }
1159 }
1160
1161 if (!esp_done) {
1162 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1163
1164 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, flags);
1165 if (r < 0)
1166 return r;
1167 }
1168 }
1169
1170 return 0;
1171 }
1172
1173 int dissected_image_mount_and_warn(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1174 int r;
1175
1176 assert(m);
1177 assert(where);
1178
1179 r = dissected_image_mount(m, where, uid_shift, flags);
1180 if (r == -ENXIO)
1181 return log_error_errno(r, "Not root file system found in image.");
1182 if (r == -EMEDIUMTYPE)
1183 return log_error_errno(r, "No suitable os-release file in image found.");
1184 if (r == -EUNATCH)
1185 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1186 if (r == -EUCLEAN)
1187 return log_error_errno(r, "File system check on image failed.");
1188 if (r == -EBUSY)
1189 return log_error_errno(r, "File system already mounted elsewhere.");
1190 if (r < 0)
1191 return log_error_errno(r, "Failed to mount image: %m");
1192
1193 return r;
1194 }
1195
1196 #if HAVE_LIBCRYPTSETUP
1197 typedef struct DecryptedPartition {
1198 struct crypt_device *device;
1199 char *name;
1200 bool relinquished;
1201 } DecryptedPartition;
1202
1203 struct DecryptedImage {
1204 DecryptedPartition *decrypted;
1205 size_t n_decrypted;
1206 size_t n_allocated;
1207 };
1208 #endif
1209
1210 DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
1211 #if HAVE_LIBCRYPTSETUP
1212 size_t i;
1213 int r;
1214
1215 if (!d)
1216 return NULL;
1217
1218 for (i = 0; i < d->n_decrypted; i++) {
1219 DecryptedPartition *p = d->decrypted + i;
1220
1221 if (p->device && p->name && !p->relinquished) {
1222 r = crypt_deactivate(p->device, p->name);
1223 if (r < 0)
1224 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1225 }
1226
1227 if (p->device)
1228 crypt_free(p->device);
1229 free(p->name);
1230 }
1231
1232 free(d);
1233 #endif
1234 return NULL;
1235 }
1236
1237 #if HAVE_LIBCRYPTSETUP
1238
1239 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1240 _cleanup_free_ char *name = NULL, *node = NULL;
1241 const char *base;
1242
1243 assert(original_node);
1244 assert(suffix);
1245 assert(ret_name);
1246 assert(ret_node);
1247
1248 base = strrchr(original_node, '/');
1249 if (!base)
1250 base = original_node;
1251 else
1252 base++;
1253 if (isempty(base))
1254 return -EINVAL;
1255
1256 name = strjoin(base, suffix);
1257 if (!name)
1258 return -ENOMEM;
1259 if (!filename_is_valid(name))
1260 return -EINVAL;
1261
1262 node = path_join(crypt_get_dir(), name);
1263 if (!node)
1264 return -ENOMEM;
1265
1266 *ret_name = TAKE_PTR(name);
1267 *ret_node = TAKE_PTR(node);
1268
1269 return 0;
1270 }
1271
1272 static int decrypt_partition(
1273 DissectedPartition *m,
1274 const char *passphrase,
1275 DissectImageFlags flags,
1276 DecryptedImage *d) {
1277
1278 _cleanup_free_ char *node = NULL, *name = NULL;
1279 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1280 int r;
1281
1282 assert(m);
1283 assert(d);
1284
1285 if (!m->found || !m->node || !m->fstype)
1286 return 0;
1287
1288 if (!streq(m->fstype, "crypto_LUKS"))
1289 return 0;
1290
1291 if (!passphrase)
1292 return -ENOKEY;
1293
1294 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1295 if (r < 0)
1296 return r;
1297
1298 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1299 return -ENOMEM;
1300
1301 r = crypt_init(&cd, m->node);
1302 if (r < 0)
1303 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
1304
1305 cryptsetup_enable_logging(cd);
1306
1307 r = crypt_load(cd, CRYPT_LUKS, NULL);
1308 if (r < 0)
1309 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
1310
1311 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1312 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1313 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
1314 if (r < 0) {
1315 log_debug_errno(r, "Failed to activate LUKS device: %m");
1316 return r == -EPERM ? -EKEYREJECTED : r;
1317 }
1318
1319 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1320 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
1321 d->n_decrypted++;
1322
1323 m->decrypted_node = TAKE_PTR(node);
1324
1325 return 0;
1326 }
1327
1328 static int verity_can_reuse(const void *root_hash, size_t root_hash_size, bool has_sig, const char *name, struct crypt_device **ret_cd) {
1329 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1330 _cleanup_free_ char *root_hash_existing = NULL;
1331 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1332 struct crypt_params_verity crypt_params = {};
1333 size_t root_hash_existing_size = root_hash_size;
1334 int r;
1335
1336 assert(ret_cd);
1337
1338 r = crypt_init_by_name(&cd, name);
1339 if (r < 0)
1340 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
1341 r = crypt_get_verity_info(cd, &crypt_params);
1342 if (r < 0)
1343 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
1344 root_hash_existing = malloc0(root_hash_size);
1345 if (!root_hash_existing)
1346 return -ENOMEM;
1347 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
1348 if (r < 0)
1349 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
1350 if (root_hash_size != root_hash_existing_size || memcmp(root_hash_existing, root_hash, root_hash_size) != 0)
1351 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
1352 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1353 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount
1354 * used the same settings, so that a previous unsigned mount will not be reused if the user
1355 * asks to use signing for the new one, and viceversa. */
1356 if (has_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
1357 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1358 #endif
1359
1360 *ret_cd = TAKE_PTR(cd);
1361 return 0;
1362 }
1363
1364 static inline void dm_deferred_remove_clean(char *name) {
1365 if (!name)
1366 return;
1367 (void) crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
1368 free(name);
1369 }
1370 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1371
1372 static int verity_partition(
1373 DissectedPartition *m,
1374 DissectedPartition *v,
1375 const void *root_hash,
1376 size_t root_hash_size,
1377 const char *verity_data,
1378 const char *root_hash_sig_path,
1379 const void *root_hash_sig,
1380 size_t root_hash_sig_size,
1381 DissectImageFlags flags,
1382 DecryptedImage *d) {
1383
1384 _cleanup_free_ char *node = NULL, *name = NULL, *hash_sig_from_file = NULL;
1385 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1386 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
1387 int r;
1388
1389 assert(m);
1390 assert(v || verity_data);
1391
1392 if (!root_hash)
1393 return 0;
1394
1395 if (!m->found || !m->node || !m->fstype)
1396 return 0;
1397 if (!verity_data) {
1398 if (!v->found || !v->node || !v->fstype)
1399 return 0;
1400
1401 if (!streq(v->fstype, "DM_verity_hash"))
1402 return 0;
1403 }
1404
1405 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
1406 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1407 _cleanup_free_ char *root_hash_encoded = NULL;
1408 root_hash_encoded = hexmem(root_hash, root_hash_size);
1409 if (!root_hash_encoded)
1410 return -ENOMEM;
1411 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
1412 } else
1413 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
1414 if (r < 0)
1415 return r;
1416
1417 if (!root_hash_sig && root_hash_sig_path) {
1418 r = read_full_file_full(AT_FDCWD, root_hash_sig_path, 0, &hash_sig_from_file, &root_hash_sig_size);
1419 if (r < 0)
1420 return r;
1421 }
1422
1423 r = crypt_init(&cd, verity_data ?: v->node);
1424 if (r < 0)
1425 return r;
1426
1427 cryptsetup_enable_logging(cd);
1428
1429 r = crypt_load(cd, CRYPT_VERITY, NULL);
1430 if (r < 0)
1431 return r;
1432
1433 r = crypt_set_data_device(cd, m->node);
1434 if (r < 0)
1435 return r;
1436
1437 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1438 return -ENOMEM;
1439
1440 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1441 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1442 * retry a few times before giving up. */
1443 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
1444 if (root_hash_sig || hash_sig_from_file) {
1445 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1446 r = crypt_activate_by_signed_key(cd, name, root_hash, root_hash_size, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, CRYPT_ACTIVATE_READONLY);
1447 #else
1448 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "activation of verity device with signature requested, but not supported by cryptsetup due to missing crypt_activate_by_signed_key()");
1449 #endif
1450 } else
1451 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
1452 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1453 * There's no way to distinguish this situation from a genuine error due to invalid
1454 * parameters, so immediately fall back to activating the device with a unique name.
1455 * Improvements in libcrypsetup can ensure this never happens: https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1456 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1457 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1458 if (!IN_SET(r,
1459 0, /* Success */
1460 -EEXIST, /* Volume is already open and ready to be used */
1461 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
1462 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
1463 return r;
1464 if (IN_SET(r, -EEXIST, -EBUSY)) {
1465 struct crypt_device *existing_cd = NULL;
1466
1467 if (!restore_deferred_remove){
1468 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1469 r = dm_deferred_remove_cancel(name);
1470 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
1471 if (r < 0 && r != -ENXIO)
1472 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
1473 if (r == 0) {
1474 restore_deferred_remove = strdup(name);
1475 if (!restore_deferred_remove)
1476 return -ENOMEM;
1477 }
1478 }
1479
1480 r = verity_can_reuse(root_hash, root_hash_size, !!root_hash_sig || !!hash_sig_from_file, name, &existing_cd);
1481 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1482 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1483 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1484 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
1485 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
1486 if (r == 0) {
1487 /* devmapper might say that the device exists, but the devlink might not yet have been
1488 * created. Check and wait for the udev event in that case. */
1489 r = device_wait_for_devlink(node, "block", 100 * USEC_PER_MSEC, NULL);
1490 /* Fallback to activation with a unique device if it's taking too long */
1491 if (r == -ETIMEDOUT)
1492 break;
1493 if (r < 0)
1494 return r;
1495
1496 if (cd)
1497 crypt_free(cd);
1498 cd = existing_cd;
1499 }
1500 }
1501 if (r == 0)
1502 break;
1503
1504 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
1505 (void) usleep(2 * USEC_PER_MSEC);
1506 }
1507
1508 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1509 * Fall back to activating it with a unique device name. */
1510 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1511 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1512
1513 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1514 restore_deferred_remove = mfree(restore_deferred_remove);
1515
1516 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1517 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
1518 d->n_decrypted++;
1519
1520 m->decrypted_node = TAKE_PTR(node);
1521
1522 return 0;
1523 }
1524 #endif
1525
1526 int dissected_image_decrypt(
1527 DissectedImage *m,
1528 const char *passphrase,
1529 const void *root_hash,
1530 size_t root_hash_size,
1531 const char *verity_data,
1532 const char *root_hash_sig_path,
1533 const void *root_hash_sig,
1534 size_t root_hash_sig_size,
1535 DissectImageFlags flags,
1536 DecryptedImage **ret) {
1537
1538 #if HAVE_LIBCRYPTSETUP
1539 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
1540 unsigned i;
1541 int r;
1542 #endif
1543
1544 assert(m);
1545 assert(root_hash || root_hash_size == 0);
1546
1547 /* Returns:
1548 *
1549 * = 0 → There was nothing to decrypt
1550 * > 0 → Decrypted successfully
1551 * -ENOKEY → There's something to decrypt but no key was supplied
1552 * -EKEYREJECTED → Passed key was not correct
1553 */
1554
1555 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1556 return -EINVAL;
1557
1558 if (!m->encrypted && !m->verity) {
1559 *ret = NULL;
1560 return 0;
1561 }
1562
1563 #if HAVE_LIBCRYPTSETUP
1564 d = new0(DecryptedImage, 1);
1565 if (!d)
1566 return -ENOMEM;
1567
1568 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1569 DissectedPartition *p = m->partitions + i;
1570 int k;
1571
1572 if (!p->found)
1573 continue;
1574
1575 r = decrypt_partition(p, passphrase, flags, d);
1576 if (r < 0)
1577 return r;
1578
1579 k = PARTITION_VERITY_OF(i);
1580 if (k >= 0) {
1581 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, verity_data, root_hash_sig_path, root_hash_sig, root_hash_sig_size, flags | DISSECT_IMAGE_VERITY_SHARE, d);
1582 if (r < 0)
1583 return r;
1584 }
1585
1586 if (!p->decrypted_fstype && p->decrypted_node) {
1587 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
1588 if (r < 0 && r != -EUCLEAN)
1589 return r;
1590 }
1591 }
1592
1593 *ret = TAKE_PTR(d);
1594
1595 return 1;
1596 #else
1597 return -EOPNOTSUPP;
1598 #endif
1599 }
1600
1601 int dissected_image_decrypt_interactively(
1602 DissectedImage *m,
1603 const char *passphrase,
1604 const void *root_hash,
1605 size_t root_hash_size,
1606 const char *verity_data,
1607 const char *root_hash_sig_path,
1608 const void *root_hash_sig,
1609 size_t root_hash_sig_size,
1610 DissectImageFlags flags,
1611 DecryptedImage **ret) {
1612
1613 _cleanup_strv_free_erase_ char **z = NULL;
1614 int n = 3, r;
1615
1616 if (passphrase)
1617 n--;
1618
1619 for (;;) {
1620 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, verity_data, root_hash_sig_path, root_hash_sig, root_hash_sig_size, flags, ret);
1621 if (r >= 0)
1622 return r;
1623 if (r == -EKEYREJECTED)
1624 log_error_errno(r, "Incorrect passphrase, try again!");
1625 else if (r != -ENOKEY)
1626 return log_error_errno(r, "Failed to decrypt image: %m");
1627
1628 if (--n < 0)
1629 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1630 "Too many retries.");
1631
1632 z = strv_free(z);
1633
1634 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
1635 if (r < 0)
1636 return log_error_errno(r, "Failed to query for passphrase: %m");
1637
1638 passphrase = z[0];
1639 }
1640 }
1641
1642 int decrypted_image_relinquish(DecryptedImage *d) {
1643
1644 #if HAVE_LIBCRYPTSETUP
1645 size_t i;
1646 int r;
1647 #endif
1648
1649 assert(d);
1650
1651 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1652 * that we don't clean it up ourselves either anymore */
1653
1654 #if HAVE_LIBCRYPTSETUP
1655 for (i = 0; i < d->n_decrypted; i++) {
1656 DecryptedPartition *p = d->decrypted + i;
1657
1658 if (p->relinquished)
1659 continue;
1660
1661 r = crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
1662 if (r < 0)
1663 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1664
1665 p->relinquished = true;
1666 }
1667 #endif
1668
1669 return 0;
1670 }
1671
1672 int verity_metadata_load(
1673 const char *image,
1674 const char *root_hash_path,
1675 void **ret_roothash,
1676 size_t *ret_roothash_size,
1677 char **ret_verity_data,
1678 char **ret_roothashsig) {
1679
1680 _cleanup_free_ char *verity_filename = NULL, *roothashsig_filename = NULL;
1681 _cleanup_free_ void *roothash_decoded = NULL;
1682 size_t roothash_decoded_size = 0;
1683 int r;
1684
1685 assert(image);
1686
1687 if (is_device_path(image)) {
1688 /* If we are asked to load the root hash for a device node, exit early */
1689 if (ret_roothash)
1690 *ret_roothash = NULL;
1691 if (ret_roothash_size)
1692 *ret_roothash_size = 0;
1693 if (ret_verity_data)
1694 *ret_verity_data = NULL;
1695 if (ret_roothashsig)
1696 *ret_roothashsig = NULL;
1697 return 0;
1698 }
1699
1700 if (ret_verity_data) {
1701 char *e;
1702
1703 verity_filename = new(char, strlen(image) + STRLEN(".verity") + 1);
1704 if (!verity_filename)
1705 return -ENOMEM;
1706 strcpy(verity_filename, image);
1707 e = endswith(verity_filename, ".raw");
1708 if (e)
1709 strcpy(e, ".verity");
1710 else
1711 strcat(verity_filename, ".verity");
1712
1713 r = access(verity_filename, F_OK);
1714 if (r < 0) {
1715 if (errno != ENOENT)
1716 return -errno;
1717 verity_filename = mfree(verity_filename);
1718 }
1719 }
1720
1721 if (ret_roothashsig) {
1722 char *e;
1723
1724 /* Follow naming convention recommended by the relevant RFC:
1725 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1726 roothashsig_filename = new(char, strlen(image) + STRLEN(".roothash.p7s") + 1);
1727 if (!roothashsig_filename)
1728 return -ENOMEM;
1729 strcpy(roothashsig_filename, image);
1730 e = endswith(roothashsig_filename, ".raw");
1731 if (e)
1732 strcpy(e, ".roothash.p7s");
1733 else
1734 strcat(roothashsig_filename, ".roothash.p7s");
1735
1736 r = access(roothashsig_filename, R_OK);
1737 if (r < 0) {
1738 if (errno != ENOENT)
1739 return -errno;
1740 roothashsig_filename = mfree(roothashsig_filename);
1741 }
1742 }
1743
1744 if (ret_roothash) {
1745 _cleanup_free_ char *text = NULL;
1746 assert(ret_roothash_size);
1747
1748 if (root_hash_path) {
1749 /* We have the path to a roothash to load and decode, eg: RootHash=/foo/bar.roothash */
1750 r = read_one_line_file(root_hash_path, &text);
1751 if (r < 0)
1752 return r;
1753 } else {
1754 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1755 if (r < 0) {
1756 char *fn, *e, *n;
1757
1758 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1759 return r;
1760
1761 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
1762 n = stpcpy(fn, image);
1763 e = endswith(fn, ".raw");
1764 if (e)
1765 n = e;
1766
1767 strcpy(n, ".roothash");
1768
1769 r = read_one_line_file(fn, &text);
1770 if (r < 0 && r != -ENOENT)
1771 return r;
1772 }
1773 }
1774
1775 if (text) {
1776 r = unhexmem(text, strlen(text), &roothash_decoded, &roothash_decoded_size);
1777 if (r < 0)
1778 return r;
1779 if (roothash_decoded_size < sizeof(sd_id128_t))
1780 return -EINVAL;
1781 }
1782 }
1783
1784 if (ret_roothash) {
1785 *ret_roothash = TAKE_PTR(roothash_decoded);
1786 *ret_roothash_size = roothash_decoded_size;
1787 }
1788 if (ret_verity_data)
1789 *ret_verity_data = TAKE_PTR(verity_filename);
1790 if (roothashsig_filename)
1791 *ret_roothashsig = TAKE_PTR(roothashsig_filename);
1792
1793 return 1;
1794 }
1795
1796 int dissected_image_acquire_metadata(DissectedImage *m) {
1797
1798 enum {
1799 META_HOSTNAME,
1800 META_MACHINE_ID,
1801 META_MACHINE_INFO,
1802 META_OS_RELEASE,
1803 _META_MAX,
1804 };
1805
1806 static const char *const paths[_META_MAX] = {
1807 [META_HOSTNAME] = "/etc/hostname\0",
1808 [META_MACHINE_ID] = "/etc/machine-id\0",
1809 [META_MACHINE_INFO] = "/etc/machine-info\0",
1810 [META_OS_RELEASE] = "/etc/os-release\0"
1811 "/usr/lib/os-release\0",
1812 };
1813
1814 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
1815 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
1816 _cleanup_(rmdir_and_freep) char *t = NULL;
1817 _cleanup_(sigkill_waitp) pid_t child = 0;
1818 sd_id128_t machine_id = SD_ID128_NULL;
1819 _cleanup_free_ char *hostname = NULL;
1820 unsigned n_meta_initialized = 0, k;
1821 int fds[2 * _META_MAX], r, v;
1822 ssize_t n;
1823
1824 BLOCK_SIGNALS(SIGCHLD);
1825
1826 assert(m);
1827
1828 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1829 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1830 r = -errno;
1831 goto finish;
1832 }
1833
1834 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1835 if (r < 0)
1836 goto finish;
1837
1838 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
1839 r = -errno;
1840 goto finish;
1841 }
1842
1843 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
1844 if (r < 0)
1845 goto finish;
1846 if (r == 0) {
1847 error_pipe[0] = safe_close(error_pipe[0]);
1848
1849 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
1850 if (r < 0) {
1851 /* Let parent know the error */
1852 (void) write(error_pipe[1], &r, sizeof(r));
1853
1854 log_debug_errno(r, "Failed to mount dissected image: %m");
1855 _exit(EXIT_FAILURE);
1856 }
1857
1858 for (k = 0; k < _META_MAX; k++) {
1859 _cleanup_close_ int fd = -ENOENT;
1860 const char *p;
1861
1862 fds[2*k] = safe_close(fds[2*k]);
1863
1864 NULSTR_FOREACH(p, paths[k]) {
1865 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
1866 if (fd >= 0)
1867 break;
1868 }
1869 if (fd < 0) {
1870 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
1871 fds[2*k+1] = safe_close(fds[2*k+1]);
1872 continue;
1873 }
1874
1875 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
1876 if (r < 0) {
1877 (void) write(error_pipe[1], &r, sizeof(r));
1878 _exit(EXIT_FAILURE);
1879 }
1880
1881 fds[2*k+1] = safe_close(fds[2*k+1]);
1882 }
1883
1884 _exit(EXIT_SUCCESS);
1885 }
1886
1887 error_pipe[1] = safe_close(error_pipe[1]);
1888
1889 for (k = 0; k < _META_MAX; k++) {
1890 _cleanup_fclose_ FILE *f = NULL;
1891
1892 fds[2*k+1] = safe_close(fds[2*k+1]);
1893
1894 f = take_fdopen(&fds[2*k], "r");
1895 if (!f) {
1896 r = -errno;
1897 goto finish;
1898 }
1899
1900 switch (k) {
1901
1902 case META_HOSTNAME:
1903 r = read_etc_hostname_stream(f, &hostname);
1904 if (r < 0)
1905 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1906
1907 break;
1908
1909 case META_MACHINE_ID: {
1910 _cleanup_free_ char *line = NULL;
1911
1912 r = read_line(f, LONG_LINE_MAX, &line);
1913 if (r < 0)
1914 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1915 else if (r == 33) {
1916 r = sd_id128_from_string(line, &machine_id);
1917 if (r < 0)
1918 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1919 } else if (r == 0)
1920 log_debug("/etc/machine-id file is empty.");
1921 else
1922 log_debug("/etc/machine-id has unexpected length %i.", r);
1923
1924 break;
1925 }
1926
1927 case META_MACHINE_INFO:
1928 r = load_env_file_pairs(f, "machine-info", &machine_info);
1929 if (r < 0)
1930 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1931
1932 break;
1933
1934 case META_OS_RELEASE:
1935 r = load_env_file_pairs(f, "os-release", &os_release);
1936 if (r < 0)
1937 log_debug_errno(r, "Failed to read OS release file: %m");
1938
1939 break;
1940 }
1941 }
1942
1943 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
1944 child = 0;
1945 if (r < 0)
1946 return r;
1947
1948 n = read(error_pipe[0], &v, sizeof(v));
1949 if (n < 0)
1950 return -errno;
1951 if (n == sizeof(v))
1952 return v; /* propagate error sent to us from child */
1953 if (n != 0)
1954 return -EIO;
1955
1956 if (r != EXIT_SUCCESS)
1957 return -EPROTO;
1958
1959 free_and_replace(m->hostname, hostname);
1960 m->machine_id = machine_id;
1961 strv_free_and_replace(m->machine_info, machine_info);
1962 strv_free_and_replace(m->os_release, os_release);
1963
1964 finish:
1965 for (k = 0; k < n_meta_initialized; k++)
1966 safe_close_pair(fds + 2*k);
1967
1968 return r;
1969 }
1970
1971 int dissect_image_and_warn(
1972 int fd,
1973 const char *name,
1974 const void *root_hash,
1975 size_t root_hash_size,
1976 const char *verity_data,
1977 const MountOptions *mount_options,
1978 DissectImageFlags flags,
1979 DissectedImage **ret) {
1980
1981 _cleanup_free_ char *buffer = NULL;
1982 int r;
1983
1984 if (!name) {
1985 r = fd_get_path(fd, &buffer);
1986 if (r < 0)
1987 return r;
1988
1989 name = buffer;
1990 }
1991
1992 r = dissect_image(fd, root_hash, root_hash_size, verity_data, mount_options, flags, ret);
1993
1994 switch (r) {
1995
1996 case -EOPNOTSUPP:
1997 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
1998
1999 case -ENOPKG:
2000 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
2001
2002 case -EADDRNOTAVAIL:
2003 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
2004
2005 case -ENOTUNIQ:
2006 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
2007
2008 case -ENXIO:
2009 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
2010
2011 case -EPROTONOSUPPORT:
2012 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
2013
2014 default:
2015 if (r < 0)
2016 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
2017
2018 return r;
2019 }
2020 }
2021
2022 bool dissected_image_can_do_verity(const DissectedImage *image, unsigned partition_designator) {
2023 if (image->single_file_system)
2024 return partition_designator == PARTITION_ROOT && image->can_verity;
2025
2026 return PARTITION_VERITY_OF(partition_designator) >= 0;
2027 }
2028
2029 bool dissected_image_has_verity(const DissectedImage *image, unsigned partition_designator) {
2030 int k;
2031
2032 if (image->single_file_system)
2033 return partition_designator == PARTITION_ROOT && image->verity;
2034
2035 k = PARTITION_VERITY_OF(partition_designator);
2036 return k >= 0 && image->partitions[k].found;
2037 }
2038
2039 MountOptions* mount_options_free_all(MountOptions *options) {
2040 MountOptions *m;
2041
2042 while ((m = options)) {
2043 LIST_REMOVE(mount_options, options, m);
2044 free(m->options);
2045 free(m);
2046 }
2047
2048 return NULL;
2049 }
2050
2051 const char* mount_options_from_part(const MountOptions *options, int designator) {
2052 MountOptions *m;
2053
2054 LIST_FOREACH(mount_options, m, (MountOptions *)options)
2055 if (designator == m->partition_designator && !isempty(m->options))
2056 return m->options;
2057
2058 return NULL;
2059 }
2060
2061 int mount_image_privately_interactively(
2062 const char *image,
2063 DissectImageFlags flags,
2064 char **ret_directory,
2065 LoopDevice **ret_loop_device,
2066 DecryptedImage **ret_decrypted_image) {
2067
2068 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2069 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2070 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2071 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
2072 _cleanup_free_ char *temp = NULL;
2073 int r;
2074
2075 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2076 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2077 * easily. */
2078
2079 assert(image);
2080 assert(ret_directory);
2081 assert(ret_loop_device);
2082 assert(ret_decrypted_image);
2083
2084 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
2085 if (r < 0)
2086 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
2087
2088 r = loop_device_make_by_path(
2089 image,
2090 FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY) ? O_RDONLY : O_RDWR,
2091 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2092 &d);
2093 if (r < 0)
2094 return log_error_errno(r, "Failed to set up loopback device: %m");
2095
2096 r = dissect_image_and_warn(d->fd, image, NULL, 0, NULL, NULL, flags, &dissected_image);
2097 if (r < 0)
2098 return r;
2099
2100 r = dissected_image_decrypt_interactively(dissected_image, NULL, NULL, 0, NULL, NULL, NULL, 0, flags, &decrypted_image);
2101 if (r < 0)
2102 return r;
2103
2104 r = detach_mount_namespace();
2105 if (r < 0)
2106 return log_error_errno(r, "Failed to detach mount namespace: %m");
2107
2108 r = mkdir_p(temp, 0700);
2109 if (r < 0)
2110 return log_error_errno(r, "Failed to create mount point: %m");
2111
2112 created_dir = TAKE_PTR(temp);
2113
2114 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, flags);
2115 if (r < 0)
2116 return r;
2117
2118 if (decrypted_image) {
2119 r = decrypted_image_relinquish(decrypted_image);
2120 if (r < 0)
2121 return log_error_errno(r, "Failed to relinquish DM devices: %m");
2122 }
2123
2124 loop_device_relinquish(d);
2125
2126 *ret_directory = TAKE_PTR(created_dir);
2127 *ret_loop_device = TAKE_PTR(d);
2128 *ret_decrypted_image = TAKE_PTR(decrypted_image);
2129
2130 return 0;
2131 }
2132
2133 static const char *const partition_designator_table[] = {
2134 [PARTITION_ROOT] = "root",
2135 [PARTITION_ROOT_SECONDARY] = "root-secondary",
2136 [PARTITION_HOME] = "home",
2137 [PARTITION_SRV] = "srv",
2138 [PARTITION_ESP] = "esp",
2139 [PARTITION_XBOOTLDR] = "xbootldr",
2140 [PARTITION_SWAP] = "swap",
2141 [PARTITION_ROOT_VERITY] = "root-verity",
2142 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
2143 [PARTITION_TMP] = "tmp",
2144 [PARTITION_VAR] = "var",
2145 };
2146
2147 DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);