]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
Merge pull request #16145 from poettering/qrcode-dlopen
[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 const MountOptions *mount_options,
312 DissectImageFlags flags,
313 DissectedImage **ret) {
314
315 #if HAVE_BLKID
316 sd_id128_t root_uuid = SD_ID128_NULL, verity_uuid = SD_ID128_NULL;
317 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
318 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
319 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
320 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
321 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
322 _cleanup_free_ char *generic_node = NULL;
323 sd_id128_t generic_uuid = SD_ID128_NULL;
324 const char *pttype = NULL;
325 blkid_partlist pl;
326 int r, generic_nr;
327 struct stat st;
328 sd_device *q;
329 unsigned i;
330
331 assert(fd >= 0);
332 assert(ret);
333 assert(root_hash || root_hash_size == 0);
334 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
335
336 /* Probes a disk image, and returns information about what it found in *ret.
337 *
338 * Returns -ENOPKG if no suitable partition table or file system could be found.
339 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
340
341 if (root_hash) {
342 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
343 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
344 * 128bit. */
345
346 if (root_hash_size < sizeof(sd_id128_t))
347 return -EINVAL;
348
349 memcpy(&root_uuid, root_hash, sizeof(sd_id128_t));
350 memcpy(&verity_uuid, (const uint8_t*) root_hash + root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
351
352 if (sd_id128_is_null(root_uuid))
353 return -EINVAL;
354 if (sd_id128_is_null(verity_uuid))
355 return -EINVAL;
356 }
357
358 if (fstat(fd, &st) < 0)
359 return -errno;
360
361 if (!S_ISBLK(st.st_mode))
362 return -ENOTBLK;
363
364 b = blkid_new_probe();
365 if (!b)
366 return -ENOMEM;
367
368 errno = 0;
369 r = blkid_probe_set_device(b, fd, 0, 0);
370 if (r != 0)
371 return errno_or_else(ENOMEM);
372
373 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
374 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
375 blkid_probe_enable_superblocks(b, 1);
376 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
377 }
378
379 blkid_probe_enable_partitions(b, 1);
380 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
381
382 errno = 0;
383 r = blkid_do_safeprobe(b);
384 if (IN_SET(r, -2, 1))
385 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
386 if (r != 0)
387 return errno_or_else(EIO);
388
389 m = new0(DissectedImage, 1);
390 if (!m)
391 return -ENOMEM;
392
393 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
394 if (r < 0)
395 return r;
396
397 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
398 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) ||
399 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
400 const char *usage = NULL;
401
402 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
403 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
404 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
405 const char *fstype = NULL, *options = NULL;
406
407 /* OK, we have found a file system, that's our root partition then. */
408 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
409
410 if (fstype) {
411 t = strdup(fstype);
412 if (!t)
413 return -ENOMEM;
414 }
415
416 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
417 if (r < 0)
418 return r;
419
420 m->single_file_system = true;
421 m->verity = root_hash && verity_data;
422 m->can_verity = !!verity_data;
423
424 options = mount_options_from_part(mount_options, 0);
425 if (options) {
426 o = strdup(options);
427 if (!o)
428 return -ENOMEM;
429 }
430
431 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
432 .found = true,
433 .rw = !m->verity,
434 .partno = -1,
435 .architecture = _ARCHITECTURE_INVALID,
436 .fstype = TAKE_PTR(t),
437 .node = TAKE_PTR(n),
438 .mount_options = TAKE_PTR(o),
439 };
440
441 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
442
443 /* Even on a single partition we need to wait for udev to create the
444 * /dev/block/X:Y symlink to /dev/loopZ */
445 r = loop_wait_for_partitions_to_appear(fd, d, 0, flags, &e);
446 if (r < 0)
447 return r;
448 *ret = TAKE_PTR(m);
449
450 return 0;
451 }
452 }
453
454 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
455 if (!pttype)
456 return -ENOPKG;
457
458 is_gpt = streq_ptr(pttype, "gpt");
459 is_mbr = streq_ptr(pttype, "dos");
460
461 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
462 return -ENOPKG;
463
464 errno = 0;
465 pl = blkid_probe_get_partitions(b);
466 if (!pl)
467 return errno_or_else(ENOMEM);
468
469 r = loop_wait_for_partitions_to_appear(fd, d, blkid_partlist_numof_partitions(pl), flags, &e);
470 if (r < 0)
471 return r;
472
473 FOREACH_DEVICE(e, q) {
474 unsigned long long pflags;
475 blkid_partition pp;
476 const char *node;
477 dev_t qn;
478 int nr;
479
480 r = sd_device_get_devnum(q, &qn);
481 if (r < 0)
482 continue;
483
484 if (st.st_rdev == qn)
485 continue;
486
487 if (!device_is_block(q))
488 continue;
489
490 if (device_is_mmc_special_partition(q))
491 continue;
492
493 r = sd_device_get_devname(q, &node);
494 if (r < 0)
495 continue;
496
497 pp = blkid_partlist_devno_to_partition(pl, qn);
498 if (!pp)
499 continue;
500
501 pflags = blkid_partition_get_flags(pp);
502
503 nr = blkid_partition_get_partno(pp);
504 if (nr < 0)
505 continue;
506
507 if (is_gpt) {
508 int designator = _PARTITION_DESIGNATOR_INVALID, architecture = _ARCHITECTURE_INVALID;
509 const char *stype, *sid, *fstype = NULL;
510 sd_id128_t type_id, id;
511 bool rw = true;
512
513 sid = blkid_partition_get_uuid(pp);
514 if (!sid)
515 continue;
516 if (sd_id128_from_string(sid, &id) < 0)
517 continue;
518
519 stype = blkid_partition_get_type_string(pp);
520 if (!stype)
521 continue;
522 if (sd_id128_from_string(stype, &type_id) < 0)
523 continue;
524
525 if (sd_id128_equal(type_id, GPT_HOME)) {
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_HOME;
533 rw = !(pflags & GPT_FLAG_READ_ONLY);
534 } else if (sd_id128_equal(type_id, GPT_SRV)) {
535
536 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
537
538 if (pflags & GPT_FLAG_NO_AUTO)
539 continue;
540
541 designator = PARTITION_SRV;
542 rw = !(pflags & GPT_FLAG_READ_ONLY);
543 } else if (sd_id128_equal(type_id, GPT_ESP)) {
544
545 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
546 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
547 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
548
549 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
550 continue;
551
552 designator = PARTITION_ESP;
553 fstype = "vfat";
554
555 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
556
557 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
558
559 if (pflags & GPT_FLAG_NO_AUTO)
560 continue;
561
562 designator = PARTITION_XBOOTLDR;
563 rw = !(pflags & GPT_FLAG_READ_ONLY);
564 }
565 #ifdef GPT_ROOT_NATIVE
566 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
567
568 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
569
570 if (pflags & GPT_FLAG_NO_AUTO)
571 continue;
572
573 /* If a root ID is specified, ignore everything but the root id */
574 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
575 continue;
576
577 designator = PARTITION_ROOT;
578 architecture = native_architecture();
579 rw = !(pflags & GPT_FLAG_READ_ONLY);
580 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
581
582 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
583
584 if (pflags & GPT_FLAG_NO_AUTO)
585 continue;
586
587 m->can_verity = true;
588
589 /* Ignore verity unless a root hash is specified */
590 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
591 continue;
592
593 designator = PARTITION_ROOT_VERITY;
594 fstype = "DM_verity_hash";
595 architecture = native_architecture();
596 rw = false;
597 }
598 #endif
599 #ifdef GPT_ROOT_SECONDARY
600 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
601
602 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
603
604 if (pflags & GPT_FLAG_NO_AUTO)
605 continue;
606
607 /* If a root ID is specified, ignore everything but the root id */
608 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
609 continue;
610
611 designator = PARTITION_ROOT_SECONDARY;
612 architecture = SECONDARY_ARCHITECTURE;
613 rw = !(pflags & GPT_FLAG_READ_ONLY);
614 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
615
616 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
617
618 if (pflags & GPT_FLAG_NO_AUTO)
619 continue;
620
621 m->can_verity = true;
622
623 /* Ignore verity unless root has is specified */
624 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
625 continue;
626
627 designator = PARTITION_ROOT_SECONDARY_VERITY;
628 fstype = "DM_verity_hash";
629 architecture = SECONDARY_ARCHITECTURE;
630 rw = false;
631 }
632 #endif
633 else if (sd_id128_equal(type_id, GPT_SWAP)) {
634
635 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
636
637 if (pflags & GPT_FLAG_NO_AUTO)
638 continue;
639
640 designator = PARTITION_SWAP;
641 fstype = "swap";
642 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
643
644 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
645
646 if (pflags & GPT_FLAG_NO_AUTO)
647 continue;
648
649 if (generic_node)
650 multiple_generic = true;
651 else {
652 generic_nr = nr;
653 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
654 generic_uuid = id;
655 generic_node = strdup(node);
656 if (!generic_node)
657 return -ENOMEM;
658 }
659
660 } else if (sd_id128_equal(type_id, GPT_TMP)) {
661
662 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
663
664 if (pflags & GPT_FLAG_NO_AUTO)
665 continue;
666
667 designator = PARTITION_TMP;
668 rw = !(pflags & GPT_FLAG_READ_ONLY);
669
670 } else if (sd_id128_equal(type_id, GPT_VAR)) {
671
672 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
673
674 if (pflags & GPT_FLAG_NO_AUTO)
675 continue;
676
677 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
678 sd_id128_t var_uuid;
679
680 /* For /var we insist that the uuid of the partition matches the
681 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
682 * ID. Why? Unlike the other partitions /var is inherently
683 * installation specific, hence we need to be careful not to mount it
684 * in the wrong installation. By hashing the partition UUID from
685 * /etc/machine-id we can securely bind the partition to the
686 * installation. */
687
688 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
689 if (r < 0)
690 return r;
691
692 if (!sd_id128_equal(var_uuid, id)) {
693 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
694 continue;
695 }
696 }
697
698 designator = PARTITION_VAR;
699 rw = !(pflags & GPT_FLAG_READ_ONLY);
700 }
701
702 if (designator != _PARTITION_DESIGNATOR_INVALID) {
703 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
704 const char *options = NULL;
705
706 /* First one wins */
707 if (m->partitions[designator].found)
708 continue;
709
710 if (fstype) {
711 t = strdup(fstype);
712 if (!t)
713 return -ENOMEM;
714 }
715
716 n = strdup(node);
717 if (!n)
718 return -ENOMEM;
719
720 options = mount_options_from_part(mount_options, nr);
721 if (options) {
722 o = strdup(options);
723 if (!o)
724 return -ENOMEM;
725 }
726
727 m->partitions[designator] = (DissectedPartition) {
728 .found = true,
729 .partno = nr,
730 .rw = rw,
731 .architecture = architecture,
732 .node = TAKE_PTR(n),
733 .fstype = TAKE_PTR(t),
734 .uuid = id,
735 .mount_options = TAKE_PTR(o),
736 };
737 }
738
739 } else if (is_mbr) {
740
741 switch (blkid_partition_get_type(pp)) {
742
743 case 0x83: /* Linux partition */
744
745 if (pflags != 0x80) /* Bootable flag */
746 continue;
747
748 if (generic_node)
749 multiple_generic = true;
750 else {
751 generic_nr = nr;
752 generic_rw = true;
753 generic_node = strdup(node);
754 if (!generic_node)
755 return -ENOMEM;
756 }
757
758 break;
759
760 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
761 _cleanup_free_ char *n = NULL, *o = NULL;
762 sd_id128_t id = SD_ID128_NULL;
763 const char *sid, *options = NULL;
764
765 /* First one wins */
766 if (m->partitions[PARTITION_XBOOTLDR].found)
767 continue;
768
769 sid = blkid_partition_get_uuid(pp);
770 if (sid)
771 (void) sd_id128_from_string(sid, &id);
772
773 n = strdup(node);
774 if (!n)
775 return -ENOMEM;
776
777 options = mount_options_from_part(mount_options, nr);
778 if (options) {
779 o = strdup(options);
780 if (!o)
781 return -ENOMEM;
782 }
783
784 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
785 .found = true,
786 .partno = nr,
787 .rw = true,
788 .architecture = _ARCHITECTURE_INVALID,
789 .node = TAKE_PTR(n),
790 .uuid = id,
791 .mount_options = TAKE_PTR(o),
792 };
793
794 break;
795 }}
796 }
797 }
798
799 if (!m->partitions[PARTITION_ROOT].found) {
800 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
801 * either, then check if there's a single generic one, and use that. */
802
803 if (m->partitions[PARTITION_ROOT_VERITY].found)
804 return -EADDRNOTAVAIL;
805
806 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
807 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
808 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
809
810 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
811 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
812
813 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
814 _cleanup_free_ char *o = NULL;
815 const char *options = NULL;
816
817 /* If the root has was set, then we won't fallback to a generic node, because the root hash
818 * decides */
819 if (root_hash)
820 return -EADDRNOTAVAIL;
821
822 /* If we didn't find a generic node, then we can't fix this up either */
823 if (!generic_node)
824 return -ENXIO;
825
826 /* If we didn't find a properly marked root partition, but we did find a single suitable
827 * generic Linux partition, then use this as root partition, if the caller asked for it. */
828 if (multiple_generic)
829 return -ENOTUNIQ;
830
831 options = mount_options_from_part(mount_options, generic_nr);
832 if (options) {
833 o = strdup(options);
834 if (!o)
835 return -ENOMEM;
836 }
837
838 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
839 .found = true,
840 .rw = generic_rw,
841 .partno = generic_nr,
842 .architecture = _ARCHITECTURE_INVALID,
843 .node = TAKE_PTR(generic_node),
844 .uuid = generic_uuid,
845 .mount_options = TAKE_PTR(o),
846 };
847 }
848 }
849
850 if (root_hash) {
851 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
852 return -EADDRNOTAVAIL;
853
854 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
855 * (which would be weird, after all the root hash should only be assigned to one pair of
856 * partitions... */
857 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
858 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
859
860 /* If we found a verity setup, then the root partition is necessarily read-only. */
861 m->partitions[PARTITION_ROOT].rw = false;
862
863 m->verity = true;
864 }
865
866 blkid_free_probe(b);
867 b = NULL;
868
869 /* Fill in file system types if we don't know them yet. */
870 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
871 DissectedPartition *p = m->partitions + i;
872
873 if (!p->found)
874 continue;
875
876 if (!p->fstype && p->node) {
877 r = probe_filesystem(p->node, &p->fstype);
878 if (r < 0 && r != -EUCLEAN)
879 return r;
880 }
881
882 if (streq_ptr(p->fstype, "crypto_LUKS"))
883 m->encrypted = true;
884
885 if (p->fstype && fstype_is_ro(p->fstype))
886 p->rw = false;
887 }
888
889 *ret = TAKE_PTR(m);
890
891 return 0;
892 #else
893 return -EOPNOTSUPP;
894 #endif
895 }
896
897 DissectedImage* dissected_image_unref(DissectedImage *m) {
898 unsigned i;
899
900 if (!m)
901 return NULL;
902
903 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
904 free(m->partitions[i].fstype);
905 free(m->partitions[i].node);
906 free(m->partitions[i].decrypted_fstype);
907 free(m->partitions[i].decrypted_node);
908 free(m->partitions[i].mount_options);
909 }
910
911 free(m->hostname);
912 strv_free(m->machine_info);
913 strv_free(m->os_release);
914
915 return mfree(m);
916 }
917
918 static int is_loop_device(const char *path) {
919 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
920 struct stat st;
921
922 assert(path);
923
924 if (stat(path, &st) < 0)
925 return -errno;
926
927 if (!S_ISBLK(st.st_mode))
928 return -ENOTBLK;
929
930 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
931 if (access(s, F_OK) < 0) {
932 if (errno != ENOENT)
933 return -errno;
934
935 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
936 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
937 if (access(s, F_OK) < 0)
938 return errno == ENOENT ? false : -errno;
939 }
940
941 return true;
942 }
943
944 static int run_fsck(const char *node, const char *fstype) {
945 int r, exit_status;
946 pid_t pid;
947
948 assert(node);
949 assert(fstype);
950
951 r = fsck_exists(fstype);
952 if (r < 0) {
953 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
954 return 0;
955 }
956 if (r == 0) {
957 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
958 return 0;
959 }
960
961 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
962 if (r < 0)
963 return log_debug_errno(r, "Failed to fork off fsck: %m");
964 if (r == 0) {
965 /* Child */
966 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
967 log_debug_errno(errno, "Failed to execl() fsck: %m");
968 _exit(FSCK_OPERATIONAL_ERROR);
969 }
970
971 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
972 if (exit_status < 0)
973 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
974
975 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
976 log_debug("fsck failed with exit status %i.", exit_status);
977
978 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
979 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
980
981 log_debug("Ignoring fsck error.");
982 }
983
984 return 0;
985 }
986
987 static int mount_partition(
988 DissectedPartition *m,
989 const char *where,
990 const char *directory,
991 uid_t uid_shift,
992 DissectImageFlags flags) {
993
994 _cleanup_free_ char *chased = NULL, *options = NULL;
995 const char *p, *node, *fstype;
996 bool rw;
997 int r;
998
999 assert(m);
1000 assert(where);
1001
1002 node = m->decrypted_node ?: m->node;
1003 fstype = m->decrypted_fstype ?: m->fstype;
1004
1005 if (!m->found || !node || !fstype)
1006 return 0;
1007
1008 /* Stacked encryption? Yuck */
1009 if (streq_ptr(fstype, "crypto_LUKS"))
1010 return -ELOOP;
1011
1012 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
1013
1014 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1015 r = run_fsck(node, fstype);
1016 if (r < 0)
1017 return r;
1018 }
1019
1020 if (directory) {
1021 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
1022 if (r < 0)
1023 return r;
1024
1025 p = chased;
1026 } else
1027 p = where;
1028
1029 /* If requested, turn on discard support. */
1030 if (fstype_can_discard(fstype) &&
1031 ((flags & DISSECT_IMAGE_DISCARD) ||
1032 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node)))) {
1033 options = strdup("discard");
1034 if (!options)
1035 return -ENOMEM;
1036 }
1037
1038 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
1039 _cleanup_free_ char *uid_option = NULL;
1040
1041 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1042 return -ENOMEM;
1043
1044 if (!strextend_with_separator(&options, ",", uid_option, NULL))
1045 return -ENOMEM;
1046 }
1047
1048 if (!isempty(m->mount_options))
1049 if (!strextend_with_separator(&options, ",", m->mount_options, NULL))
1050 return -ENOMEM;
1051
1052 r = mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
1053 if (r < 0)
1054 return r;
1055
1056 return 1;
1057 }
1058
1059 int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1060 int r, boot_mounted;
1061
1062 assert(m);
1063 assert(where);
1064
1065 if (!m->partitions[PARTITION_ROOT].found)
1066 return -ENXIO;
1067
1068 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1069 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
1070 if (r < 0)
1071 return r;
1072
1073 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
1074 r = path_is_os_tree(where);
1075 if (r < 0)
1076 return r;
1077 if (r == 0)
1078 return -EMEDIUMTYPE;
1079 }
1080 }
1081
1082 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
1083 return 0;
1084
1085 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
1086 if (r < 0)
1087 return r;
1088
1089 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
1090 if (r < 0)
1091 return r;
1092
1093 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, flags);
1094 if (r < 0)
1095 return r;
1096
1097 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, flags);
1098 if (r < 0)
1099 return r;
1100
1101 boot_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, flags);
1102 if (boot_mounted < 0)
1103 return boot_mounted;
1104
1105 if (m->partitions[PARTITION_ESP].found) {
1106 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1107 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1108
1109 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1110 if (r >= 0) {
1111 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, flags);
1112 if (r < 0)
1113 return r;
1114
1115 } else if (boot_mounted <= 0) {
1116 _cleanup_free_ char *p = NULL;
1117
1118 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1119 if (r >= 0 && dir_is_empty(p) > 0) {
1120 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, flags);
1121 if (r < 0)
1122 return r;
1123 }
1124 }
1125 }
1126
1127 return 0;
1128 }
1129
1130 #if HAVE_LIBCRYPTSETUP
1131 typedef struct DecryptedPartition {
1132 struct crypt_device *device;
1133 char *name;
1134 bool relinquished;
1135 } DecryptedPartition;
1136
1137 struct DecryptedImage {
1138 DecryptedPartition *decrypted;
1139 size_t n_decrypted;
1140 size_t n_allocated;
1141 };
1142 #endif
1143
1144 DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
1145 #if HAVE_LIBCRYPTSETUP
1146 size_t i;
1147 int r;
1148
1149 if (!d)
1150 return NULL;
1151
1152 for (i = 0; i < d->n_decrypted; i++) {
1153 DecryptedPartition *p = d->decrypted + i;
1154
1155 if (p->device && p->name && !p->relinquished) {
1156 r = crypt_deactivate(p->device, p->name);
1157 if (r < 0)
1158 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1159 }
1160
1161 if (p->device)
1162 crypt_free(p->device);
1163 free(p->name);
1164 }
1165
1166 free(d);
1167 #endif
1168 return NULL;
1169 }
1170
1171 #if HAVE_LIBCRYPTSETUP
1172
1173 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1174 _cleanup_free_ char *name = NULL, *node = NULL;
1175 const char *base;
1176
1177 assert(original_node);
1178 assert(suffix);
1179 assert(ret_name);
1180 assert(ret_node);
1181
1182 base = strrchr(original_node, '/');
1183 if (!base)
1184 base = original_node;
1185 else
1186 base++;
1187 if (isempty(base))
1188 return -EINVAL;
1189
1190 name = strjoin(base, suffix);
1191 if (!name)
1192 return -ENOMEM;
1193 if (!filename_is_valid(name))
1194 return -EINVAL;
1195
1196 node = path_join(crypt_get_dir(), name);
1197 if (!node)
1198 return -ENOMEM;
1199
1200 *ret_name = TAKE_PTR(name);
1201 *ret_node = TAKE_PTR(node);
1202
1203 return 0;
1204 }
1205
1206 static int decrypt_partition(
1207 DissectedPartition *m,
1208 const char *passphrase,
1209 DissectImageFlags flags,
1210 DecryptedImage *d) {
1211
1212 _cleanup_free_ char *node = NULL, *name = NULL;
1213 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1214 int r;
1215
1216 assert(m);
1217 assert(d);
1218
1219 if (!m->found || !m->node || !m->fstype)
1220 return 0;
1221
1222 if (!streq(m->fstype, "crypto_LUKS"))
1223 return 0;
1224
1225 if (!passphrase)
1226 return -ENOKEY;
1227
1228 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1229 if (r < 0)
1230 return r;
1231
1232 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1233 return -ENOMEM;
1234
1235 r = crypt_init(&cd, m->node);
1236 if (r < 0)
1237 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
1238
1239 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
1240
1241 r = crypt_load(cd, CRYPT_LUKS, NULL);
1242 if (r < 0)
1243 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
1244
1245 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1246 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1247 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
1248 if (r < 0) {
1249 log_debug_errno(r, "Failed to activate LUKS device: %m");
1250 return r == -EPERM ? -EKEYREJECTED : r;
1251 }
1252
1253 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1254 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
1255 d->n_decrypted++;
1256
1257 m->decrypted_node = TAKE_PTR(node);
1258
1259 return 0;
1260 }
1261
1262 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) {
1263 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1264 _cleanup_free_ char *root_hash_existing = NULL;
1265 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1266 struct crypt_params_verity crypt_params = {};
1267 size_t root_hash_existing_size = root_hash_size;
1268 int r;
1269
1270 assert(ret_cd);
1271
1272 r = crypt_init_by_name(&cd, name);
1273 if (r < 0)
1274 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
1275 r = crypt_get_verity_info(cd, &crypt_params);
1276 if (r < 0)
1277 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
1278 root_hash_existing = malloc0(root_hash_size);
1279 if (!root_hash_existing)
1280 return -ENOMEM;
1281 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
1282 if (r < 0)
1283 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
1284 if (root_hash_size != root_hash_existing_size || memcmp(root_hash_existing, root_hash, root_hash_size) != 0)
1285 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
1286 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1287 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount
1288 * used the same settings, so that a previous unsigned mount will not be reused if the user
1289 * asks to use signing for the new one, and viceversa. */
1290 if (has_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
1291 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1292 #endif
1293
1294 *ret_cd = TAKE_PTR(cd);
1295 return 0;
1296 }
1297
1298 static inline void dm_deferred_remove_clean(char *name) {
1299 if (!name)
1300 return;
1301 (void) crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
1302 free(name);
1303 }
1304 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1305
1306 static int verity_partition(
1307 DissectedPartition *m,
1308 DissectedPartition *v,
1309 const void *root_hash,
1310 size_t root_hash_size,
1311 const char *verity_data,
1312 const char *root_hash_sig_path,
1313 const void *root_hash_sig,
1314 size_t root_hash_sig_size,
1315 DissectImageFlags flags,
1316 DecryptedImage *d) {
1317
1318 _cleanup_free_ char *node = NULL, *name = NULL, *hash_sig_from_file = NULL;
1319 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1320 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
1321 int r;
1322
1323 assert(m);
1324 assert(v || verity_data);
1325
1326 if (!root_hash)
1327 return 0;
1328
1329 if (!m->found || !m->node || !m->fstype)
1330 return 0;
1331 if (!verity_data) {
1332 if (!v->found || !v->node || !v->fstype)
1333 return 0;
1334
1335 if (!streq(v->fstype, "DM_verity_hash"))
1336 return 0;
1337 }
1338
1339 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
1340 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1341 _cleanup_free_ char *root_hash_encoded = NULL;
1342 root_hash_encoded = hexmem(root_hash, root_hash_size);
1343 if (!root_hash_encoded)
1344 return -ENOMEM;
1345 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
1346 } else
1347 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
1348 if (r < 0)
1349 return r;
1350
1351 if (!root_hash_sig && root_hash_sig_path) {
1352 r = read_full_file_full(AT_FDCWD, root_hash_sig_path, 0, &hash_sig_from_file, &root_hash_sig_size);
1353 if (r < 0)
1354 return r;
1355 }
1356
1357 r = crypt_init(&cd, verity_data ?: v->node);
1358 if (r < 0)
1359 return r;
1360
1361 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
1362
1363 r = crypt_load(cd, CRYPT_VERITY, NULL);
1364 if (r < 0)
1365 return r;
1366
1367 r = crypt_set_data_device(cd, m->node);
1368 if (r < 0)
1369 return r;
1370
1371 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1372 return -ENOMEM;
1373
1374 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1375 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1376 * retry a few times before giving up. */
1377 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
1378 if (root_hash_sig || hash_sig_from_file) {
1379 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1380 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);
1381 #else
1382 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()");
1383 #endif
1384 } else
1385 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
1386 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1387 * There's no way to distinguish this situation from a genuine error due to invalid
1388 * parameters, so immediately fallback to activating the device with a unique name.
1389 * Improvements in libcrypsetup can ensure this never happens: https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1390 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1391 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);
1392 if (!IN_SET(r, 0, -EEXIST, -ENODEV))
1393 return r;
1394 if (r == -EEXIST) {
1395 struct crypt_device *existing_cd = NULL;
1396
1397 if (!restore_deferred_remove){
1398 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1399 r = dm_deferred_remove_cancel(name);
1400 if (r < 0)
1401 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
1402 restore_deferred_remove = strdup(name);
1403 if (!restore_deferred_remove)
1404 return -ENOMEM;
1405 }
1406
1407 r = verity_can_reuse(root_hash, root_hash_size, !!root_hash_sig || !!hash_sig_from_file, name, &existing_cd);
1408 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1409 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1410 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);
1411 if (!IN_SET(r, 0, -ENODEV, -ENOENT))
1412 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
1413 if (r == 0) {
1414 if (cd)
1415 crypt_free(cd);
1416 cd = existing_cd;
1417 }
1418 }
1419 if (r == 0)
1420 break;
1421 }
1422
1423 /* Sanity check: libdevmapper is known to report that the device already exists and is active,
1424 * but it's actually not there, so the later filesystem probe or mount would fail. */
1425 if (r == 0)
1426 r = access(node, F_OK);
1427 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1428 * Fall back to activating it with a unique device name. */
1429 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1430 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);
1431
1432 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1433 restore_deferred_remove = mfree(restore_deferred_remove);
1434
1435 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1436 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
1437 d->n_decrypted++;
1438
1439 m->decrypted_node = TAKE_PTR(node);
1440
1441 return 0;
1442 }
1443 #endif
1444
1445 int dissected_image_decrypt(
1446 DissectedImage *m,
1447 const char *passphrase,
1448 const void *root_hash,
1449 size_t root_hash_size,
1450 const char *verity_data,
1451 const char *root_hash_sig_path,
1452 const void *root_hash_sig,
1453 size_t root_hash_sig_size,
1454 DissectImageFlags flags,
1455 DecryptedImage **ret) {
1456
1457 #if HAVE_LIBCRYPTSETUP
1458 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
1459 unsigned i;
1460 int r;
1461 #endif
1462
1463 assert(m);
1464 assert(root_hash || root_hash_size == 0);
1465
1466 /* Returns:
1467 *
1468 * = 0 → There was nothing to decrypt
1469 * > 0 → Decrypted successfully
1470 * -ENOKEY → There's something to decrypt but no key was supplied
1471 * -EKEYREJECTED → Passed key was not correct
1472 */
1473
1474 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1475 return -EINVAL;
1476
1477 if (!m->encrypted && !m->verity) {
1478 *ret = NULL;
1479 return 0;
1480 }
1481
1482 #if HAVE_LIBCRYPTSETUP
1483 d = new0(DecryptedImage, 1);
1484 if (!d)
1485 return -ENOMEM;
1486
1487 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1488 DissectedPartition *p = m->partitions + i;
1489 int k;
1490
1491 if (!p->found)
1492 continue;
1493
1494 r = decrypt_partition(p, passphrase, flags, d);
1495 if (r < 0)
1496 return r;
1497
1498 k = PARTITION_VERITY_OF(i);
1499 if (k >= 0) {
1500 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);
1501 if (r < 0)
1502 return r;
1503 }
1504
1505 if (!p->decrypted_fstype && p->decrypted_node) {
1506 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
1507 if (r < 0 && r != -EUCLEAN)
1508 return r;
1509 }
1510 }
1511
1512 *ret = TAKE_PTR(d);
1513
1514 return 1;
1515 #else
1516 return -EOPNOTSUPP;
1517 #endif
1518 }
1519
1520 int dissected_image_decrypt_interactively(
1521 DissectedImage *m,
1522 const char *passphrase,
1523 const void *root_hash,
1524 size_t root_hash_size,
1525 const char *verity_data,
1526 const char *root_hash_sig_path,
1527 const void *root_hash_sig,
1528 size_t root_hash_sig_size,
1529 DissectImageFlags flags,
1530 DecryptedImage **ret) {
1531
1532 _cleanup_strv_free_erase_ char **z = NULL;
1533 int n = 3, r;
1534
1535 if (passphrase)
1536 n--;
1537
1538 for (;;) {
1539 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);
1540 if (r >= 0)
1541 return r;
1542 if (r == -EKEYREJECTED)
1543 log_error_errno(r, "Incorrect passphrase, try again!");
1544 else if (r != -ENOKEY)
1545 return log_error_errno(r, "Failed to decrypt image: %m");
1546
1547 if (--n < 0)
1548 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1549 "Too many retries.");
1550
1551 z = strv_free(z);
1552
1553 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
1554 if (r < 0)
1555 return log_error_errno(r, "Failed to query for passphrase: %m");
1556
1557 passphrase = z[0];
1558 }
1559 }
1560
1561 int decrypted_image_relinquish(DecryptedImage *d) {
1562
1563 #if HAVE_LIBCRYPTSETUP
1564 size_t i;
1565 int r;
1566 #endif
1567
1568 assert(d);
1569
1570 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1571 * that we don't clean it up ourselves either anymore */
1572
1573 #if HAVE_LIBCRYPTSETUP
1574 for (i = 0; i < d->n_decrypted; i++) {
1575 DecryptedPartition *p = d->decrypted + i;
1576
1577 if (p->relinquished)
1578 continue;
1579
1580 r = crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
1581 if (r < 0)
1582 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1583
1584 p->relinquished = true;
1585 }
1586 #endif
1587
1588 return 0;
1589 }
1590
1591 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) {
1592 _cleanup_free_ char *verity_filename = NULL, *roothashsig_filename = NULL;
1593 _cleanup_free_ void *roothash_decoded = NULL;
1594 size_t roothash_decoded_size = 0;
1595 int r;
1596
1597 assert(image);
1598
1599 if (is_device_path(image)) {
1600 /* If we are asked to load the root hash for a device node, exit early */
1601 if (ret_roothash)
1602 *ret_roothash = NULL;
1603 if (ret_roothash_size)
1604 *ret_roothash_size = 0;
1605 if (ret_verity_data)
1606 *ret_verity_data = NULL;
1607 if (ret_roothashsig)
1608 *ret_roothashsig = NULL;
1609 return 0;
1610 }
1611
1612 if (ret_verity_data) {
1613 char *e;
1614
1615 verity_filename = new(char, strlen(image) + STRLEN(".verity") + 1);
1616 if (!verity_filename)
1617 return -ENOMEM;
1618 strcpy(verity_filename, image);
1619 e = endswith(verity_filename, ".raw");
1620 if (e)
1621 strcpy(e, ".verity");
1622 else
1623 strcat(verity_filename, ".verity");
1624
1625 r = access(verity_filename, F_OK);
1626 if (r < 0) {
1627 if (errno != ENOENT)
1628 return -errno;
1629 verity_filename = mfree(verity_filename);
1630 }
1631 }
1632
1633 if (ret_roothashsig) {
1634 char *e;
1635
1636 /* Follow naming convention recommended by the relevant RFC:
1637 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1638 roothashsig_filename = new(char, strlen(image) + STRLEN(".roothash.p7s") + 1);
1639 if (!roothashsig_filename)
1640 return -ENOMEM;
1641 strcpy(roothashsig_filename, image);
1642 e = endswith(roothashsig_filename, ".raw");
1643 if (e)
1644 strcpy(e, ".roothash.p7s");
1645 else
1646 strcat(roothashsig_filename, ".roothash.p7s");
1647
1648 r = access(roothashsig_filename, R_OK);
1649 if (r < 0) {
1650 if (errno != ENOENT)
1651 return -errno;
1652 roothashsig_filename = mfree(roothashsig_filename);
1653 }
1654 }
1655
1656 if (ret_roothash) {
1657 _cleanup_free_ char *text = NULL;
1658 assert(ret_roothash_size);
1659
1660 if (root_hash_path) {
1661 /* We have the path to a roothash to load and decode, eg: RootHash=/foo/bar.roothash */
1662 r = read_one_line_file(root_hash_path, &text);
1663 if (r < 0)
1664 return r;
1665 } else {
1666 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1667 if (r < 0) {
1668 char *fn, *e, *n;
1669
1670 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1671 return r;
1672
1673 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
1674 n = stpcpy(fn, image);
1675 e = endswith(fn, ".raw");
1676 if (e)
1677 n = e;
1678
1679 strcpy(n, ".roothash");
1680
1681 r = read_one_line_file(fn, &text);
1682 if (r < 0 && r != -ENOENT)
1683 return r;
1684 }
1685 }
1686
1687 if (text) {
1688 r = unhexmem(text, strlen(text), &roothash_decoded, &roothash_decoded_size);
1689 if (r < 0)
1690 return r;
1691 if (roothash_decoded_size < sizeof(sd_id128_t))
1692 return -EINVAL;
1693 }
1694 }
1695
1696 if (ret_roothash) {
1697 *ret_roothash = TAKE_PTR(roothash_decoded);
1698 *ret_roothash_size = roothash_decoded_size;
1699 }
1700 if (ret_verity_data)
1701 *ret_verity_data = TAKE_PTR(verity_filename);
1702 if (roothashsig_filename)
1703 *ret_roothashsig = TAKE_PTR(roothashsig_filename);
1704
1705 return 1;
1706 }
1707
1708 int dissected_image_acquire_metadata(DissectedImage *m) {
1709
1710 enum {
1711 META_HOSTNAME,
1712 META_MACHINE_ID,
1713 META_MACHINE_INFO,
1714 META_OS_RELEASE,
1715 _META_MAX,
1716 };
1717
1718 static const char *const paths[_META_MAX] = {
1719 [META_HOSTNAME] = "/etc/hostname\0",
1720 [META_MACHINE_ID] = "/etc/machine-id\0",
1721 [META_MACHINE_INFO] = "/etc/machine-info\0",
1722 [META_OS_RELEASE] = "/etc/os-release\0"
1723 "/usr/lib/os-release\0",
1724 };
1725
1726 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
1727 _cleanup_(rmdir_and_freep) char *t = NULL;
1728 _cleanup_(sigkill_waitp) pid_t child = 0;
1729 sd_id128_t machine_id = SD_ID128_NULL;
1730 _cleanup_free_ char *hostname = NULL;
1731 unsigned n_meta_initialized = 0, k;
1732 int fds[2 * _META_MAX], r;
1733
1734 BLOCK_SIGNALS(SIGCHLD);
1735
1736 assert(m);
1737
1738 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1739 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1740 r = -errno;
1741 goto finish;
1742 }
1743
1744 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1745 if (r < 0)
1746 goto finish;
1747
1748 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
1749 if (r < 0)
1750 goto finish;
1751 if (r == 0) {
1752 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
1753 if (r < 0) {
1754 log_debug_errno(r, "Failed to mount dissected image: %m");
1755 _exit(EXIT_FAILURE);
1756 }
1757
1758 for (k = 0; k < _META_MAX; k++) {
1759 _cleanup_close_ int fd = -1;
1760 const char *p;
1761
1762 fds[2*k] = safe_close(fds[2*k]);
1763
1764 NULSTR_FOREACH(p, paths[k]) {
1765 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
1766 if (fd >= 0)
1767 break;
1768 }
1769 if (fd < 0) {
1770 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
1771 continue;
1772 }
1773
1774 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
1775 if (r < 0)
1776 _exit(EXIT_FAILURE);
1777
1778 fds[2*k+1] = safe_close(fds[2*k+1]);
1779 }
1780
1781 _exit(EXIT_SUCCESS);
1782 }
1783
1784 for (k = 0; k < _META_MAX; k++) {
1785 _cleanup_fclose_ FILE *f = NULL;
1786
1787 fds[2*k+1] = safe_close(fds[2*k+1]);
1788
1789 f = take_fdopen(&fds[2*k], "r");
1790 if (!f) {
1791 r = -errno;
1792 goto finish;
1793 }
1794
1795 switch (k) {
1796
1797 case META_HOSTNAME:
1798 r = read_etc_hostname_stream(f, &hostname);
1799 if (r < 0)
1800 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1801
1802 break;
1803
1804 case META_MACHINE_ID: {
1805 _cleanup_free_ char *line = NULL;
1806
1807 r = read_line(f, LONG_LINE_MAX, &line);
1808 if (r < 0)
1809 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1810 else if (r == 33) {
1811 r = sd_id128_from_string(line, &machine_id);
1812 if (r < 0)
1813 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1814 } else if (r == 0)
1815 log_debug("/etc/machine-id file is empty.");
1816 else
1817 log_debug("/etc/machine-id has unexpected length %i.", r);
1818
1819 break;
1820 }
1821
1822 case META_MACHINE_INFO:
1823 r = load_env_file_pairs(f, "machine-info", &machine_info);
1824 if (r < 0)
1825 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1826
1827 break;
1828
1829 case META_OS_RELEASE:
1830 r = load_env_file_pairs(f, "os-release", &os_release);
1831 if (r < 0)
1832 log_debug_errno(r, "Failed to read OS release file: %m");
1833
1834 break;
1835 }
1836 }
1837
1838 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
1839 child = 0;
1840 if (r < 0)
1841 goto finish;
1842 if (r != EXIT_SUCCESS)
1843 return -EPROTO;
1844
1845 free_and_replace(m->hostname, hostname);
1846 m->machine_id = machine_id;
1847 strv_free_and_replace(m->machine_info, machine_info);
1848 strv_free_and_replace(m->os_release, os_release);
1849
1850 finish:
1851 for (k = 0; k < n_meta_initialized; k++)
1852 safe_close_pair(fds + 2*k);
1853
1854 return r;
1855 }
1856
1857 int dissect_image_and_warn(
1858 int fd,
1859 const char *name,
1860 const void *root_hash,
1861 size_t root_hash_size,
1862 const char *verity_data,
1863 const MountOptions *mount_options,
1864 DissectImageFlags flags,
1865 DissectedImage **ret) {
1866
1867 _cleanup_free_ char *buffer = NULL;
1868 int r;
1869
1870 if (!name) {
1871 r = fd_get_path(fd, &buffer);
1872 if (r < 0)
1873 return r;
1874
1875 name = buffer;
1876 }
1877
1878 r = dissect_image(fd, root_hash, root_hash_size, verity_data, mount_options, flags, ret);
1879
1880 switch (r) {
1881
1882 case -EOPNOTSUPP:
1883 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
1884
1885 case -ENOPKG:
1886 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
1887
1888 case -EADDRNOTAVAIL:
1889 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
1890
1891 case -ENOTUNIQ:
1892 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
1893
1894 case -ENXIO:
1895 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
1896
1897 case -EPROTONOSUPPORT:
1898 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
1899
1900 default:
1901 if (r < 0)
1902 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
1903
1904 return r;
1905 }
1906 }
1907
1908 bool dissected_image_can_do_verity(const DissectedImage *image, unsigned partition_designator) {
1909 if (image->single_file_system)
1910 return partition_designator == PARTITION_ROOT && image->can_verity;
1911
1912 return PARTITION_VERITY_OF(partition_designator) >= 0;
1913 }
1914
1915 bool dissected_image_has_verity(const DissectedImage *image, unsigned partition_designator) {
1916 int k;
1917
1918 if (image->single_file_system)
1919 return partition_designator == PARTITION_ROOT && image->verity;
1920
1921 k = PARTITION_VERITY_OF(partition_designator);
1922 return k >= 0 && image->partitions[k].found;
1923 }
1924
1925 MountOptions* mount_options_free_all(MountOptions *options) {
1926 MountOptions *m;
1927
1928 while ((m = options)) {
1929 LIST_REMOVE(mount_options, options, m);
1930 free(m->options);
1931 free(m);
1932 }
1933
1934 return NULL;
1935 }
1936
1937 const char* mount_options_from_part(const MountOptions *options, unsigned int partition_number) {
1938 MountOptions *m;
1939
1940 LIST_FOREACH(mount_options, m, (MountOptions *)options)
1941 if (partition_number == m->partition_number && !isempty(m->options))
1942 return m->options;
1943 return NULL;
1944 }
1945
1946 static const char *const partition_designator_table[] = {
1947 [PARTITION_ROOT] = "root",
1948 [PARTITION_ROOT_SECONDARY] = "root-secondary",
1949 [PARTITION_HOME] = "home",
1950 [PARTITION_SRV] = "srv",
1951 [PARTITION_ESP] = "esp",
1952 [PARTITION_XBOOTLDR] = "xbootldr",
1953 [PARTITION_SWAP] = "swap",
1954 [PARTITION_ROOT_VERITY] = "root-verity",
1955 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
1956 [PARTITION_TMP] = "tmp",
1957 [PARTITION_VAR] = "var",
1958 };
1959
1960 DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);