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