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