]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
Merge pull request #10963 from poettering/bus-force-state-change-signal
[thirdparty/systemd.git] / src / shared / dissect-image.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <sys/mount.h>
4 #include <sys/prctl.h>
5 #include <sys/wait.h>
6
7 #include "sd-device.h"
8 #include "sd-id128.h"
9
10 #include "architecture.h"
11 #include "ask-password-api.h"
12 #include "blkid-util.h"
13 #include "blockdev-util.h"
14 #include "copy.h"
15 #include "crypt-util.h"
16 #include "def.h"
17 #include "device-nodes.h"
18 #include "device-util.h"
19 #include "dissect-image.h"
20 #include "env-file.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 #include "fs-util.h"
24 #include "gpt.h"
25 #include "hexdecoct.h"
26 #include "hostname-util.h"
27 #include "id128-util.h"
28 #include "linux-3.13/dm-ioctl.h"
29 #include "missing.h"
30 #include "mount-util.h"
31 #include "mountpoint-util.h"
32 #include "os-util.h"
33 #include "path-util.h"
34 #include "process-util.h"
35 #include "raw-clone.h"
36 #include "signal-util.h"
37 #include "stat-util.h"
38 #include "stdio-util.h"
39 #include "string-table.h"
40 #include "string-util.h"
41 #include "strv.h"
42 #include "tmpfile-util.h"
43 #include "user-util.h"
44 #include "xattr-util.h"
45
46 int probe_filesystem(const char *node, char **ret_fstype) {
47 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
48 * 0/NULL will be returned. -EUCLEAN will be returned for ambigous results, and an
49 * different error otherwise. */
50
51 #if HAVE_BLKID
52 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
53 const char *fstype;
54 int r;
55
56 errno = 0;
57 b = blkid_new_probe_from_filename(node);
58 if (!b)
59 return -errno ?: -ENOMEM;
60
61 blkid_probe_enable_superblocks(b, 1);
62 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
63
64 errno = 0;
65 r = blkid_do_safeprobe(b);
66 if (r == 1) {
67 log_debug("No type detected on partition %s", node);
68 goto not_found;
69 }
70 if (r == -2) {
71 log_debug("Results ambiguous for partition %s", node);
72 return -EUCLEAN;
73 }
74 if (r != 0)
75 return -errno ?: -EIO;
76
77 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
78
79 if (fstype) {
80 char *t;
81
82 t = strdup(fstype);
83 if (!t)
84 return -ENOMEM;
85
86 *ret_fstype = t;
87 return 1;
88 }
89
90 not_found:
91 *ret_fstype = NULL;
92 return 0;
93 #else
94 return -EOPNOTSUPP;
95 #endif
96 }
97
98 #if HAVE_BLKID
99 /* Detect RPMB and Boot partitions, which are not listed by blkid.
100 * See https://github.com/systemd/systemd/issues/5806. */
101 static bool device_is_mmc_special_partition(sd_device *d) {
102 const char *sysname;
103
104 if (sd_device_get_sysname(d, &sysname) < 0)
105 return false;
106
107 return startswith(sysname, "mmcblk") &&
108 (endswith(sysname, "rpmb") || endswith(sysname, "boot0") || endswith(sysname, "boot1"));
109 }
110
111 static bool device_is_block(sd_device *d) {
112 const char *ss;
113
114 if (sd_device_get_subsystem(d, &ss) < 0)
115 return false;
116
117 return streq(ss, "block");
118 }
119 #endif
120
121 int dissect_image(
122 int fd,
123 const void *root_hash,
124 size_t root_hash_size,
125 DissectImageFlags flags,
126 DissectedImage **ret) {
127
128 #if HAVE_BLKID
129 sd_id128_t root_uuid = SD_ID128_NULL, verity_uuid = SD_ID128_NULL;
130 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
131 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
132 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
133 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
134 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
135 _cleanup_free_ char *generic_node = NULL;
136 sd_id128_t generic_uuid = SD_ID128_NULL;
137 const char *pttype = NULL;
138 blkid_partlist pl;
139 int r, generic_nr;
140 struct stat st;
141 sd_device *q;
142 unsigned i;
143
144 assert(fd >= 0);
145 assert(ret);
146 assert(root_hash || root_hash_size == 0);
147
148 /* Probes a disk image, and returns information about what it found in *ret.
149 *
150 * Returns -ENOPKG if no suitable partition table or file system could be found.
151 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
152
153 if (root_hash) {
154 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
155 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
156 * 128bit. */
157
158 if (root_hash_size < sizeof(sd_id128_t))
159 return -EINVAL;
160
161 memcpy(&root_uuid, root_hash, sizeof(sd_id128_t));
162 memcpy(&verity_uuid, (const uint8_t*) root_hash + root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
163
164 if (sd_id128_is_null(root_uuid))
165 return -EINVAL;
166 if (sd_id128_is_null(verity_uuid))
167 return -EINVAL;
168 }
169
170 if (fstat(fd, &st) < 0)
171 return -errno;
172
173 if (!S_ISBLK(st.st_mode))
174 return -ENOTBLK;
175
176 b = blkid_new_probe();
177 if (!b)
178 return -ENOMEM;
179
180 errno = 0;
181 r = blkid_probe_set_device(b, fd, 0, 0);
182 if (r != 0)
183 return -errno ?: -ENOMEM;
184
185 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
186 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
187 blkid_probe_enable_superblocks(b, 1);
188 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
189 }
190
191 blkid_probe_enable_partitions(b, 1);
192 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
193
194 errno = 0;
195 r = blkid_do_safeprobe(b);
196 if (IN_SET(r, -2, 1)) {
197 log_debug("Failed to identify any partition table.");
198 return -ENOPKG;
199 }
200 if (r != 0)
201 return -errno ?: -EIO;
202
203 m = new0(DissectedImage, 1);
204 if (!m)
205 return -ENOMEM;
206
207 if (!(flags & DISSECT_IMAGE_GPT_ONLY) &&
208 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) {
209 const char *usage = NULL;
210
211 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
212 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
213 _cleanup_free_ char *t = NULL, *n = NULL;
214 const char *fstype = NULL;
215
216 /* OK, we have found a file system, that's our root partition then. */
217 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
218
219 if (fstype) {
220 t = strdup(fstype);
221 if (!t)
222 return -ENOMEM;
223 }
224
225 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
226 if (r < 0)
227 return r;
228
229 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
230 .found = true,
231 .rw = true,
232 .partno = -1,
233 .architecture = _ARCHITECTURE_INVALID,
234 .fstype = TAKE_PTR(t),
235 .node = TAKE_PTR(n),
236 };
237
238 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
239
240 *ret = TAKE_PTR(m);
241
242 return 0;
243 }
244 }
245
246 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
247 if (!pttype)
248 return -ENOPKG;
249
250 is_gpt = streq_ptr(pttype, "gpt");
251 is_mbr = streq_ptr(pttype, "dos");
252
253 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
254 return -ENOPKG;
255
256 errno = 0;
257 pl = blkid_probe_get_partitions(b);
258 if (!pl)
259 return -errno ?: -ENOMEM;
260
261 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
262 if (r < 0)
263 return r;
264
265 for (i = 0;; i++) {
266 int n, z;
267
268 if (i >= 10) {
269 log_debug("Kernel partitions never appeared.");
270 return -ENXIO;
271 }
272
273 r = sd_device_enumerator_new(&e);
274 if (r < 0)
275 return r;
276
277 r = sd_device_enumerator_allow_uninitialized(e);
278 if (r < 0)
279 return r;
280
281 r = sd_device_enumerator_add_match_parent(e, d);
282 if (r < 0)
283 return r;
284
285 /* Count the partitions enumerated by the kernel */
286 n = 0;
287 FOREACH_DEVICE(e, q) {
288 if (sd_device_get_devnum(q, NULL) < 0)
289 continue;
290
291 if (!device_is_block(q))
292 continue;
293
294 if (device_is_mmc_special_partition(q))
295 continue;
296 n++;
297 }
298
299 /* Count the partitions enumerated by blkid */
300 z = blkid_partlist_numof_partitions(pl);
301 if (n == z + 1)
302 break;
303 if (n > z + 1) {
304 log_debug("blkid and kernel partition list do not match.");
305 return -EIO;
306 }
307 if (n < z + 1) {
308 unsigned j = 0;
309
310 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running
311 * or it got EBUSY because udev already opened the device. Let's reprobe the device, which is a
312 * synchronous call that waits until probing is complete. */
313
314 for (;;) {
315 if (j++ > 20)
316 return -EBUSY;
317
318 if (ioctl(fd, BLKRRPART, 0) < 0) {
319 r = -errno;
320
321 if (r == -EINVAL) {
322 struct loop_info64 info;
323
324 /* If we are running on a loop device that has partition scanning off,
325 * return an explicit recognizable error about this, so that callers
326 * can generate a proper message explaining the situation. */
327
328 if (ioctl(fd, LOOP_GET_STATUS64, &info) >= 0 && (info.lo_flags & LO_FLAGS_PARTSCAN) == 0) {
329 log_debug("Device is loop device and partition scanning is off!");
330 return -EPROTONOSUPPORT;
331 }
332 }
333 if (r != -EBUSY)
334 return r;
335 } else
336 break;
337
338 /* If something else has the device open, such as an udev rule, the ioctl will return
339 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a
340 * bit, and try again.
341 *
342 * This is really something they should fix in the kernel! */
343
344 (void) usleep(50 * USEC_PER_MSEC);
345 }
346 }
347
348 e = sd_device_enumerator_unref(e);
349 }
350
351 FOREACH_DEVICE(e, q) {
352 unsigned long long pflags;
353 blkid_partition pp;
354 const char *node;
355 dev_t qn;
356 int nr;
357
358 r = sd_device_get_devnum(q, &qn);
359 if (r < 0)
360 continue;
361
362 if (st.st_rdev == qn)
363 continue;
364
365 if (!device_is_block(q))
366 continue;
367
368 if (device_is_mmc_special_partition(q))
369 continue;
370
371 r = sd_device_get_devname(q, &node);
372 if (r < 0)
373 continue;
374
375 pp = blkid_partlist_devno_to_partition(pl, qn);
376 if (!pp)
377 continue;
378
379 pflags = blkid_partition_get_flags(pp);
380
381 nr = blkid_partition_get_partno(pp);
382 if (nr < 0)
383 continue;
384
385 if (is_gpt) {
386 int designator = _PARTITION_DESIGNATOR_INVALID, architecture = _ARCHITECTURE_INVALID;
387 const char *stype, *sid, *fstype = NULL;
388 sd_id128_t type_id, id;
389 bool rw = true;
390
391 sid = blkid_partition_get_uuid(pp);
392 if (!sid)
393 continue;
394 if (sd_id128_from_string(sid, &id) < 0)
395 continue;
396
397 stype = blkid_partition_get_type_string(pp);
398 if (!stype)
399 continue;
400 if (sd_id128_from_string(stype, &type_id) < 0)
401 continue;
402
403 if (sd_id128_equal(type_id, GPT_HOME)) {
404
405 if (pflags & GPT_FLAG_NO_AUTO)
406 continue;
407
408 designator = PARTITION_HOME;
409 rw = !(pflags & GPT_FLAG_READ_ONLY);
410 } else if (sd_id128_equal(type_id, GPT_SRV)) {
411
412 if (pflags & GPT_FLAG_NO_AUTO)
413 continue;
414
415 designator = PARTITION_SRV;
416 rw = !(pflags & GPT_FLAG_READ_ONLY);
417 } else if (sd_id128_equal(type_id, GPT_ESP)) {
418
419 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
420 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
421 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
422
423 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
424 continue;
425
426 designator = PARTITION_ESP;
427 fstype = "vfat";
428 }
429 #ifdef GPT_ROOT_NATIVE
430 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
431
432 if (pflags & GPT_FLAG_NO_AUTO)
433 continue;
434
435 /* If a root ID is specified, ignore everything but the root id */
436 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
437 continue;
438
439 designator = PARTITION_ROOT;
440 architecture = native_architecture();
441 rw = !(pflags & GPT_FLAG_READ_ONLY);
442 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
443
444 if (pflags & GPT_FLAG_NO_AUTO)
445 continue;
446
447 m->can_verity = true;
448
449 /* Ignore verity unless a root hash is specified */
450 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
451 continue;
452
453 designator = PARTITION_ROOT_VERITY;
454 fstype = "DM_verity_hash";
455 architecture = native_architecture();
456 rw = false;
457 }
458 #endif
459 #ifdef GPT_ROOT_SECONDARY
460 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
461
462 if (pflags & GPT_FLAG_NO_AUTO)
463 continue;
464
465 /* If a root ID is specified, ignore everything but the root id */
466 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
467 continue;
468
469 designator = PARTITION_ROOT_SECONDARY;
470 architecture = SECONDARY_ARCHITECTURE;
471 rw = !(pflags & GPT_FLAG_READ_ONLY);
472 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
473
474 if (pflags & GPT_FLAG_NO_AUTO)
475 continue;
476
477 m->can_verity = true;
478
479 /* Ignore verity unless root has is specified */
480 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
481 continue;
482
483 designator = PARTITION_ROOT_SECONDARY_VERITY;
484 fstype = "DM_verity_hash";
485 architecture = SECONDARY_ARCHITECTURE;
486 rw = false;
487 }
488 #endif
489 else if (sd_id128_equal(type_id, GPT_SWAP)) {
490
491 if (pflags & GPT_FLAG_NO_AUTO)
492 continue;
493
494 designator = PARTITION_SWAP;
495 fstype = "swap";
496 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
497
498 if (pflags & GPT_FLAG_NO_AUTO)
499 continue;
500
501 if (generic_node)
502 multiple_generic = true;
503 else {
504 generic_nr = nr;
505 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
506 generic_uuid = id;
507 generic_node = strdup(node);
508 if (!generic_node)
509 return -ENOMEM;
510 }
511 }
512
513 if (designator != _PARTITION_DESIGNATOR_INVALID) {
514 _cleanup_free_ char *t = NULL, *n = NULL;
515
516 /* First one wins */
517 if (m->partitions[designator].found)
518 continue;
519
520 if (fstype) {
521 t = strdup(fstype);
522 if (!t)
523 return -ENOMEM;
524 }
525
526 n = strdup(node);
527 if (!n)
528 return -ENOMEM;
529
530 m->partitions[designator] = (DissectedPartition) {
531 .found = true,
532 .partno = nr,
533 .rw = rw,
534 .architecture = architecture,
535 .node = TAKE_PTR(n),
536 .fstype = TAKE_PTR(t),
537 .uuid = id,
538 };
539 }
540
541 } else if (is_mbr) {
542
543 if (pflags != 0x80) /* Bootable flag */
544 continue;
545
546 if (blkid_partition_get_type(pp) != 0x83) /* Linux partition */
547 continue;
548
549 if (generic_node)
550 multiple_generic = true;
551 else {
552 generic_nr = nr;
553 generic_rw = true;
554 generic_node = strdup(node);
555 if (!generic_node)
556 return -ENOMEM;
557 }
558 }
559 }
560
561 if (!m->partitions[PARTITION_ROOT].found) {
562 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
563 * either, then check if there's a single generic one, and use that. */
564
565 if (m->partitions[PARTITION_ROOT_VERITY].found)
566 return -EADDRNOTAVAIL;
567
568 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
569 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
570 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
571
572 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
573 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
574
575 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
576
577 /* If the root has was set, then we won't fallback to a generic node, because the root hash
578 * decides */
579 if (root_hash)
580 return -EADDRNOTAVAIL;
581
582 /* If we didn't find a generic node, then we can't fix this up either */
583 if (!generic_node)
584 return -ENXIO;
585
586 /* If we didn't find a properly marked root partition, but we did find a single suitable
587 * generic Linux partition, then use this as root partition, if the caller asked for it. */
588 if (multiple_generic)
589 return -ENOTUNIQ;
590
591 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
592 .found = true,
593 .rw = generic_rw,
594 .partno = generic_nr,
595 .architecture = _ARCHITECTURE_INVALID,
596 .node = TAKE_PTR(generic_node),
597 .uuid = generic_uuid,
598 };
599 }
600 }
601
602 if (root_hash) {
603 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
604 return -EADDRNOTAVAIL;
605
606 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
607 * (which would be weird, after all the root hash should only be assigned to one pair of
608 * partitions... */
609 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
610 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
611
612 /* If we found a verity setup, then the root partition is necessarily read-only. */
613 m->partitions[PARTITION_ROOT].rw = false;
614
615 m->verity = true;
616 }
617
618 blkid_free_probe(b);
619 b = NULL;
620
621 /* Fill in file system types if we don't know them yet. */
622 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
623 DissectedPartition *p = m->partitions + i;
624
625 if (!p->found)
626 continue;
627
628 if (!p->fstype && p->node) {
629 r = probe_filesystem(p->node, &p->fstype);
630 if (r < 0 && r != -EUCLEAN)
631 return r;
632 }
633
634 if (streq_ptr(p->fstype, "crypto_LUKS"))
635 m->encrypted = true;
636
637 if (p->fstype && fstype_is_ro(p->fstype))
638 p->rw = false;
639 }
640
641 *ret = TAKE_PTR(m);
642
643 return 0;
644 #else
645 return -EOPNOTSUPP;
646 #endif
647 }
648
649 DissectedImage* dissected_image_unref(DissectedImage *m) {
650 unsigned i;
651
652 if (!m)
653 return NULL;
654
655 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
656 free(m->partitions[i].fstype);
657 free(m->partitions[i].node);
658 free(m->partitions[i].decrypted_fstype);
659 free(m->partitions[i].decrypted_node);
660 }
661
662 free(m->hostname);
663 strv_free(m->machine_info);
664 strv_free(m->os_release);
665
666 return mfree(m);
667 }
668
669 static int is_loop_device(const char *path) {
670 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
671 struct stat st;
672
673 assert(path);
674
675 if (stat(path, &st) < 0)
676 return -errno;
677
678 if (!S_ISBLK(st.st_mode))
679 return -ENOTBLK;
680
681 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
682 if (access(s, F_OK) < 0) {
683 if (errno != ENOENT)
684 return -errno;
685
686 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
687 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
688 if (access(s, F_OK) < 0)
689 return errno == ENOENT ? false : -errno;
690 }
691
692 return true;
693 }
694
695 static int mount_partition(
696 DissectedPartition *m,
697 const char *where,
698 const char *directory,
699 uid_t uid_shift,
700 DissectImageFlags flags) {
701
702 _cleanup_free_ char *chased = NULL, *options = NULL;
703 const char *p, *node, *fstype;
704 bool rw;
705 int r;
706
707 assert(m);
708 assert(where);
709
710 node = m->decrypted_node ?: m->node;
711 fstype = m->decrypted_fstype ?: m->fstype;
712
713 if (!m->found || !node || !fstype)
714 return 0;
715
716 /* Stacked encryption? Yuck */
717 if (streq_ptr(fstype, "crypto_LUKS"))
718 return -ELOOP;
719
720 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
721
722 if (directory) {
723 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased);
724 if (r < 0)
725 return r;
726
727 p = chased;
728 } else
729 p = where;
730
731 /* If requested, turn on discard support. */
732 if (fstype_can_discard(fstype) &&
733 ((flags & DISSECT_IMAGE_DISCARD) ||
734 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node)))) {
735 options = strdup("discard");
736 if (!options)
737 return -ENOMEM;
738 }
739
740 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
741 _cleanup_free_ char *uid_option = NULL;
742
743 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
744 return -ENOMEM;
745
746 if (!strextend_with_separator(&options, ",", uid_option, NULL))
747 return -ENOMEM;
748 }
749
750 return mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
751 }
752
753 int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
754 int r;
755
756 assert(m);
757 assert(where);
758
759 if (!m->partitions[PARTITION_ROOT].found)
760 return -ENXIO;
761
762 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
763 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
764 if (r < 0)
765 return r;
766
767 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
768 r = path_is_os_tree(where);
769 if (r < 0)
770 return r;
771 if (r == 0)
772 return -EMEDIUMTYPE;
773 }
774 }
775
776 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
777 return 0;
778
779 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
780 if (r < 0)
781 return r;
782
783 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
784 if (r < 0)
785 return r;
786
787 if (m->partitions[PARTITION_ESP].found) {
788 const char *mp;
789
790 /* Mount the ESP to /efi if it exists and is empty. If it doesn't exist, use /boot instead. */
791
792 FOREACH_STRING(mp, "/efi", "/boot") {
793 _cleanup_free_ char *p = NULL;
794
795 r = chase_symlinks(mp, where, CHASE_PREFIX_ROOT, &p);
796 if (r < 0)
797 continue;
798
799 r = dir_is_empty(p);
800 if (r > 0) {
801 r = mount_partition(m->partitions + PARTITION_ESP, where, mp, uid_shift, flags);
802 if (r < 0)
803 return r;
804 }
805 }
806 }
807
808 return 0;
809 }
810
811 #if HAVE_LIBCRYPTSETUP
812 typedef struct DecryptedPartition {
813 struct crypt_device *device;
814 char *name;
815 bool relinquished;
816 } DecryptedPartition;
817
818 struct DecryptedImage {
819 DecryptedPartition *decrypted;
820 size_t n_decrypted;
821 size_t n_allocated;
822 };
823 #endif
824
825 DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
826 #if HAVE_LIBCRYPTSETUP
827 size_t i;
828 int r;
829
830 if (!d)
831 return NULL;
832
833 for (i = 0; i < d->n_decrypted; i++) {
834 DecryptedPartition *p = d->decrypted + i;
835
836 if (p->device && p->name && !p->relinquished) {
837 r = crypt_deactivate(p->device, p->name);
838 if (r < 0)
839 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
840 }
841
842 if (p->device)
843 crypt_free(p->device);
844 free(p->name);
845 }
846
847 free(d);
848 #endif
849 return NULL;
850 }
851
852 #if HAVE_LIBCRYPTSETUP
853
854 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
855 _cleanup_free_ char *name = NULL, *node = NULL;
856 const char *base;
857
858 assert(original_node);
859 assert(suffix);
860 assert(ret_name);
861 assert(ret_node);
862
863 base = strrchr(original_node, '/');
864 if (!base)
865 return -EINVAL;
866 base++;
867 if (isempty(base))
868 return -EINVAL;
869
870 name = strjoin(base, suffix);
871 if (!name)
872 return -ENOMEM;
873 if (!filename_is_valid(name))
874 return -EINVAL;
875
876 node = strjoin(crypt_get_dir(), "/", name);
877 if (!node)
878 return -ENOMEM;
879
880 *ret_name = TAKE_PTR(name);
881 *ret_node = TAKE_PTR(node);
882
883 return 0;
884 }
885
886 static int decrypt_partition(
887 DissectedPartition *m,
888 const char *passphrase,
889 DissectImageFlags flags,
890 DecryptedImage *d) {
891
892 _cleanup_free_ char *node = NULL, *name = NULL;
893 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
894 int r;
895
896 assert(m);
897 assert(d);
898
899 if (!m->found || !m->node || !m->fstype)
900 return 0;
901
902 if (!streq(m->fstype, "crypto_LUKS"))
903 return 0;
904
905 if (!passphrase)
906 return -ENOKEY;
907
908 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
909 if (r < 0)
910 return r;
911
912 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
913 return -ENOMEM;
914
915 r = crypt_init(&cd, m->node);
916 if (r < 0)
917 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
918
919 r = crypt_load(cd, CRYPT_LUKS, NULL);
920 if (r < 0)
921 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
922
923 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
924 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
925 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
926 if (r < 0) {
927 log_debug_errno(r, "Failed to activate LUKS device: %m");
928 return r == -EPERM ? -EKEYREJECTED : r;
929 }
930
931 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
932 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
933 d->n_decrypted++;
934
935 m->decrypted_node = TAKE_PTR(node);
936
937 return 0;
938 }
939
940 static int verity_partition(
941 DissectedPartition *m,
942 DissectedPartition *v,
943 const void *root_hash,
944 size_t root_hash_size,
945 DissectImageFlags flags,
946 DecryptedImage *d) {
947
948 _cleanup_free_ char *node = NULL, *name = NULL;
949 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
950 int r;
951
952 assert(m);
953 assert(v);
954
955 if (!root_hash)
956 return 0;
957
958 if (!m->found || !m->node || !m->fstype)
959 return 0;
960 if (!v->found || !v->node || !v->fstype)
961 return 0;
962
963 if (!streq(v->fstype, "DM_verity_hash"))
964 return 0;
965
966 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
967 if (r < 0)
968 return r;
969
970 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
971 return -ENOMEM;
972
973 r = crypt_init(&cd, v->node);
974 if (r < 0)
975 return r;
976
977 r = crypt_load(cd, CRYPT_VERITY, NULL);
978 if (r < 0)
979 return r;
980
981 r = crypt_set_data_device(cd, m->node);
982 if (r < 0)
983 return r;
984
985 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
986 if (r < 0)
987 return r;
988
989 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
990 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
991 d->n_decrypted++;
992
993 m->decrypted_node = TAKE_PTR(node);
994
995 return 0;
996 }
997 #endif
998
999 int dissected_image_decrypt(
1000 DissectedImage *m,
1001 const char *passphrase,
1002 const void *root_hash,
1003 size_t root_hash_size,
1004 DissectImageFlags flags,
1005 DecryptedImage **ret) {
1006
1007 #if HAVE_LIBCRYPTSETUP
1008 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
1009 unsigned i;
1010 int r;
1011 #endif
1012
1013 assert(m);
1014 assert(root_hash || root_hash_size == 0);
1015
1016 /* Returns:
1017 *
1018 * = 0 → There was nothing to decrypt
1019 * > 0 → Decrypted successfully
1020 * -ENOKEY → There's something to decrypt but no key was supplied
1021 * -EKEYREJECTED → Passed key was not correct
1022 */
1023
1024 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1025 return -EINVAL;
1026
1027 if (!m->encrypted && !m->verity) {
1028 *ret = NULL;
1029 return 0;
1030 }
1031
1032 #if HAVE_LIBCRYPTSETUP
1033 d = new0(DecryptedImage, 1);
1034 if (!d)
1035 return -ENOMEM;
1036
1037 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1038 DissectedPartition *p = m->partitions + i;
1039 int k;
1040
1041 if (!p->found)
1042 continue;
1043
1044 r = decrypt_partition(p, passphrase, flags, d);
1045 if (r < 0)
1046 return r;
1047
1048 k = PARTITION_VERITY_OF(i);
1049 if (k >= 0) {
1050 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, flags, d);
1051 if (r < 0)
1052 return r;
1053 }
1054
1055 if (!p->decrypted_fstype && p->decrypted_node) {
1056 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
1057 if (r < 0 && r != -EUCLEAN)
1058 return r;
1059 }
1060 }
1061
1062 *ret = TAKE_PTR(d);
1063
1064 return 1;
1065 #else
1066 return -EOPNOTSUPP;
1067 #endif
1068 }
1069
1070 int dissected_image_decrypt_interactively(
1071 DissectedImage *m,
1072 const char *passphrase,
1073 const void *root_hash,
1074 size_t root_hash_size,
1075 DissectImageFlags flags,
1076 DecryptedImage **ret) {
1077
1078 _cleanup_strv_free_erase_ char **z = NULL;
1079 int n = 3, r;
1080
1081 if (passphrase)
1082 n--;
1083
1084 for (;;) {
1085 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, flags, ret);
1086 if (r >= 0)
1087 return r;
1088 if (r == -EKEYREJECTED)
1089 log_error_errno(r, "Incorrect passphrase, try again!");
1090 else if (r != -ENOKEY)
1091 return log_error_errno(r, "Failed to decrypt image: %m");
1092
1093 if (--n < 0)
1094 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1095 "Too many retries.");
1096
1097 z = strv_free(z);
1098
1099 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
1100 if (r < 0)
1101 return log_error_errno(r, "Failed to query for passphrase: %m");
1102
1103 passphrase = z[0];
1104 }
1105 }
1106
1107 #if HAVE_LIBCRYPTSETUP
1108 static int deferred_remove(DecryptedPartition *p) {
1109
1110 struct dm_ioctl dm = {
1111 .version = {
1112 DM_VERSION_MAJOR,
1113 DM_VERSION_MINOR,
1114 DM_VERSION_PATCHLEVEL
1115 },
1116 .data_size = sizeof(dm),
1117 .flags = DM_DEFERRED_REMOVE,
1118 };
1119
1120 _cleanup_close_ int fd = -1;
1121
1122 assert(p);
1123
1124 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1125
1126 fd = open("/dev/mapper/control", O_RDWR|O_CLOEXEC);
1127 if (fd < 0)
1128 return -errno;
1129
1130 strncpy(dm.name, p->name, sizeof(dm.name));
1131
1132 if (ioctl(fd, DM_DEV_REMOVE, &dm))
1133 return -errno;
1134
1135 return 0;
1136 }
1137 #endif
1138
1139 int decrypted_image_relinquish(DecryptedImage *d) {
1140
1141 #if HAVE_LIBCRYPTSETUP
1142 size_t i;
1143 int r;
1144 #endif
1145
1146 assert(d);
1147
1148 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1149 * that we don't clean it up ourselves either anymore */
1150
1151 #if HAVE_LIBCRYPTSETUP
1152 for (i = 0; i < d->n_decrypted; i++) {
1153 DecryptedPartition *p = d->decrypted + i;
1154
1155 if (p->relinquished)
1156 continue;
1157
1158 r = deferred_remove(p);
1159 if (r < 0)
1160 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1161
1162 p->relinquished = true;
1163 }
1164 #endif
1165
1166 return 0;
1167 }
1168
1169 int root_hash_load(const char *image, void **ret, size_t *ret_size) {
1170 _cleanup_free_ char *text = NULL;
1171 _cleanup_free_ void *k = NULL;
1172 size_t l;
1173 int r;
1174
1175 assert(image);
1176 assert(ret);
1177 assert(ret_size);
1178
1179 if (is_device_path(image)) {
1180 /* If we are asked to load the root hash for a device node, exit early */
1181 *ret = NULL;
1182 *ret_size = 0;
1183 return 0;
1184 }
1185
1186 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1187 if (r < 0) {
1188 char *fn, *e, *n;
1189
1190 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1191 return r;
1192
1193 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
1194 n = stpcpy(fn, image);
1195 e = endswith(fn, ".raw");
1196 if (e)
1197 n = e;
1198
1199 strcpy(n, ".roothash");
1200
1201 r = read_one_line_file(fn, &text);
1202 if (r == -ENOENT) {
1203 *ret = NULL;
1204 *ret_size = 0;
1205 return 0;
1206 }
1207 if (r < 0)
1208 return r;
1209 }
1210
1211 r = unhexmem(text, strlen(text), &k, &l);
1212 if (r < 0)
1213 return r;
1214 if (l < sizeof(sd_id128_t))
1215 return -EINVAL;
1216
1217 *ret = TAKE_PTR(k);
1218 *ret_size = l;
1219
1220 return 1;
1221 }
1222
1223 int dissected_image_acquire_metadata(DissectedImage *m) {
1224
1225 enum {
1226 META_HOSTNAME,
1227 META_MACHINE_ID,
1228 META_MACHINE_INFO,
1229 META_OS_RELEASE,
1230 _META_MAX,
1231 };
1232
1233 static const char *const paths[_META_MAX] = {
1234 [META_HOSTNAME] = "/etc/hostname\0",
1235 [META_MACHINE_ID] = "/etc/machine-id\0",
1236 [META_MACHINE_INFO] = "/etc/machine-info\0",
1237 [META_OS_RELEASE] = "/etc/os-release\0/usr/lib/os-release\0",
1238 };
1239
1240 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
1241 _cleanup_(rmdir_and_freep) char *t = NULL;
1242 _cleanup_(sigkill_waitp) pid_t child = 0;
1243 sd_id128_t machine_id = SD_ID128_NULL;
1244 _cleanup_free_ char *hostname = NULL;
1245 unsigned n_meta_initialized = 0, k;
1246 int fds[2 * _META_MAX], r;
1247
1248 BLOCK_SIGNALS(SIGCHLD);
1249
1250 assert(m);
1251
1252 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1253 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1254 r = -errno;
1255 goto finish;
1256 }
1257
1258 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1259 if (r < 0)
1260 goto finish;
1261
1262 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
1263 if (r < 0)
1264 goto finish;
1265 if (r == 0) {
1266 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
1267 if (r < 0) {
1268 log_debug_errno(r, "Failed to mount dissected image: %m");
1269 _exit(EXIT_FAILURE);
1270 }
1271
1272 for (k = 0; k < _META_MAX; k++) {
1273 _cleanup_close_ int fd = -1;
1274 const char *p;
1275
1276 fds[2*k] = safe_close(fds[2*k]);
1277
1278 NULSTR_FOREACH(p, paths[k]) {
1279 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
1280 if (fd >= 0)
1281 break;
1282 }
1283 if (fd < 0) {
1284 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
1285 continue;
1286 }
1287
1288 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
1289 if (r < 0)
1290 _exit(EXIT_FAILURE);
1291
1292 fds[2*k+1] = safe_close(fds[2*k+1]);
1293 }
1294
1295 _exit(EXIT_SUCCESS);
1296 }
1297
1298 for (k = 0; k < _META_MAX; k++) {
1299 _cleanup_fclose_ FILE *f = NULL;
1300
1301 fds[2*k+1] = safe_close(fds[2*k+1]);
1302
1303 f = fdopen(fds[2*k], "re");
1304 if (!f) {
1305 r = -errno;
1306 goto finish;
1307 }
1308
1309 fds[2*k] = -1;
1310
1311 switch (k) {
1312
1313 case META_HOSTNAME:
1314 r = read_etc_hostname_stream(f, &hostname);
1315 if (r < 0)
1316 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1317
1318 break;
1319
1320 case META_MACHINE_ID: {
1321 _cleanup_free_ char *line = NULL;
1322
1323 r = read_line(f, LONG_LINE_MAX, &line);
1324 if (r < 0)
1325 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1326 else if (r == 33) {
1327 r = sd_id128_from_string(line, &machine_id);
1328 if (r < 0)
1329 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1330 } else if (r == 0)
1331 log_debug("/etc/machine-id file is empty.");
1332 else
1333 log_debug("/etc/machine-id has unexpected length %i.", r);
1334
1335 break;
1336 }
1337
1338 case META_MACHINE_INFO:
1339 r = load_env_file_pairs(f, "machine-info", &machine_info);
1340 if (r < 0)
1341 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1342
1343 break;
1344
1345 case META_OS_RELEASE:
1346 r = load_env_file_pairs(f, "os-release", &os_release);
1347 if (r < 0)
1348 log_debug_errno(r, "Failed to read OS release file: %m");
1349
1350 break;
1351 }
1352 }
1353
1354 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
1355 child = 0;
1356 if (r < 0)
1357 goto finish;
1358 if (r != EXIT_SUCCESS)
1359 return -EPROTO;
1360
1361 free_and_replace(m->hostname, hostname);
1362 m->machine_id = machine_id;
1363 strv_free_and_replace(m->machine_info, machine_info);
1364 strv_free_and_replace(m->os_release, os_release);
1365
1366 finish:
1367 for (k = 0; k < n_meta_initialized; k++)
1368 safe_close_pair(fds + 2*k);
1369
1370 return r;
1371 }
1372
1373 int dissect_image_and_warn(
1374 int fd,
1375 const char *name,
1376 const void *root_hash,
1377 size_t root_hash_size,
1378 DissectImageFlags flags,
1379 DissectedImage **ret) {
1380
1381 _cleanup_free_ char *buffer = NULL;
1382 int r;
1383
1384 if (!name) {
1385 r = fd_get_path(fd, &buffer);
1386 if (r < 0)
1387 return r;
1388
1389 name = buffer;
1390 }
1391
1392 r = dissect_image(fd, root_hash, root_hash_size, flags, ret);
1393
1394 switch (r) {
1395
1396 case -EOPNOTSUPP:
1397 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
1398
1399 case -ENOPKG:
1400 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
1401
1402 case -EADDRNOTAVAIL:
1403 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
1404
1405 case -ENOTUNIQ:
1406 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
1407
1408 case -ENXIO:
1409 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
1410
1411 case -EPROTONOSUPPORT:
1412 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
1413
1414 default:
1415 if (r < 0)
1416 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
1417
1418 return r;
1419 }
1420 }
1421
1422 static const char *const partition_designator_table[] = {
1423 [PARTITION_ROOT] = "root",
1424 [PARTITION_ROOT_SECONDARY] = "root-secondary",
1425 [PARTITION_HOME] = "home",
1426 [PARTITION_SRV] = "srv",
1427 [PARTITION_ESP] = "esp",
1428 [PARTITION_SWAP] = "swap",
1429 [PARTITION_ROOT_VERITY] = "root-verity",
1430 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
1431 };
1432
1433 DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);