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