]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
Merge pull request #16104 from ssahani/dhcpv6-iaid
[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 return -EINVAL;
1144 base++;
1145 if (isempty(base))
1146 return -EINVAL;
1147
1148 name = strjoin(base, suffix);
1149 if (!name)
1150 return -ENOMEM;
1151 if (!filename_is_valid(name))
1152 return -EINVAL;
1153
1154 node = path_join(crypt_get_dir(), name);
1155 if (!node)
1156 return -ENOMEM;
1157
1158 *ret_name = TAKE_PTR(name);
1159 *ret_node = TAKE_PTR(node);
1160
1161 return 0;
1162 }
1163
1164 static int decrypt_partition(
1165 DissectedPartition *m,
1166 const char *passphrase,
1167 DissectImageFlags flags,
1168 DecryptedImage *d) {
1169
1170 _cleanup_free_ char *node = NULL, *name = NULL;
1171 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1172 int r;
1173
1174 assert(m);
1175 assert(d);
1176
1177 if (!m->found || !m->node || !m->fstype)
1178 return 0;
1179
1180 if (!streq(m->fstype, "crypto_LUKS"))
1181 return 0;
1182
1183 if (!passphrase)
1184 return -ENOKEY;
1185
1186 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1187 if (r < 0)
1188 return r;
1189
1190 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1191 return -ENOMEM;
1192
1193 r = crypt_init(&cd, m->node);
1194 if (r < 0)
1195 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
1196
1197 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
1198
1199 r = crypt_load(cd, CRYPT_LUKS, NULL);
1200 if (r < 0)
1201 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
1202
1203 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1204 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1205 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
1206 if (r < 0) {
1207 log_debug_errno(r, "Failed to activate LUKS device: %m");
1208 return r == -EPERM ? -EKEYREJECTED : r;
1209 }
1210
1211 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1212 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
1213 d->n_decrypted++;
1214
1215 m->decrypted_node = TAKE_PTR(node);
1216
1217 return 0;
1218 }
1219
1220 static int verity_partition(
1221 DissectedPartition *m,
1222 DissectedPartition *v,
1223 const void *root_hash,
1224 size_t root_hash_size,
1225 const char *verity_data,
1226 DissectImageFlags flags,
1227 DecryptedImage *d) {
1228
1229 _cleanup_free_ char *node = NULL, *name = NULL;
1230 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1231 int r;
1232
1233 assert(m);
1234 assert(v || verity_data);
1235
1236 if (!root_hash)
1237 return 0;
1238
1239 if (!m->found || !m->node || !m->fstype)
1240 return 0;
1241 if (!verity_data) {
1242 if (!v->found || !v->node || !v->fstype)
1243 return 0;
1244
1245 if (!streq(v->fstype, "DM_verity_hash"))
1246 return 0;
1247 }
1248
1249 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
1250 if (r < 0)
1251 return r;
1252
1253 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1254 return -ENOMEM;
1255
1256 r = crypt_init(&cd, verity_data ?: v->node);
1257 if (r < 0)
1258 return r;
1259
1260 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
1261
1262 r = crypt_load(cd, CRYPT_VERITY, NULL);
1263 if (r < 0)
1264 return r;
1265
1266 r = crypt_set_data_device(cd, m->node);
1267 if (r < 0)
1268 return r;
1269
1270 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
1271 if (r < 0)
1272 return r;
1273
1274 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1275 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
1276 d->n_decrypted++;
1277
1278 m->decrypted_node = TAKE_PTR(node);
1279
1280 return 0;
1281 }
1282 #endif
1283
1284 int dissected_image_decrypt(
1285 DissectedImage *m,
1286 const char *passphrase,
1287 const void *root_hash,
1288 size_t root_hash_size,
1289 const char *verity_data,
1290 DissectImageFlags flags,
1291 DecryptedImage **ret) {
1292
1293 #if HAVE_LIBCRYPTSETUP
1294 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
1295 unsigned i;
1296 int r;
1297 #endif
1298
1299 assert(m);
1300 assert(root_hash || root_hash_size == 0);
1301
1302 /* Returns:
1303 *
1304 * = 0 → There was nothing to decrypt
1305 * > 0 → Decrypted successfully
1306 * -ENOKEY → There's something to decrypt but no key was supplied
1307 * -EKEYREJECTED → Passed key was not correct
1308 */
1309
1310 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1311 return -EINVAL;
1312
1313 if (!m->encrypted && !m->verity) {
1314 *ret = NULL;
1315 return 0;
1316 }
1317
1318 #if HAVE_LIBCRYPTSETUP
1319 d = new0(DecryptedImage, 1);
1320 if (!d)
1321 return -ENOMEM;
1322
1323 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1324 DissectedPartition *p = m->partitions + i;
1325 int k;
1326
1327 if (!p->found)
1328 continue;
1329
1330 r = decrypt_partition(p, passphrase, flags, d);
1331 if (r < 0)
1332 return r;
1333
1334 k = PARTITION_VERITY_OF(i);
1335 if (k >= 0) {
1336 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, verity_data, flags, d);
1337 if (r < 0)
1338 return r;
1339 }
1340
1341 if (!p->decrypted_fstype && p->decrypted_node) {
1342 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
1343 if (r < 0 && r != -EUCLEAN)
1344 return r;
1345 }
1346 }
1347
1348 *ret = TAKE_PTR(d);
1349
1350 return 1;
1351 #else
1352 return -EOPNOTSUPP;
1353 #endif
1354 }
1355
1356 int dissected_image_decrypt_interactively(
1357 DissectedImage *m,
1358 const char *passphrase,
1359 const void *root_hash,
1360 size_t root_hash_size,
1361 const char *verity_data,
1362 DissectImageFlags flags,
1363 DecryptedImage **ret) {
1364
1365 _cleanup_strv_free_erase_ char **z = NULL;
1366 int n = 3, r;
1367
1368 if (passphrase)
1369 n--;
1370
1371 for (;;) {
1372 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, verity_data, flags, ret);
1373 if (r >= 0)
1374 return r;
1375 if (r == -EKEYREJECTED)
1376 log_error_errno(r, "Incorrect passphrase, try again!");
1377 else if (r != -ENOKEY)
1378 return log_error_errno(r, "Failed to decrypt image: %m");
1379
1380 if (--n < 0)
1381 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1382 "Too many retries.");
1383
1384 z = strv_free(z);
1385
1386 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
1387 if (r < 0)
1388 return log_error_errno(r, "Failed to query for passphrase: %m");
1389
1390 passphrase = z[0];
1391 }
1392 }
1393
1394 int decrypted_image_relinquish(DecryptedImage *d) {
1395
1396 #if HAVE_LIBCRYPTSETUP
1397 size_t i;
1398 int r;
1399 #endif
1400
1401 assert(d);
1402
1403 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1404 * that we don't clean it up ourselves either anymore */
1405
1406 #if HAVE_LIBCRYPTSETUP
1407 for (i = 0; i < d->n_decrypted; i++) {
1408 DecryptedPartition *p = d->decrypted + i;
1409
1410 if (p->relinquished)
1411 continue;
1412
1413 r = dm_deferred_remove(p->name);
1414 if (r < 0)
1415 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1416
1417 p->relinquished = true;
1418 }
1419 #endif
1420
1421 return 0;
1422 }
1423
1424 int verity_metadata_load(const char *image, void **ret_roothash, size_t *ret_roothash_size, char **ret_verity_data) {
1425 _cleanup_free_ char *verity_filename = NULL;
1426 _cleanup_free_ void *roothash_decoded = NULL;
1427 size_t roothash_decoded_size = 0;
1428 int r;
1429
1430 assert(image);
1431
1432 if (is_device_path(image)) {
1433 /* If we are asked to load the root hash for a device node, exit early */
1434 if (ret_roothash)
1435 *ret_roothash = NULL;
1436 if (ret_roothash_size)
1437 *ret_roothash_size = 0;
1438 if (ret_verity_data)
1439 *ret_verity_data = NULL;
1440 return 0;
1441 }
1442
1443 if (ret_verity_data) {
1444 char *e;
1445
1446 verity_filename = new(char, strlen(image) + STRLEN(".verity") + 1);
1447 if (!verity_filename)
1448 return -ENOMEM;
1449 strcpy(verity_filename, image);
1450 e = endswith(verity_filename, ".raw");
1451 if (e)
1452 strcpy(e, ".verity");
1453 else
1454 strcat(verity_filename, ".verity");
1455
1456 r = access(verity_filename, F_OK);
1457 if (r < 0) {
1458 if (errno != ENOENT)
1459 return -errno;
1460 verity_filename = mfree(verity_filename);
1461 }
1462 }
1463
1464 if (ret_roothash) {
1465 _cleanup_free_ char *text = NULL;
1466 assert(ret_roothash_size);
1467
1468 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1469 if (r < 0) {
1470 char *fn, *e, *n;
1471
1472 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1473 return r;
1474
1475 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
1476 n = stpcpy(fn, image);
1477 e = endswith(fn, ".raw");
1478 if (e)
1479 n = e;
1480
1481 strcpy(n, ".roothash");
1482
1483 r = read_one_line_file(fn, &text);
1484 if (r < 0 && r != -ENOENT)
1485 return r;
1486 }
1487
1488 if (text) {
1489 r = unhexmem(text, strlen(text), &roothash_decoded, &roothash_decoded_size);
1490 if (r < 0)
1491 return r;
1492 if (roothash_decoded_size < sizeof(sd_id128_t))
1493 return -EINVAL;
1494 }
1495 }
1496
1497 if (ret_roothash) {
1498 *ret_roothash = TAKE_PTR(roothash_decoded);
1499 *ret_roothash_size = roothash_decoded_size;
1500 }
1501 if (ret_verity_data)
1502 *ret_verity_data = TAKE_PTR(verity_filename);
1503
1504 return 1;
1505 }
1506
1507 int dissected_image_acquire_metadata(DissectedImage *m) {
1508
1509 enum {
1510 META_HOSTNAME,
1511 META_MACHINE_ID,
1512 META_MACHINE_INFO,
1513 META_OS_RELEASE,
1514 _META_MAX,
1515 };
1516
1517 static const char *const paths[_META_MAX] = {
1518 [META_HOSTNAME] = "/etc/hostname\0",
1519 [META_MACHINE_ID] = "/etc/machine-id\0",
1520 [META_MACHINE_INFO] = "/etc/machine-info\0",
1521 [META_OS_RELEASE] = "/etc/os-release\0"
1522 "/usr/lib/os-release\0",
1523 };
1524
1525 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
1526 _cleanup_(rmdir_and_freep) char *t = NULL;
1527 _cleanup_(sigkill_waitp) pid_t child = 0;
1528 sd_id128_t machine_id = SD_ID128_NULL;
1529 _cleanup_free_ char *hostname = NULL;
1530 unsigned n_meta_initialized = 0, k;
1531 int fds[2 * _META_MAX], r;
1532
1533 BLOCK_SIGNALS(SIGCHLD);
1534
1535 assert(m);
1536
1537 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1538 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1539 r = -errno;
1540 goto finish;
1541 }
1542
1543 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1544 if (r < 0)
1545 goto finish;
1546
1547 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
1548 if (r < 0)
1549 goto finish;
1550 if (r == 0) {
1551 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
1552 if (r < 0) {
1553 log_debug_errno(r, "Failed to mount dissected image: %m");
1554 _exit(EXIT_FAILURE);
1555 }
1556
1557 for (k = 0; k < _META_MAX; k++) {
1558 _cleanup_close_ int fd = -1;
1559 const char *p;
1560
1561 fds[2*k] = safe_close(fds[2*k]);
1562
1563 NULSTR_FOREACH(p, paths[k]) {
1564 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
1565 if (fd >= 0)
1566 break;
1567 }
1568 if (fd < 0) {
1569 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
1570 continue;
1571 }
1572
1573 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
1574 if (r < 0)
1575 _exit(EXIT_FAILURE);
1576
1577 fds[2*k+1] = safe_close(fds[2*k+1]);
1578 }
1579
1580 _exit(EXIT_SUCCESS);
1581 }
1582
1583 for (k = 0; k < _META_MAX; k++) {
1584 _cleanup_fclose_ FILE *f = NULL;
1585
1586 fds[2*k+1] = safe_close(fds[2*k+1]);
1587
1588 f = take_fdopen(&fds[2*k], "r");
1589 if (!f) {
1590 r = -errno;
1591 goto finish;
1592 }
1593
1594 switch (k) {
1595
1596 case META_HOSTNAME:
1597 r = read_etc_hostname_stream(f, &hostname);
1598 if (r < 0)
1599 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1600
1601 break;
1602
1603 case META_MACHINE_ID: {
1604 _cleanup_free_ char *line = NULL;
1605
1606 r = read_line(f, LONG_LINE_MAX, &line);
1607 if (r < 0)
1608 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1609 else if (r == 33) {
1610 r = sd_id128_from_string(line, &machine_id);
1611 if (r < 0)
1612 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1613 } else if (r == 0)
1614 log_debug("/etc/machine-id file is empty.");
1615 else
1616 log_debug("/etc/machine-id has unexpected length %i.", r);
1617
1618 break;
1619 }
1620
1621 case META_MACHINE_INFO:
1622 r = load_env_file_pairs(f, "machine-info", &machine_info);
1623 if (r < 0)
1624 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1625
1626 break;
1627
1628 case META_OS_RELEASE:
1629 r = load_env_file_pairs(f, "os-release", &os_release);
1630 if (r < 0)
1631 log_debug_errno(r, "Failed to read OS release file: %m");
1632
1633 break;
1634 }
1635 }
1636
1637 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
1638 child = 0;
1639 if (r < 0)
1640 goto finish;
1641 if (r != EXIT_SUCCESS)
1642 return -EPROTO;
1643
1644 free_and_replace(m->hostname, hostname);
1645 m->machine_id = machine_id;
1646 strv_free_and_replace(m->machine_info, machine_info);
1647 strv_free_and_replace(m->os_release, os_release);
1648
1649 finish:
1650 for (k = 0; k < n_meta_initialized; k++)
1651 safe_close_pair(fds + 2*k);
1652
1653 return r;
1654 }
1655
1656 int dissect_image_and_warn(
1657 int fd,
1658 const char *name,
1659 const void *root_hash,
1660 size_t root_hash_size,
1661 const char *verity_data,
1662 DissectImageFlags flags,
1663 DissectedImage **ret) {
1664
1665 _cleanup_free_ char *buffer = NULL;
1666 int r;
1667
1668 if (!name) {
1669 r = fd_get_path(fd, &buffer);
1670 if (r < 0)
1671 return r;
1672
1673 name = buffer;
1674 }
1675
1676 r = dissect_image(fd, root_hash, root_hash_size, verity_data, flags, ret);
1677
1678 switch (r) {
1679
1680 case -EOPNOTSUPP:
1681 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
1682
1683 case -ENOPKG:
1684 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
1685
1686 case -EADDRNOTAVAIL:
1687 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
1688
1689 case -ENOTUNIQ:
1690 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
1691
1692 case -ENXIO:
1693 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
1694
1695 case -EPROTONOSUPPORT:
1696 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
1697
1698 default:
1699 if (r < 0)
1700 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
1701
1702 return r;
1703 }
1704 }
1705
1706 bool dissected_image_can_do_verity(const DissectedImage *image, unsigned partition_designator) {
1707 if (image->single_file_system)
1708 return partition_designator == PARTITION_ROOT && image->can_verity;
1709
1710 return PARTITION_VERITY_OF(partition_designator) >= 0;
1711 }
1712
1713 bool dissected_image_has_verity(const DissectedImage *image, unsigned partition_designator) {
1714 int k;
1715
1716 if (image->single_file_system)
1717 return partition_designator == PARTITION_ROOT && image->verity;
1718
1719 k = PARTITION_VERITY_OF(partition_designator);
1720 return k >= 0 && image->partitions[k].found;
1721 }
1722
1723 static const char *const partition_designator_table[] = {
1724 [PARTITION_ROOT] = "root",
1725 [PARTITION_ROOT_SECONDARY] = "root-secondary",
1726 [PARTITION_HOME] = "home",
1727 [PARTITION_SRV] = "srv",
1728 [PARTITION_ESP] = "esp",
1729 [PARTITION_XBOOTLDR] = "xbootldr",
1730 [PARTITION_SWAP] = "swap",
1731 [PARTITION_ROOT_VERITY] = "root-verity",
1732 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
1733 [PARTITION_TMP] = "tmp",
1734 [PARTITION_VAR] = "var",
1735 };
1736
1737 DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);