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