]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
Merge pull request #16929 from ssahani/network-bare-udp
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
8c1be37e 2
10c1b188
LP
3#if HAVE_VALGRIND_MEMCHECK_H
4#include <valgrind/memcheck.h>
5#endif
6
01234e1f
YW
7#include <linux/dm-ioctl.h>
8#include <linux/loop.h>
8c1be37e 9#include <sys/mount.h>
3b925504
LP
10#include <sys/prctl.h>
11#include <sys/wait.h>
f5ea63a5 12#include <sysexits.h>
8c1be37e 13
3c1f2cee 14#include "sd-device.h"
dccca82b
LP
15#include "sd-id128.h"
16
8c1be37e 17#include "architecture.h"
18b5886e 18#include "ask-password-api.h"
8c1be37e 19#include "blkid-util.h"
18c528e9 20#include "blockdev-util.h"
3b925504 21#include "copy.h"
1e2f3230 22#include "cryptsetup-util.h"
3b925504 23#include "def.h"
553e15f2 24#include "device-nodes.h"
8437c059 25#include "device-util.h"
8c1be37e 26#include "dissect-image.h"
a709a315 27#include "dm-util.h"
686d13b9 28#include "env-file.h"
18b5886e 29#include "fd-util.h"
78ebe980 30#include "fileio.h"
2eedfd2d 31#include "fs-util.h"
cf32c486 32#include "fsck-util.h"
8c1be37e 33#include "gpt.h"
78ebe980 34#include "hexdecoct.h"
3b925504
LP
35#include "hostname-util.h"
36#include "id128-util.h"
6aa05ebd 37#include "mkdir.h"
8c1be37e 38#include "mount-util.h"
e4de7287 39#include "mountpoint-util.h"
6aa05ebd 40#include "namespace-util.h"
d8b4d14d 41#include "nulstr-util.h"
d58ad743 42#include "os-util.h"
8c1be37e 43#include "path-util.h"
3b925504
LP
44#include "process-util.h"
45#include "raw-clone.h"
46#include "signal-util.h"
8c1be37e 47#include "stat-util.h"
18b5886e 48#include "stdio-util.h"
8c1be37e
LP
49#include "string-table.h"
50#include "string-util.h"
2eedfd2d 51#include "strv.h"
e4de7287 52#include "tmpfile-util.h"
a8040b6d 53#include "udev-util.h"
2d3a5a73 54#include "user-util.h"
41488e1f 55#include "xattr-util.h"
8c1be37e 56
28e2641a
FF
57/* how many times to wait for the device nodes to appear */
58#define N_DEVICE_NODE_LIST_ATTEMPTS 10
59
c34b75a1 60int probe_filesystem(const char *node, char **ret_fstype) {
7cc84b2c 61 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
5238e957 62 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
7cc84b2c
ZJS
63 * different error otherwise. */
64
349cc4a5 65#if HAVE_BLKID
8e766630 66 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
18b5886e
LP
67 const char *fstype;
68 int r;
69
995fa2e5 70 errno = 0;
18b5886e
LP
71 b = blkid_new_probe_from_filename(node);
72 if (!b)
66855de7 73 return errno_or_else(ENOMEM);
18b5886e
LP
74
75 blkid_probe_enable_superblocks(b, 1);
76 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
77
78 errno = 0;
79 r = blkid_do_safeprobe(b);
7cc84b2c
ZJS
80 if (r == 1) {
81 log_debug("No type detected on partition %s", node);
18b5886e
LP
82 goto not_found;
83 }
58dfbfbd
LP
84 if (r == -2)
85 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
86 "Results ambiguous for partition %s", node);
b382db9f 87 if (r != 0)
66855de7 88 return errno_or_else(EIO);
18b5886e
LP
89
90 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
91
92 if (fstype) {
93 char *t;
94
95 t = strdup(fstype);
96 if (!t)
97 return -ENOMEM;
98
99 *ret_fstype = t;
100 return 1;
101 }
102
103not_found:
104 *ret_fstype = NULL;
105 return 0;
d1c536f5
ZJS
106#else
107 return -EOPNOTSUPP;
a75e27eb 108#endif
d1c536f5 109}
18b5886e 110
40c10d3f 111#if HAVE_BLKID
cde942f6
JPRV
112/* Detect RPMB and Boot partitions, which are not listed by blkid.
113 * See https://github.com/systemd/systemd/issues/5806. */
3c1f2cee 114static bool device_is_mmc_special_partition(sd_device *d) {
aae22eb3
LP
115 const char *sysname;
116
f70e7f70
LP
117 assert(d);
118
3c1f2cee
YW
119 if (sd_device_get_sysname(d, &sysname) < 0)
120 return false;
121
122 return startswith(sysname, "mmcblk") &&
0cfa78dd 123 (endswith(sysname, "rpmb") || endswith(sysname, "boot0") || endswith(sysname, "boot1"));
cde942f6
JPRV
124}
125
3c1f2cee 126static bool device_is_block(sd_device *d) {
aae22eb3
LP
127 const char *ss;
128
f70e7f70
LP
129 assert(d);
130
3c1f2cee 131 if (sd_device_get_subsystem(d, &ss) < 0)
aae22eb3
LP
132 return false;
133
134 return streq(ss, "block");
135}
ea887be0
ZJS
136
137static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
138 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
139 int r;
140
f70e7f70
LP
141 assert(d);
142 assert(ret);
143
ea887be0
ZJS
144 r = sd_device_enumerator_new(&e);
145 if (r < 0)
146 return r;
147
148 r = sd_device_enumerator_allow_uninitialized(e);
149 if (r < 0)
150 return r;
151
152 r = sd_device_enumerator_add_match_parent(e, d);
153 if (r < 0)
154 return r;
155
156 *ret = TAKE_PTR(e);
157 return 0;
158}
159
ea887be0
ZJS
160static int wait_for_partitions_to_appear(
161 int fd,
162 sd_device *d,
163 unsigned num_partitions,
052eaf5c 164 DissectImageFlags flags,
ea887be0
ZJS
165 sd_device_enumerator **ret_enumerator) {
166
167 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
168 sd_device *q;
169 unsigned n;
170 int r;
171
f70e7f70
LP
172 assert(fd >= 0);
173 assert(d);
174 assert(ret_enumerator);
175
ea887be0
ZJS
176 r = enumerator_for_parent(d, &e);
177 if (r < 0)
178 return r;
179
180 /* Count the partitions enumerated by the kernel */
181 n = 0;
182 FOREACH_DEVICE(e, q) {
183 if (sd_device_get_devnum(q, NULL) < 0)
184 continue;
185 if (!device_is_block(q))
186 continue;
187 if (device_is_mmc_special_partition(q))
188 continue;
189
052eaf5c 190 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
1b47436e 191 r = device_wait_for_initialization(q, "block", USEC_INFINITY, NULL);
052eaf5c
LP
192 if (r < 0)
193 return r;
194 }
a8040b6d 195
ea887be0
ZJS
196 n++;
197 }
198
199 if (n == num_partitions + 1) {
200 *ret_enumerator = TAKE_PTR(e);
201 return 0; /* success! */
202 }
203 if (n > num_partitions + 1)
204 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
205 "blkid and kernel partition lists do not match.");
206
207 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
208 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
209 * call that waits until probing is complete. */
210
211 for (unsigned j = 0; ; j++) {
212 if (j++ > 20)
213 return -EBUSY;
214
215 if (ioctl(fd, BLKRRPART, 0) >= 0)
216 break;
217 r = -errno;
218 if (r == -EINVAL) {
834c15ec
LP
219 /* If we are running on a block device that has partition scanning off, return an
220 * explicit recognizable error about this, so that callers can generate a proper
221 * message explaining the situation. */
ea887be0 222
834c15ec
LP
223 r = blockdev_partscan_enabled(fd);
224 if (r < 0)
225 return r;
226 if (r == 0)
227 return log_debug_errno(EPROTONOSUPPORT,
228 "Device is a loop device and partition scanning is off!");
10c1b188 229
834c15ec 230 return -EINVAL; /* original error */
ea887be0
ZJS
231 }
232 if (r != -EBUSY)
233 return r;
234
235 /* If something else has the device open, such as an udev rule, the ioctl will return
236 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
237 * and try again.
238 *
239 * This is really something they should fix in the kernel! */
240 (void) usleep(50 * USEC_PER_MSEC);
241
242 }
243
244 return -EAGAIN; /* no success yet, try again */
245}
246
247static int loop_wait_for_partitions_to_appear(
248 int fd,
249 sd_device *d,
250 unsigned num_partitions,
052eaf5c 251 DissectImageFlags flags,
ea887be0 252 sd_device_enumerator **ret_enumerator) {
a8040b6d 253 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
ea887be0
ZJS
254 int r;
255
f70e7f70
LP
256 assert(fd >= 0);
257 assert(d);
258 assert(ret_enumerator);
259
b887c8b8
ZJS
260 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions);
261
052eaf5c 262 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
1b47436e 263 r = device_wait_for_initialization(d, "block", USEC_INFINITY, &device);
052eaf5c
LP
264 if (r < 0)
265 return r;
266 } else
267 device = sd_device_ref(d);
a8040b6d 268
ea887be0 269 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
052eaf5c 270 r = wait_for_partitions_to_appear(fd, device, num_partitions, flags, ret_enumerator);
ea887be0
ZJS
271 if (r != -EAGAIN)
272 return r;
273 }
274
275 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO),
276 "Kernel partitions dit not appear within %d attempts",
277 N_DEVICE_NODE_LIST_ATTEMPTS);
278}
279
0f7c9a3d
LP
280static void check_partition_flags(
281 const char *node,
282 unsigned long long pflags,
283 unsigned long long supported) {
284
285 assert(node);
286
287 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
288 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
289
290 if (pflags == 0)
291 return;
292
293 /* If there are other bits set, then log about it, to make things discoverable */
294 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
295 unsigned long long bit = 1ULL << i;
296 if (!FLAGS_SET(pflags, bit))
297 continue;
298
299 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
300 }
301}
302
40c10d3f 303#endif
aae22eb3 304
4526113f
LP
305int dissect_image(
306 int fd,
307 const void *root_hash,
308 size_t root_hash_size,
e7cbe5cb 309 const char *verity_data,
18d73705 310 const MountOptions *mount_options,
4526113f
LP
311 DissectImageFlags flags,
312 DissectedImage **ret) {
8c1be37e 313
349cc4a5 314#if HAVE_BLKID
4623e8e6 315 sd_id128_t root_uuid = SD_ID128_NULL, verity_uuid = SD_ID128_NULL;
3c1f2cee 316 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
8c1be37e 317 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
3c1f2cee 318 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
8c1be37e 319 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
8e766630 320 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
8c1be37e 321 _cleanup_free_ char *generic_node = NULL;
be30ad41 322 sd_id128_t generic_uuid = SD_ID128_NULL;
9b6deb03 323 const char *pttype = NULL;
8c1be37e
LP
324 blkid_partlist pl;
325 int r, generic_nr;
326 struct stat st;
3c1f2cee 327 sd_device *q;
8c1be37e
LP
328
329 assert(fd >= 0);
330 assert(ret);
4623e8e6 331 assert(root_hash || root_hash_size == 0);
e7cbe5cb 332 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
8c1be37e
LP
333
334 /* Probes a disk image, and returns information about what it found in *ret.
335 *
4623e8e6
LP
336 * Returns -ENOPKG if no suitable partition table or file system could be found.
337 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
338
339 if (root_hash) {
340 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
341 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
342 * 128bit. */
343
344 if (root_hash_size < sizeof(sd_id128_t))
345 return -EINVAL;
346
347 memcpy(&root_uuid, root_hash, sizeof(sd_id128_t));
348 memcpy(&verity_uuid, (const uint8_t*) root_hash + root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
349
350 if (sd_id128_is_null(root_uuid))
351 return -EINVAL;
352 if (sd_id128_is_null(verity_uuid))
353 return -EINVAL;
354 }
8c1be37e
LP
355
356 if (fstat(fd, &st) < 0)
357 return -errno;
358
359 if (!S_ISBLK(st.st_mode))
360 return -ENOTBLK;
361
362 b = blkid_new_probe();
363 if (!b)
364 return -ENOMEM;
365
366 errno = 0;
367 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f 368 if (r != 0)
66855de7 369 return errno_or_else(ENOMEM);
8c1be37e 370
9b6deb03
LP
371 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
372 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
373 blkid_probe_enable_superblocks(b, 1);
374 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
375 }
376
8c1be37e
LP
377 blkid_probe_enable_partitions(b, 1);
378 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
379
380 errno = 0;
381 r = blkid_do_safeprobe(b);
59ba6d0c
LP
382 if (IN_SET(r, -2, 1))
383 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
b382db9f 384 if (r != 0)
66855de7 385 return errno_or_else(EIO);
8c1be37e
LP
386
387 m = new0(DissectedImage, 1);
388 if (!m)
389 return -ENOMEM;
390
b887c8b8
ZJS
391 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
392 if (r < 0)
393 return r;
394
e7cbe5cb
LB
395 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
396 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) ||
397 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
9b6deb03 398 const char *usage = NULL;
8c1be37e 399
9b6deb03
LP
400 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
401 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
18d73705
LB
402 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
403 const char *fstype = NULL, *options = NULL;
8c1be37e 404
9b6deb03
LP
405 /* OK, we have found a file system, that's our root partition then. */
406 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 407
9b6deb03
LP
408 if (fstype) {
409 t = strdup(fstype);
410 if (!t)
411 return -ENOMEM;
412 }
413
54b22b26
LP
414 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
415 if (r < 0)
416 return r;
8c1be37e 417
e7cbe5cb
LB
418 m->single_file_system = true;
419 m->verity = root_hash && verity_data;
420 m->can_verity = !!verity_data;
421
f5215bc8 422 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
423 if (options) {
424 o = strdup(options);
425 if (!o)
426 return -ENOMEM;
427 }
428
9b6deb03
LP
429 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
430 .found = true,
e7cbe5cb 431 .rw = !m->verity,
9b6deb03
LP
432 .partno = -1,
433 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
434 .fstype = TAKE_PTR(t),
435 .node = TAKE_PTR(n),
18d73705 436 .mount_options = TAKE_PTR(o),
9b6deb03 437 };
8c1be37e 438
4db1879a 439 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
18b5886e 440
b1806441
LB
441 /* Even on a single partition we need to wait for udev to create the
442 * /dev/block/X:Y symlink to /dev/loopZ */
443 r = loop_wait_for_partitions_to_appear(fd, d, 0, flags, &e);
444 if (r < 0)
445 return r;
1cc6c93a 446 *ret = TAKE_PTR(m);
8c1be37e 447
9b6deb03
LP
448 return 0;
449 }
8c1be37e
LP
450 }
451
452 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
453 if (!pttype)
454 return -ENOPKG;
455
456 is_gpt = streq_ptr(pttype, "gpt");
457 is_mbr = streq_ptr(pttype, "dos");
458
9b6deb03 459 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
460 return -ENOPKG;
461
462 errno = 0;
463 pl = blkid_probe_get_partitions(b);
b382db9f 464 if (!pl)
66855de7 465 return errno_or_else(ENOMEM);
8c1be37e 466
052eaf5c 467 r = loop_wait_for_partitions_to_appear(fd, d, blkid_partlist_numof_partitions(pl), flags, &e);
ea887be0
ZJS
468 if (r < 0)
469 return r;
8c1be37e 470
8437c059 471 FOREACH_DEVICE(e, q) {
9b6deb03 472 unsigned long long pflags;
8c1be37e 473 blkid_partition pp;
cde942f6 474 const char *node;
8c1be37e
LP
475 dev_t qn;
476 int nr;
477
3c1f2cee
YW
478 r = sd_device_get_devnum(q, &qn);
479 if (r < 0)
8c1be37e
LP
480 continue;
481
482 if (st.st_rdev == qn)
483 continue;
484
aae22eb3
LP
485 if (!device_is_block(q))
486 continue;
487
cde942f6 488 if (device_is_mmc_special_partition(q))
7be1420f
LP
489 continue;
490
3c1f2cee
YW
491 r = sd_device_get_devname(q, &node);
492 if (r < 0)
8c1be37e
LP
493 continue;
494
495 pp = blkid_partlist_devno_to_partition(pl, qn);
496 if (!pp)
497 continue;
498
9b6deb03 499 pflags = blkid_partition_get_flags(pp);
8c1be37e
LP
500
501 nr = blkid_partition_get_partno(pp);
502 if (nr < 0)
503 continue;
504
505 if (is_gpt) {
569a0e42
LP
506 PartitionDesignator designator = _PARTITION_DESIGNATOR_INVALID;
507 int architecture = _ARCHITECTURE_INVALID;
4623e8e6
LP
508 const char *stype, *sid, *fstype = NULL;
509 sd_id128_t type_id, id;
8c1be37e
LP
510 bool rw = true;
511
4623e8e6
LP
512 sid = blkid_partition_get_uuid(pp);
513 if (!sid)
514 continue;
515 if (sd_id128_from_string(sid, &id) < 0)
516 continue;
517
8c1be37e
LP
518 stype = blkid_partition_get_type_string(pp);
519 if (!stype)
520 continue;
8c1be37e
LP
521 if (sd_id128_from_string(stype, &type_id) < 0)
522 continue;
523
524 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347 525
0f7c9a3d
LP
526 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
527
a48dd347
LP
528 if (pflags & GPT_FLAG_NO_AUTO)
529 continue;
530
8c1be37e 531 designator = PARTITION_HOME;
9b6deb03 532 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 533 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347 534
0f7c9a3d
LP
535 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
536
a48dd347
LP
537 if (pflags & GPT_FLAG_NO_AUTO)
538 continue;
539
8c1be37e 540 designator = PARTITION_SRV;
9b6deb03 541 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 542 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347
LP
543
544 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
545 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
546 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
547
548 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
549 continue;
550
8c1be37e
LP
551 designator = PARTITION_ESP;
552 fstype = "vfat";
a8c47660
LP
553
554 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
555
0f7c9a3d
LP
556 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
557
a8c47660
LP
558 if (pflags & GPT_FLAG_NO_AUTO)
559 continue;
560
561 designator = PARTITION_XBOOTLDR;
562 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
563 }
564#ifdef GPT_ROOT_NATIVE
565 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 566
0f7c9a3d
LP
567 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
568
a48dd347
LP
569 if (pflags & GPT_FLAG_NO_AUTO)
570 continue;
571
4623e8e6
LP
572 /* If a root ID is specified, ignore everything but the root id */
573 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
574 continue;
575
8c1be37e
LP
576 designator = PARTITION_ROOT;
577 architecture = native_architecture();
9b6deb03 578 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 579 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 580
0f7c9a3d
LP
581 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
582
a48dd347
LP
583 if (pflags & GPT_FLAG_NO_AUTO)
584 continue;
585
4623e8e6
LP
586 m->can_verity = true;
587
588 /* Ignore verity unless a root hash is specified */
589 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
590 continue;
591
592 designator = PARTITION_ROOT_VERITY;
593 fstype = "DM_verity_hash";
594 architecture = native_architecture();
595 rw = false;
596 }
597#endif
8c1be37e
LP
598#ifdef GPT_ROOT_SECONDARY
599 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 600
0f7c9a3d
LP
601 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
602
a48dd347
LP
603 if (pflags & GPT_FLAG_NO_AUTO)
604 continue;
605
4623e8e6
LP
606 /* If a root ID is specified, ignore everything but the root id */
607 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
608 continue;
609
8c1be37e
LP
610 designator = PARTITION_ROOT_SECONDARY;
611 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 612 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 613 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347 614
0f7c9a3d
LP
615 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
616
a48dd347
LP
617 if (pflags & GPT_FLAG_NO_AUTO)
618 continue;
619
4623e8e6
LP
620 m->can_verity = true;
621
622 /* Ignore verity unless root has is specified */
623 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
624 continue;
625
626 designator = PARTITION_ROOT_SECONDARY_VERITY;
627 fstype = "DM_verity_hash";
628 architecture = SECONDARY_ARCHITECTURE;
629 rw = false;
630 }
8c1be37e
LP
631#endif
632 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347 633
0f7c9a3d
LP
634 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
635
a48dd347
LP
636 if (pflags & GPT_FLAG_NO_AUTO)
637 continue;
638
8c1be37e
LP
639 designator = PARTITION_SWAP;
640 fstype = "swap";
641 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
642
0f7c9a3d
LP
643 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
644
a48dd347
LP
645 if (pflags & GPT_FLAG_NO_AUTO)
646 continue;
647
8c1be37e
LP
648 if (generic_node)
649 multiple_generic = true;
650 else {
651 generic_nr = nr;
9b6deb03 652 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
be30ad41 653 generic_uuid = id;
8c1be37e
LP
654 generic_node = strdup(node);
655 if (!generic_node)
656 return -ENOMEM;
657 }
d4dffb85
LP
658
659 } else if (sd_id128_equal(type_id, GPT_TMP)) {
660
0f7c9a3d
LP
661 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
662
d4dffb85
LP
663 if (pflags & GPT_FLAG_NO_AUTO)
664 continue;
665
666 designator = PARTITION_TMP;
667 rw = !(pflags & GPT_FLAG_READ_ONLY);
668
669 } else if (sd_id128_equal(type_id, GPT_VAR)) {
670
0f7c9a3d
LP
671 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
672
d4dffb85
LP
673 if (pflags & GPT_FLAG_NO_AUTO)
674 continue;
675
676 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
677 sd_id128_t var_uuid;
678
679 /* For /var we insist that the uuid of the partition matches the
680 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
681 * ID. Why? Unlike the other partitions /var is inherently
682 * installation specific, hence we need to be careful not to mount it
683 * in the wrong installation. By hashing the partition UUID from
684 * /etc/machine-id we can securely bind the partition to the
685 * installation. */
686
687 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
688 if (r < 0)
689 return r;
690
691 if (!sd_id128_equal(var_uuid, id)) {
692 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
693 continue;
694 }
695 }
696
697 designator = PARTITION_VAR;
698 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
699 }
700
701 if (designator != _PARTITION_DESIGNATOR_INVALID) {
18d73705
LB
702 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
703 const char *options = NULL;
8c1be37e
LP
704
705 /* First one wins */
706 if (m->partitions[designator].found)
707 continue;
708
709 if (fstype) {
710 t = strdup(fstype);
711 if (!t)
712 return -ENOMEM;
713 }
714
715 n = strdup(node);
716 if (!n)
717 return -ENOMEM;
718
f5215bc8 719 options = mount_options_from_designator(mount_options, designator);
18d73705
LB
720 if (options) {
721 o = strdup(options);
722 if (!o)
723 return -ENOMEM;
724 }
725
8c1be37e
LP
726 m->partitions[designator] = (DissectedPartition) {
727 .found = true,
728 .partno = nr,
729 .rw = rw,
730 .architecture = architecture,
1cc6c93a
YW
731 .node = TAKE_PTR(n),
732 .fstype = TAKE_PTR(t),
be30ad41 733 .uuid = id,
18d73705 734 .mount_options = TAKE_PTR(o),
8c1be37e 735 };
8c1be37e
LP
736 }
737
738 } else if (is_mbr) {
739
a8c47660 740 switch (blkid_partition_get_type(pp)) {
8c1be37e 741
a8c47660
LP
742 case 0x83: /* Linux partition */
743
744 if (pflags != 0x80) /* Bootable flag */
745 continue;
8c1be37e 746
a8c47660
LP
747 if (generic_node)
748 multiple_generic = true;
749 else {
750 generic_nr = nr;
751 generic_rw = true;
752 generic_node = strdup(node);
753 if (!generic_node)
754 return -ENOMEM;
755 }
756
757 break;
758
759 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
18d73705 760 _cleanup_free_ char *n = NULL, *o = NULL;
a8c47660 761 sd_id128_t id = SD_ID128_NULL;
18d73705 762 const char *sid, *options = NULL;
a8c47660
LP
763
764 /* First one wins */
765 if (m->partitions[PARTITION_XBOOTLDR].found)
766 continue;
767
768 sid = blkid_partition_get_uuid(pp);
769 if (sid)
770 (void) sd_id128_from_string(sid, &id);
771
772 n = strdup(node);
773 if (!n)
8c1be37e 774 return -ENOMEM;
a8c47660 775
f5215bc8 776 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
18d73705
LB
777 if (options) {
778 o = strdup(options);
779 if (!o)
780 return -ENOMEM;
781 }
782
a8c47660
LP
783 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
784 .found = true,
785 .partno = nr,
786 .rw = true,
787 .architecture = _ARCHITECTURE_INVALID,
788 .node = TAKE_PTR(n),
789 .uuid = id,
18d73705 790 .mount_options = TAKE_PTR(o),
a8c47660
LP
791 };
792
793 break;
794 }}
8c1be37e
LP
795 }
796 }
797
798 if (!m->partitions[PARTITION_ROOT].found) {
799 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
800 * either, then check if there's a single generic one, and use that. */
801
4623e8e6 802 if (m->partitions[PARTITION_ROOT_VERITY].found)
e0f9e7bd 803 return -EADDRNOTAVAIL;
4623e8e6 804
8c1be37e
LP
805 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
806 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
807 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
4623e8e6
LP
808
809 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
810 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
811
e0f9e7bd 812 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
18d73705
LB
813 _cleanup_free_ char *o = NULL;
814 const char *options = NULL;
e0f9e7bd 815
2aed63f4
ZJS
816 /* If the root hash was set, then we won't fall back to a generic node, because the
817 * root hash decides. */
e0f9e7bd
LP
818 if (root_hash)
819 return -EADDRNOTAVAIL;
8c1be37e 820
e0f9e7bd
LP
821 /* If we didn't find a generic node, then we can't fix this up either */
822 if (!generic_node)
823 return -ENXIO;
824
825 /* If we didn't find a properly marked root partition, but we did find a single suitable
826 * generic Linux partition, then use this as root partition, if the caller asked for it. */
8c1be37e
LP
827 if (multiple_generic)
828 return -ENOTUNIQ;
829
f5215bc8 830 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
831 if (options) {
832 o = strdup(options);
833 if (!o)
834 return -ENOMEM;
835 }
836
8c1be37e
LP
837 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
838 .found = true,
839 .rw = generic_rw,
840 .partno = generic_nr,
841 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 842 .node = TAKE_PTR(generic_node),
be30ad41 843 .uuid = generic_uuid,
18d73705 844 .mount_options = TAKE_PTR(o),
8c1be37e 845 };
e0f9e7bd 846 }
8c1be37e
LP
847 }
848
4623e8e6 849 if (root_hash) {
e0f9e7bd 850 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
4623e8e6
LP
851 return -EADDRNOTAVAIL;
852
853 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
854 * (which would be weird, after all the root hash should only be assigned to one pair of
855 * partitions... */
856 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
857 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
858
859 /* If we found a verity setup, then the root partition is necessarily read-only. */
860 m->partitions[PARTITION_ROOT].rw = false;
861
862 m->verity = true;
863 }
864
18b5886e
LP
865 blkid_free_probe(b);
866 b = NULL;
867
8c1be37e 868 /* Fill in file system types if we don't know them yet. */
569a0e42 869 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 870 DissectedPartition *p = m->partitions + i;
8c1be37e 871
18b5886e 872 if (!p->found)
8c1be37e
LP
873 continue;
874
18b5886e
LP
875 if (!p->fstype && p->node) {
876 r = probe_filesystem(p->node, &p->fstype);
7cc84b2c 877 if (r < 0 && r != -EUCLEAN)
18b5886e 878 return r;
8c1be37e
LP
879 }
880
18b5886e
LP
881 if (streq_ptr(p->fstype, "crypto_LUKS"))
882 m->encrypted = true;
896f937f
LP
883
884 if (p->fstype && fstype_is_ro(p->fstype))
885 p->rw = false;
8c1be37e
LP
886 }
887
1cc6c93a 888 *ret = TAKE_PTR(m);
8c1be37e
LP
889
890 return 0;
891#else
892 return -EOPNOTSUPP;
893#endif
894}
895
896DissectedImage* dissected_image_unref(DissectedImage *m) {
8c1be37e
LP
897 if (!m)
898 return NULL;
899
569a0e42 900 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
8c1be37e
LP
901 free(m->partitions[i].fstype);
902 free(m->partitions[i].node);
18b5886e
LP
903 free(m->partitions[i].decrypted_fstype);
904 free(m->partitions[i].decrypted_node);
18d73705 905 free(m->partitions[i].mount_options);
8c1be37e
LP
906 }
907
3b925504
LP
908 free(m->hostname);
909 strv_free(m->machine_info);
910 strv_free(m->os_release);
911
5fecf46d 912 return mfree(m);
8c1be37e
LP
913}
914
18b5886e 915static int is_loop_device(const char *path) {
553e15f2 916 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
917 struct stat st;
918
919 assert(path);
920
921 if (stat(path, &st) < 0)
922 return -errno;
923
924 if (!S_ISBLK(st.st_mode))
925 return -ENOTBLK;
926
553e15f2 927 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
928 if (access(s, F_OK) < 0) {
929 if (errno != ENOENT)
930 return -errno;
931
932 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 933 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
934 if (access(s, F_OK) < 0)
935 return errno == ENOENT ? false : -errno;
936 }
937
938 return true;
939}
940
cf32c486
LP
941static int run_fsck(const char *node, const char *fstype) {
942 int r, exit_status;
943 pid_t pid;
944
945 assert(node);
946 assert(fstype);
947
948 r = fsck_exists(fstype);
949 if (r < 0) {
950 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
951 return 0;
952 }
953 if (r == 0) {
954 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
955 return 0;
956 }
957
958 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
959 if (r < 0)
960 return log_debug_errno(r, "Failed to fork off fsck: %m");
961 if (r == 0) {
962 /* Child */
963 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
964 log_debug_errno(errno, "Failed to execl() fsck: %m");
965 _exit(FSCK_OPERATIONAL_ERROR);
966 }
967
968 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
969 if (exit_status < 0)
970 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
971
972 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
973 log_debug("fsck failed with exit status %i.", exit_status);
974
975 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
976 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
977
978 log_debug("Ignoring fsck error.");
979 }
980
981 return 0;
982}
983
18b5886e
LP
984static int mount_partition(
985 DissectedPartition *m,
986 const char *where,
987 const char *directory,
2d3a5a73 988 uid_t uid_shift,
18b5886e
LP
989 DissectImageFlags flags) {
990
2d3a5a73
LP
991 _cleanup_free_ char *chased = NULL, *options = NULL;
992 const char *p, *node, *fstype;
8c1be37e 993 bool rw;
2eedfd2d 994 int r;
8c1be37e
LP
995
996 assert(m);
997 assert(where);
998
4dc28665 999 /* Use decrypted node and matching fstype if available, otherwise use the original device */
18b5886e 1000 node = m->decrypted_node ?: m->node;
4dc28665 1001 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
18b5886e 1002
4dc28665 1003 if (!m->found || !node)
8c1be37e 1004 return 0;
4dc28665
LP
1005 if (!fstype)
1006 return -EAFNOSUPPORT;
8c1be37e 1007
fa45d12c 1008 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this case. */
4dc28665 1009 if (streq(fstype, "crypto_LUKS"))
fa45d12c 1010 return -EUNATCH;
18b5886e
LP
1011
1012 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
8c1be37e 1013
cf32c486
LP
1014 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1015 r = run_fsck(node, fstype);
1016 if (r < 0)
1017 return r;
1018 }
1019
2eedfd2d 1020 if (directory) {
1f0f82f1
LP
1021 if (!FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY)) {
1022 /* Automatically create missing mount points, if necessary. */
1023 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1024 if (r < 0)
1025 return r;
1026 }
1027
a5648b80 1028 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2eedfd2d
LP
1029 if (r < 0)
1030 return r;
1031
1032 p = chased;
1033 } else
8c1be37e
LP
1034 p = where;
1035
18b5886e 1036 /* If requested, turn on discard support. */
154d2269 1037 if (fstype_can_discard(fstype) &&
18b5886e 1038 ((flags & DISSECT_IMAGE_DISCARD) ||
2d3a5a73
LP
1039 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node)))) {
1040 options = strdup("discard");
1041 if (!options)
1042 return -ENOMEM;
1043 }
1044
1045 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
1046 _cleanup_free_ char *uid_option = NULL;
1047
1048 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1049 return -ENOMEM;
1050
1051 if (!strextend_with_separator(&options, ",", uid_option, NULL))
1052 return -ENOMEM;
1053 }
8c1be37e 1054
18d73705
LB
1055 if (!isempty(m->mount_options))
1056 if (!strextend_with_separator(&options, ",", m->mount_options, NULL))
1057 return -ENOMEM;
1058
5c05f062
LP
1059 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1060 r = mkdir_p(p, 0755);
1061 if (r < 0)
1062 return r;
1063 }
1064
d9223c07
LP
1065 r = mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
1066 if (r < 0)
1067 return r;
1068
1069 return 1;
8c1be37e
LP
1070}
1071
2d3a5a73 1072int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1f0f82f1 1073 int r, xbootldr_mounted;
8c1be37e
LP
1074
1075 assert(m);
1076 assert(where);
1077
fa45d12c
LP
1078 /* Returns:
1079 *
1080 * -ENXIO → No root partition found
1081 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release file found
1082 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1083 * -EUCLEAN → fsck for file system failed
1084 * -EBUSY → File system already mounted/used elsewhere (kernel)
4dc28665 1085 * -EAFNOSUPPORT → File system type not supported or not known
fa45d12c
LP
1086 */
1087
8c1be37e
LP
1088 if (!m->partitions[PARTITION_ROOT].found)
1089 return -ENXIO;
1090
2d3a5a73
LP
1091 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1092 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
1093 if (r < 0)
1094 return r;
03bcb6d4
LP
1095
1096 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
1097 r = path_is_os_tree(where);
1098 if (r < 0)
1099 return r;
1100 if (r == 0)
1101 return -EMEDIUMTYPE;
1102 }
2d3a5a73
LP
1103 }
1104
705727fd 1105 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 1106 return 0;
8c1be37e 1107
5c05f062
LP
1108 /* Mask DISSECT_IMAGE_MKDIR for all subdirs: the idea is that only the top-level mount point is
1109 * created if needed, but the image itself not modified. */
1110 flags &= ~DISSECT_IMAGE_MKDIR;
1111
2d3a5a73 1112 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
8c1be37e
LP
1113 if (r < 0)
1114 return r;
1115
2d3a5a73 1116 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
8c1be37e
LP
1117 if (r < 0)
1118 return r;
1119
d4dffb85
LP
1120 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, flags);
1121 if (r < 0)
1122 return r;
1123
1124 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, flags);
1125 if (r < 0)
1126 return r;
1127
1f0f82f1
LP
1128 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, flags);
1129 if (xbootldr_mounted < 0)
1130 return xbootldr_mounted;
d9223c07 1131
8c1be37e 1132 if (m->partitions[PARTITION_ESP].found) {
1f0f82f1
LP
1133 int esp_done = false;
1134
d9223c07
LP
1135 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1136 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
8c1be37e 1137
a5648b80 1138 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1f0f82f1
LP
1139 if (r < 0) {
1140 if (r != -ENOENT)
d9223c07 1141 return r;
8c1be37e 1142
1f0f82f1
LP
1143 /* /efi doesn't exist. Let's see if /boot is suitable then */
1144
1145 if (!xbootldr_mounted) {
1146 _cleanup_free_ char *p = NULL;
2eedfd2d 1147
1f0f82f1
LP
1148 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1149 if (r < 0) {
1150 if (r != -ENOENT)
1151 return r;
1152 } else if (dir_is_empty(p) > 0) {
1153 /* It exists and is an empty directory. Let's mount the ESP there. */
1154 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, flags);
1155 if (r < 0)
1156 return r;
1157
1158 esp_done = true;
1159 }
2eedfd2d 1160 }
8c1be37e 1161 }
1f0f82f1
LP
1162
1163 if (!esp_done) {
1164 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1165
1166 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, flags);
1167 if (r < 0)
1168 return r;
1169 }
8c1be37e
LP
1170 }
1171
1172 return 0;
1173}
1174
af187ab2
LP
1175int dissected_image_mount_and_warn(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1176 int r;
1177
1178 assert(m);
1179 assert(where);
1180
1181 r = dissected_image_mount(m, where, uid_shift, flags);
1182 if (r == -ENXIO)
1183 return log_error_errno(r, "Not root file system found in image.");
1184 if (r == -EMEDIUMTYPE)
1185 return log_error_errno(r, "No suitable os-release file in image found.");
1186 if (r == -EUNATCH)
1187 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1188 if (r == -EUCLEAN)
1189 return log_error_errno(r, "File system check on image failed.");
1190 if (r == -EBUSY)
1191 return log_error_errno(r, "File system already mounted elsewhere.");
4dc28665
LP
1192 if (r == -EAFNOSUPPORT)
1193 return log_error_errno(r, "File system type not supported or not known.");
af187ab2
LP
1194 if (r < 0)
1195 return log_error_errno(r, "Failed to mount image: %m");
1196
1197 return r;
1198}
1199
349cc4a5 1200#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1201typedef struct DecryptedPartition {
1202 struct crypt_device *device;
1203 char *name;
1204 bool relinquished;
1205} DecryptedPartition;
1206
1207struct DecryptedImage {
1208 DecryptedPartition *decrypted;
1209 size_t n_decrypted;
1210 size_t n_allocated;
1211};
1212#endif
1213
1214DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
349cc4a5 1215#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1216 size_t i;
1217 int r;
1218
1219 if (!d)
1220 return NULL;
1221
1222 for (i = 0; i < d->n_decrypted; i++) {
1223 DecryptedPartition *p = d->decrypted + i;
1224
1225 if (p->device && p->name && !p->relinquished) {
0d12936d 1226 r = sym_crypt_deactivate_by_name(p->device, p->name, 0);
18b5886e
LP
1227 if (r < 0)
1228 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1229 }
1230
1231 if (p->device)
0d12936d 1232 sym_crypt_free(p->device);
18b5886e
LP
1233 free(p->name);
1234 }
1235
1236 free(d);
1237#endif
1238 return NULL;
1239}
1240
349cc4a5 1241#if HAVE_LIBCRYPTSETUP
4623e8e6
LP
1242
1243static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1244 _cleanup_free_ char *name = NULL, *node = NULL;
1245 const char *base;
1246
1247 assert(original_node);
1248 assert(suffix);
1249 assert(ret_name);
1250 assert(ret_node);
1251
1252 base = strrchr(original_node, '/');
1253 if (!base)
ac1f3ad0
LB
1254 base = original_node;
1255 else
1256 base++;
4623e8e6
LP
1257 if (isempty(base))
1258 return -EINVAL;
1259
1260 name = strjoin(base, suffix);
1261 if (!name)
1262 return -ENOMEM;
1263 if (!filename_is_valid(name))
1264 return -EINVAL;
1265
0d12936d 1266 node = path_join(sym_crypt_get_dir(), name);
4623e8e6
LP
1267 if (!node)
1268 return -ENOMEM;
1269
1cc6c93a
YW
1270 *ret_name = TAKE_PTR(name);
1271 *ret_node = TAKE_PTR(node);
4623e8e6 1272
4623e8e6
LP
1273 return 0;
1274}
1275
18b5886e
LP
1276static int decrypt_partition(
1277 DissectedPartition *m,
1278 const char *passphrase,
1279 DissectImageFlags flags,
1280 DecryptedImage *d) {
1281
1282 _cleanup_free_ char *node = NULL, *name = NULL;
0d12936d 1283 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
18b5886e
LP
1284 int r;
1285
1286 assert(m);
1287 assert(d);
1288
1289 if (!m->found || !m->node || !m->fstype)
1290 return 0;
1291
1292 if (!streq(m->fstype, "crypto_LUKS"))
1293 return 0;
1294
bdd73ac5
ZJS
1295 if (!passphrase)
1296 return -ENOKEY;
1297
0d12936d
LP
1298 r = dlopen_cryptsetup();
1299 if (r < 0)
1300 return r;
1301
4623e8e6
LP
1302 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1303 if (r < 0)
1304 return r;
18b5886e
LP
1305
1306 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1307 return -ENOMEM;
1308
0d12936d 1309 r = sym_crypt_init(&cd, m->node);
18b5886e 1310 if (r < 0)
715cbb81 1311 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 1312
efc3b12f 1313 cryptsetup_enable_logging(cd);
1887032f 1314
0d12936d 1315 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
1316 if (r < 0)
1317 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e 1318
0d12936d
LP
1319 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1320 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1321 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 1322 if (r < 0) {
715cbb81 1323 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 1324 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 1325 }
18b5886e 1326
1cc6c93a
YW
1327 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1328 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
18b5886e
LP
1329 d->n_decrypted++;
1330
1cc6c93a 1331 m->decrypted_node = TAKE_PTR(node);
18b5886e
LP
1332
1333 return 0;
4623e8e6
LP
1334}
1335
ac1f3ad0
LB
1336static int verity_can_reuse(const void *root_hash, size_t root_hash_size, bool has_sig, const char *name, struct crypt_device **ret_cd) {
1337 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1338 _cleanup_free_ char *root_hash_existing = NULL;
0d12936d 1339 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0
LB
1340 struct crypt_params_verity crypt_params = {};
1341 size_t root_hash_existing_size = root_hash_size;
1342 int r;
1343
1344 assert(ret_cd);
1345
0d12936d 1346 r = sym_crypt_init_by_name(&cd, name);
ac1f3ad0
LB
1347 if (r < 0)
1348 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
0d12936d
LP
1349
1350 r = sym_crypt_get_verity_info(cd, &crypt_params);
ac1f3ad0
LB
1351 if (r < 0)
1352 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
0d12936d 1353
ac1f3ad0
LB
1354 root_hash_existing = malloc0(root_hash_size);
1355 if (!root_hash_existing)
1356 return -ENOMEM;
0d12936d
LP
1357
1358 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
ac1f3ad0
LB
1359 if (r < 0)
1360 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
1361 if (root_hash_size != root_hash_existing_size || memcmp(root_hash_existing, root_hash, root_hash_size) != 0)
1362 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
1363#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1364 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount
1365 * used the same settings, so that a previous unsigned mount will not be reused if the user
1366 * asks to use signing for the new one, and viceversa. */
1367 if (has_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
1368 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1369#endif
1370
1371 *ret_cd = TAKE_PTR(cd);
1372 return 0;
1373}
1374
1375static inline void dm_deferred_remove_clean(char *name) {
1376 if (!name)
1377 return;
0d12936d
LP
1378
1379 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
ac1f3ad0
LB
1380 free(name);
1381}
1382DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1383
4623e8e6
LP
1384static int verity_partition(
1385 DissectedPartition *m,
1386 DissectedPartition *v,
1387 const void *root_hash,
1388 size_t root_hash_size,
e7cbe5cb 1389 const char *verity_data,
c2923fdc
LB
1390 const char *root_hash_sig_path,
1391 const void *root_hash_sig,
1392 size_t root_hash_sig_size,
4623e8e6
LP
1393 DissectImageFlags flags,
1394 DecryptedImage *d) {
1395
ac1f3ad0 1396 _cleanup_free_ char *node = NULL, *name = NULL, *hash_sig_from_file = NULL;
0d12936d 1397 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1398 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
4623e8e6
LP
1399 int r;
1400
1401 assert(m);
e7cbe5cb 1402 assert(v || verity_data);
4623e8e6
LP
1403
1404 if (!root_hash)
1405 return 0;
1406
1407 if (!m->found || !m->node || !m->fstype)
1408 return 0;
e7cbe5cb
LB
1409 if (!verity_data) {
1410 if (!v->found || !v->node || !v->fstype)
1411 return 0;
4623e8e6 1412
e7cbe5cb
LB
1413 if (!streq(v->fstype, "DM_verity_hash"))
1414 return 0;
1415 }
4623e8e6 1416
0d12936d
LP
1417 r = dlopen_cryptsetup();
1418 if (r < 0)
1419 return r;
1420
ac1f3ad0
LB
1421 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
1422 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1423 _cleanup_free_ char *root_hash_encoded = NULL;
0d12936d 1424
ac1f3ad0
LB
1425 root_hash_encoded = hexmem(root_hash, root_hash_size);
1426 if (!root_hash_encoded)
0d12936d 1427
ac1f3ad0
LB
1428 return -ENOMEM;
1429 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
1430 } else
1431 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
4623e8e6
LP
1432 if (r < 0)
1433 return r;
1434
ac1f3ad0
LB
1435 if (!root_hash_sig && root_hash_sig_path) {
1436 r = read_full_file_full(AT_FDCWD, root_hash_sig_path, 0, &hash_sig_from_file, &root_hash_sig_size);
1437 if (r < 0)
1438 return r;
1439 }
4623e8e6 1440
0d12936d 1441 r = sym_crypt_init(&cd, verity_data ?: v->node);
4623e8e6
LP
1442 if (r < 0)
1443 return r;
1444
efc3b12f 1445 cryptsetup_enable_logging(cd);
1887032f 1446
0d12936d 1447 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
4623e8e6 1448 if (r < 0)
294bd454 1449 return r;
4623e8e6 1450
0d12936d 1451 r = sym_crypt_set_data_device(cd, m->node);
4623e8e6 1452 if (r < 0)
294bd454 1453 return r;
4623e8e6 1454
ac1f3ad0
LB
1455 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1456 return -ENOMEM;
1457
1458 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1459 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1460 * retry a few times before giving up. */
1461 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
1462 if (root_hash_sig || hash_sig_from_file) {
c2923fdc 1463#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
0d12936d 1464 r = sym_crypt_activate_by_signed_key(cd, name, root_hash, root_hash_size, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, CRYPT_ACTIVATE_READONLY);
ac1f3ad0
LB
1465#else
1466 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "activation of verity device with signature requested, but not supported by cryptsetup due to missing crypt_activate_by_signed_key()");
1467#endif
1468 } else
0d12936d 1469 r = sym_crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
ac1f3ad0
LB
1470 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1471 * There's no way to distinguish this situation from a genuine error due to invalid
2aed63f4 1472 * parameters, so immediately fall back to activating the device with a unique name.
ac1f3ad0
LB
1473 * Improvements in libcrypsetup can ensure this never happens: https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1474 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1475 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10
LB
1476 if (!IN_SET(r,
1477 0, /* Success */
1478 -EEXIST, /* Volume is already open and ready to be used */
1479 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
1480 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
ac1f3ad0 1481 return r;
9ecb5c10 1482 if (IN_SET(r, -EEXIST, -EBUSY)) {
ac1f3ad0 1483 struct crypt_device *existing_cd = NULL;
c2923fdc 1484
ac1f3ad0
LB
1485 if (!restore_deferred_remove){
1486 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1487 r = dm_deferred_remove_cancel(name);
9ecb5c10
LB
1488 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
1489 if (r < 0 && r != -ENXIO)
ac1f3ad0 1490 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
9ecb5c10
LB
1491 if (r == 0) {
1492 restore_deferred_remove = strdup(name);
1493 if (!restore_deferred_remove)
1494 return -ENOMEM;
1495 }
ac1f3ad0 1496 }
c2923fdc 1497
ac1f3ad0
LB
1498 r = verity_can_reuse(root_hash, root_hash_size, !!root_hash_sig || !!hash_sig_from_file, name, &existing_cd);
1499 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1500 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1501 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10 1502 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
ac1f3ad0
LB
1503 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
1504 if (r == 0) {
c419b6f0
LB
1505 /* devmapper might say that the device exists, but the devlink might not yet have been
1506 * created. Check and wait for the udev event in that case. */
1507 r = device_wait_for_devlink(node, "block", 100 * USEC_PER_MSEC, NULL);
1508 /* Fallback to activation with a unique device if it's taking too long */
1509 if (r == -ETIMEDOUT)
1510 break;
1511 if (r < 0)
1512 return r;
1513
ac1f3ad0 1514 if (cd)
0d12936d 1515 sym_crypt_free(cd);
ac1f3ad0
LB
1516 cd = existing_cd;
1517 }
c2923fdc 1518 }
ac1f3ad0
LB
1519 if (r == 0)
1520 break;
ecab4c47
LB
1521
1522 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
1523 (void) usleep(2 * USEC_PER_MSEC);
ac1f3ad0
LB
1524 }
1525
ac1f3ad0
LB
1526 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1527 * Fall back to activating it with a unique device name. */
1528 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1529 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1530
1531 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1532 restore_deferred_remove = mfree(restore_deferred_remove);
4623e8e6 1533
1cc6c93a
YW
1534 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1535 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
4623e8e6
LP
1536 d->n_decrypted++;
1537
1cc6c93a 1538 m->decrypted_node = TAKE_PTR(node);
4623e8e6
LP
1539
1540 return 0;
18b5886e
LP
1541}
1542#endif
1543
1544int dissected_image_decrypt(
1545 DissectedImage *m,
1546 const char *passphrase,
4623e8e6
LP
1547 const void *root_hash,
1548 size_t root_hash_size,
e7cbe5cb 1549 const char *verity_data,
c2923fdc
LB
1550 const char *root_hash_sig_path,
1551 const void *root_hash_sig,
1552 size_t root_hash_sig_size,
18b5886e
LP
1553 DissectImageFlags flags,
1554 DecryptedImage **ret) {
1555
349cc4a5 1556#if HAVE_LIBCRYPTSETUP
49b5b3b4 1557 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
1558 int r;
1559#endif
1560
1561 assert(m);
4623e8e6 1562 assert(root_hash || root_hash_size == 0);
18b5886e
LP
1563
1564 /* Returns:
1565 *
1566 * = 0 → There was nothing to decrypt
1567 * > 0 → Decrypted successfully
d1c536f5 1568 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
1569 * -EKEYREJECTED → Passed key was not correct
1570 */
1571
4623e8e6
LP
1572 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1573 return -EINVAL;
1574
1575 if (!m->encrypted && !m->verity) {
18b5886e
LP
1576 *ret = NULL;
1577 return 0;
1578 }
1579
349cc4a5 1580#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1581 d = new0(DecryptedImage, 1);
1582 if (!d)
1583 return -ENOMEM;
1584
569a0e42 1585 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 1586 DissectedPartition *p = m->partitions + i;
4623e8e6 1587 int k;
18b5886e
LP
1588
1589 if (!p->found)
1590 continue;
1591
1592 r = decrypt_partition(p, passphrase, flags, d);
1593 if (r < 0)
1594 return r;
1595
4623e8e6
LP
1596 k = PARTITION_VERITY_OF(i);
1597 if (k >= 0) {
ac1f3ad0 1598 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, verity_data, root_hash_sig_path, root_hash_sig, root_hash_sig_size, flags | DISSECT_IMAGE_VERITY_SHARE, d);
4623e8e6
LP
1599 if (r < 0)
1600 return r;
1601 }
1602
18b5886e
LP
1603 if (!p->decrypted_fstype && p->decrypted_node) {
1604 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 1605 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
1606 return r;
1607 }
1608 }
1609
1cc6c93a 1610 *ret = TAKE_PTR(d);
18b5886e
LP
1611
1612 return 1;
1613#else
1614 return -EOPNOTSUPP;
1615#endif
1616}
1617
1618int dissected_image_decrypt_interactively(
1619 DissectedImage *m,
1620 const char *passphrase,
4623e8e6
LP
1621 const void *root_hash,
1622 size_t root_hash_size,
e7cbe5cb 1623 const char *verity_data,
c2923fdc
LB
1624 const char *root_hash_sig_path,
1625 const void *root_hash_sig,
1626 size_t root_hash_sig_size,
18b5886e
LP
1627 DissectImageFlags flags,
1628 DecryptedImage **ret) {
1629
1630 _cleanup_strv_free_erase_ char **z = NULL;
1631 int n = 3, r;
1632
1633 if (passphrase)
1634 n--;
1635
1636 for (;;) {
c2923fdc 1637 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, verity_data, root_hash_sig_path, root_hash_sig, root_hash_sig_size, flags, ret);
18b5886e
LP
1638 if (r >= 0)
1639 return r;
1640 if (r == -EKEYREJECTED)
1641 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
1642 else if (r != -ENOKEY)
1643 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 1644
baaa35ad
ZJS
1645 if (--n < 0)
1646 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1647 "Too many retries.");
18b5886e
LP
1648
1649 z = strv_free(z);
1650
a1c111c2 1651 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
18b5886e
LP
1652 if (r < 0)
1653 return log_error_errno(r, "Failed to query for passphrase: %m");
1654
1655 passphrase = z[0];
1656 }
1657}
1658
18b5886e
LP
1659int decrypted_image_relinquish(DecryptedImage *d) {
1660
349cc4a5 1661#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1662 size_t i;
1663 int r;
1664#endif
1665
1666 assert(d);
1667
1668 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1669 * that we don't clean it up ourselves either anymore */
1670
349cc4a5 1671#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1672 for (i = 0; i < d->n_decrypted; i++) {
1673 DecryptedPartition *p = d->decrypted + i;
1674
1675 if (p->relinquished)
1676 continue;
1677
0d12936d 1678 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
1679 if (r < 0)
1680 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1681
1682 p->relinquished = true;
1683 }
1684#endif
1685
1686 return 0;
1687}
1688
f5ea63a5
LP
1689int verity_metadata_load(
1690 const char *image,
1691 const char *root_hash_path,
1692 void **ret_roothash,
1693 size_t *ret_roothash_size,
1694 char **ret_verity_data,
1695 char **ret_roothashsig) {
1696
c2923fdc 1697 _cleanup_free_ char *verity_filename = NULL, *roothashsig_filename = NULL;
e7cbe5cb
LB
1698 _cleanup_free_ void *roothash_decoded = NULL;
1699 size_t roothash_decoded_size = 0;
78ebe980
LP
1700 int r;
1701
1702 assert(image);
78ebe980
LP
1703
1704 if (is_device_path(image)) {
1705 /* If we are asked to load the root hash for a device node, exit early */
e7cbe5cb
LB
1706 if (ret_roothash)
1707 *ret_roothash = NULL;
1708 if (ret_roothash_size)
1709 *ret_roothash_size = 0;
1710 if (ret_verity_data)
1711 *ret_verity_data = NULL;
c2923fdc
LB
1712 if (ret_roothashsig)
1713 *ret_roothashsig = NULL;
78ebe980
LP
1714 return 0;
1715 }
1716
e7cbe5cb
LB
1717 if (ret_verity_data) {
1718 char *e;
78ebe980 1719
e7cbe5cb
LB
1720 verity_filename = new(char, strlen(image) + STRLEN(".verity") + 1);
1721 if (!verity_filename)
1722 return -ENOMEM;
1723 strcpy(verity_filename, image);
1724 e = endswith(verity_filename, ".raw");
41488e1f 1725 if (e)
e7cbe5cb
LB
1726 strcpy(e, ".verity");
1727 else
1728 strcat(verity_filename, ".verity");
41488e1f 1729
e7cbe5cb
LB
1730 r = access(verity_filename, F_OK);
1731 if (r < 0) {
1732 if (errno != ENOENT)
1733 return -errno;
1734 verity_filename = mfree(verity_filename);
41488e1f 1735 }
78ebe980 1736 }
78ebe980 1737
c2923fdc
LB
1738 if (ret_roothashsig) {
1739 char *e;
1740
1741 /* Follow naming convention recommended by the relevant RFC:
1742 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1743 roothashsig_filename = new(char, strlen(image) + STRLEN(".roothash.p7s") + 1);
1744 if (!roothashsig_filename)
1745 return -ENOMEM;
1746 strcpy(roothashsig_filename, image);
1747 e = endswith(roothashsig_filename, ".raw");
1748 if (e)
1749 strcpy(e, ".roothash.p7s");
1750 else
1751 strcat(roothashsig_filename, ".roothash.p7s");
1752
1753 r = access(roothashsig_filename, R_OK);
1754 if (r < 0) {
1755 if (errno != ENOENT)
1756 return -errno;
1757 roothashsig_filename = mfree(roothashsig_filename);
1758 }
1759 }
1760
e7cbe5cb
LB
1761 if (ret_roothash) {
1762 _cleanup_free_ char *text = NULL;
1763 assert(ret_roothash_size);
1764
0389f4fa
LB
1765 if (root_hash_path) {
1766 /* We have the path to a roothash to load and decode, eg: RootHash=/foo/bar.roothash */
1767 r = read_one_line_file(root_hash_path, &text);
1768 if (r < 0)
e7cbe5cb 1769 return r;
0389f4fa
LB
1770 } else {
1771 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1772 if (r < 0) {
1773 char *fn, *e, *n;
1774
1775 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1776 return r;
78ebe980 1777
0389f4fa
LB
1778 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
1779 n = stpcpy(fn, image);
1780 e = endswith(fn, ".raw");
1781 if (e)
1782 n = e;
e7cbe5cb 1783
0389f4fa 1784 strcpy(n, ".roothash");
e7cbe5cb 1785
0389f4fa
LB
1786 r = read_one_line_file(fn, &text);
1787 if (r < 0 && r != -ENOENT)
1788 return r;
1789 }
e7cbe5cb
LB
1790 }
1791
1792 if (text) {
1793 r = unhexmem(text, strlen(text), &roothash_decoded, &roothash_decoded_size);
1794 if (r < 0)
1795 return r;
1796 if (roothash_decoded_size < sizeof(sd_id128_t))
1797 return -EINVAL;
1798 }
1799 }
1800
1801 if (ret_roothash) {
1802 *ret_roothash = TAKE_PTR(roothash_decoded);
1803 *ret_roothash_size = roothash_decoded_size;
1804 }
1805 if (ret_verity_data)
1806 *ret_verity_data = TAKE_PTR(verity_filename);
c2923fdc
LB
1807 if (roothashsig_filename)
1808 *ret_roothashsig = TAKE_PTR(roothashsig_filename);
78ebe980 1809
78ebe980
LP
1810 return 1;
1811}
1812
3b925504
LP
1813int dissected_image_acquire_metadata(DissectedImage *m) {
1814
1815 enum {
1816 META_HOSTNAME,
1817 META_MACHINE_ID,
1818 META_MACHINE_INFO,
1819 META_OS_RELEASE,
1820 _META_MAX,
1821 };
1822
1823 static const char *const paths[_META_MAX] = {
1824 [META_HOSTNAME] = "/etc/hostname\0",
1825 [META_MACHINE_ID] = "/etc/machine-id\0",
1826 [META_MACHINE_INFO] = "/etc/machine-info\0",
d4dffb85
LP
1827 [META_OS_RELEASE] = "/etc/os-release\0"
1828 "/usr/lib/os-release\0",
3b925504
LP
1829 };
1830
1831 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
af8219d5 1832 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
3b925504
LP
1833 _cleanup_(rmdir_and_freep) char *t = NULL;
1834 _cleanup_(sigkill_waitp) pid_t child = 0;
1835 sd_id128_t machine_id = SD_ID128_NULL;
1836 _cleanup_free_ char *hostname = NULL;
1837 unsigned n_meta_initialized = 0, k;
af8219d5
LP
1838 int fds[2 * _META_MAX], r, v;
1839 ssize_t n;
3b925504
LP
1840
1841 BLOCK_SIGNALS(SIGCHLD);
1842
1843 assert(m);
1844
1845 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1846 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1847 r = -errno;
1848 goto finish;
1849 }
1850
1851 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1852 if (r < 0)
1853 goto finish;
1854
af8219d5
LP
1855 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
1856 r = -errno;
1857 goto finish;
1858 }
1859
e2047ba9 1860 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 1861 if (r < 0)
3b925504 1862 goto finish;
be39f6ee 1863 if (r == 0) {
af8219d5
LP
1864 error_pipe[0] = safe_close(error_pipe[0]);
1865
03bcb6d4 1866 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
429d4e41 1867 if (r < 0) {
af8219d5
LP
1868 /* Let parent know the error */
1869 (void) write(error_pipe[1], &r, sizeof(r));
1870
429d4e41 1871 log_debug_errno(r, "Failed to mount dissected image: %m");
3b925504 1872 _exit(EXIT_FAILURE);
429d4e41 1873 }
3b925504
LP
1874
1875 for (k = 0; k < _META_MAX; k++) {
37e44c3f 1876 _cleanup_close_ int fd = -ENOENT;
3b925504
LP
1877 const char *p;
1878
1879 fds[2*k] = safe_close(fds[2*k]);
1880
1881 NULSTR_FOREACH(p, paths[k]) {
36952d19 1882 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3b925504
LP
1883 if (fd >= 0)
1884 break;
1885 }
36952d19
LP
1886 if (fd < 0) {
1887 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
37e44c3f 1888 fds[2*k+1] = safe_close(fds[2*k+1]);
3b925504 1889 continue;
36952d19 1890 }
3b925504
LP
1891
1892 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
af8219d5
LP
1893 if (r < 0) {
1894 (void) write(error_pipe[1], &r, sizeof(r));
3b925504 1895 _exit(EXIT_FAILURE);
af8219d5 1896 }
3b925504
LP
1897
1898 fds[2*k+1] = safe_close(fds[2*k+1]);
1899 }
1900
1901 _exit(EXIT_SUCCESS);
1902 }
1903
af8219d5
LP
1904 error_pipe[1] = safe_close(error_pipe[1]);
1905
3b925504
LP
1906 for (k = 0; k < _META_MAX; k++) {
1907 _cleanup_fclose_ FILE *f = NULL;
1908
1909 fds[2*k+1] = safe_close(fds[2*k+1]);
1910
4fa744a3 1911 f = take_fdopen(&fds[2*k], "r");
3b925504
LP
1912 if (!f) {
1913 r = -errno;
1914 goto finish;
1915 }
1916
3b925504
LP
1917 switch (k) {
1918
1919 case META_HOSTNAME:
1920 r = read_etc_hostname_stream(f, &hostname);
1921 if (r < 0)
1922 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1923
1924 break;
1925
1926 case META_MACHINE_ID: {
1927 _cleanup_free_ char *line = NULL;
1928
1929 r = read_line(f, LONG_LINE_MAX, &line);
1930 if (r < 0)
1931 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1932 else if (r == 33) {
1933 r = sd_id128_from_string(line, &machine_id);
1934 if (r < 0)
1935 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1936 } else if (r == 0)
1937 log_debug("/etc/machine-id file is empty.");
1938 else
1939 log_debug("/etc/machine-id has unexpected length %i.", r);
1940
1941 break;
1942 }
1943
1944 case META_MACHINE_INFO:
aa8fbc74 1945 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504
LP
1946 if (r < 0)
1947 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1948
1949 break;
1950
1951 case META_OS_RELEASE:
aa8fbc74 1952 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504
LP
1953 if (r < 0)
1954 log_debug_errno(r, "Failed to read OS release file: %m");
1955
1956 break;
1957 }
1958 }
1959
2e87a1fd 1960 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 1961 child = 0;
2e87a1fd 1962 if (r < 0)
af8219d5
LP
1963 return r;
1964
1965 n = read(error_pipe[0], &v, sizeof(v));
1966 if (n < 0)
1967 return -errno;
1968 if (n == sizeof(v))
1969 return v; /* propagate error sent to us from child */
1970 if (n != 0)
1971 return -EIO;
1972
2e87a1fd
LP
1973 if (r != EXIT_SUCCESS)
1974 return -EPROTO;
3b925504
LP
1975
1976 free_and_replace(m->hostname, hostname);
1977 m->machine_id = machine_id;
1978 strv_free_and_replace(m->machine_info, machine_info);
1979 strv_free_and_replace(m->os_release, os_release);
1980
1981finish:
1982 for (k = 0; k < n_meta_initialized; k++)
1983 safe_close_pair(fds + 2*k);
1984
1985 return r;
1986}
1987
4526113f
LP
1988int dissect_image_and_warn(
1989 int fd,
1990 const char *name,
1991 const void *root_hash,
1992 size_t root_hash_size,
e7cbe5cb 1993 const char *verity_data,
18d73705 1994 const MountOptions *mount_options,
4526113f
LP
1995 DissectImageFlags flags,
1996 DissectedImage **ret) {
1997
1998 _cleanup_free_ char *buffer = NULL;
1999 int r;
2000
2001 if (!name) {
2002 r = fd_get_path(fd, &buffer);
2003 if (r < 0)
2004 return r;
2005
2006 name = buffer;
2007 }
2008
18d73705 2009 r = dissect_image(fd, root_hash, root_hash_size, verity_data, mount_options, flags, ret);
4526113f
LP
2010
2011 switch (r) {
2012
2013 case -EOPNOTSUPP:
2014 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
2015
2016 case -ENOPKG:
2017 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
2018
2019 case -EADDRNOTAVAIL:
2020 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
2021
2022 case -ENOTUNIQ:
2023 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
2024
2025 case -ENXIO:
2026 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
2027
2028 case -EPROTONOSUPPORT:
2029 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
2030
2031 default:
2032 if (r < 0)
2033 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
2034
2035 return r;
2036 }
2037}
2038
569a0e42 2039bool dissected_image_can_do_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
e7cbe5cb
LB
2040 if (image->single_file_system)
2041 return partition_designator == PARTITION_ROOT && image->can_verity;
2042
2043 return PARTITION_VERITY_OF(partition_designator) >= 0;
2044}
2045
569a0e42 2046bool dissected_image_has_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
e7cbe5cb
LB
2047 int k;
2048
2049 if (image->single_file_system)
2050 return partition_designator == PARTITION_ROOT && image->verity;
2051
2052 k = PARTITION_VERITY_OF(partition_designator);
2053 return k >= 0 && image->partitions[k].found;
2054}
2055
18d73705
LB
2056MountOptions* mount_options_free_all(MountOptions *options) {
2057 MountOptions *m;
2058
2059 while ((m = options)) {
2060 LIST_REMOVE(mount_options, options, m);
2061 free(m->options);
2062 free(m);
2063 }
2064
2065 return NULL;
2066}
2067
569a0e42 2068const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
f5215bc8 2069 const MountOptions *m;
18d73705 2070
f5215bc8 2071 LIST_FOREACH(mount_options, m, options)
9ece6444 2072 if (designator == m->partition_designator && !isempty(m->options))
18d73705 2073 return m->options;
6aa05ebd 2074
18d73705
LB
2075 return NULL;
2076}
2077
6aa05ebd
LP
2078int mount_image_privately_interactively(
2079 const char *image,
2080 DissectImageFlags flags,
2081 char **ret_directory,
2082 LoopDevice **ret_loop_device,
2083 DecryptedImage **ret_decrypted_image) {
2084
2085 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2086 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2087 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2088 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
2089 _cleanup_free_ char *temp = NULL;
2090 int r;
2091
2092 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2093 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2094 * easily. */
2095
2096 assert(image);
2097 assert(ret_directory);
2098 assert(ret_loop_device);
2099 assert(ret_decrypted_image);
2100
2101 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
2102 if (r < 0)
2103 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
2104
2105 r = loop_device_make_by_path(
2106 image,
2107 FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY) ? O_RDONLY : O_RDWR,
2108 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2109 &d);
2110 if (r < 0)
2111 return log_error_errno(r, "Failed to set up loopback device: %m");
2112
2113 r = dissect_image_and_warn(d->fd, image, NULL, 0, NULL, NULL, flags, &dissected_image);
2114 if (r < 0)
2115 return r;
2116
2117 r = dissected_image_decrypt_interactively(dissected_image, NULL, NULL, 0, NULL, NULL, NULL, 0, flags, &decrypted_image);
2118 if (r < 0)
2119 return r;
2120
2121 r = detach_mount_namespace();
2122 if (r < 0)
2123 return log_error_errno(r, "Failed to detach mount namespace: %m");
2124
2125 r = mkdir_p(temp, 0700);
2126 if (r < 0)
2127 return log_error_errno(r, "Failed to create mount point: %m");
2128
2129 created_dir = TAKE_PTR(temp);
2130
af187ab2 2131 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, flags);
6aa05ebd 2132 if (r < 0)
af187ab2 2133 return r;
6aa05ebd
LP
2134
2135 if (decrypted_image) {
2136 r = decrypted_image_relinquish(decrypted_image);
2137 if (r < 0)
2138 return log_error_errno(r, "Failed to relinquish DM devices: %m");
2139 }
2140
2141 loop_device_relinquish(d);
2142
2143 *ret_directory = TAKE_PTR(created_dir);
2144 *ret_loop_device = TAKE_PTR(d);
2145 *ret_decrypted_image = TAKE_PTR(decrypted_image);
2146
2147 return 0;
2148}
2149
8c1be37e
LP
2150static const char *const partition_designator_table[] = {
2151 [PARTITION_ROOT] = "root",
2152 [PARTITION_ROOT_SECONDARY] = "root-secondary",
2153 [PARTITION_HOME] = "home",
2154 [PARTITION_SRV] = "srv",
2155 [PARTITION_ESP] = "esp",
a8c47660 2156 [PARTITION_XBOOTLDR] = "xbootldr",
8c1be37e 2157 [PARTITION_SWAP] = "swap",
4623e8e6
LP
2158 [PARTITION_ROOT_VERITY] = "root-verity",
2159 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
d4dffb85
LP
2160 [PARTITION_TMP] = "tmp",
2161 [PARTITION_VAR] = "var",
8c1be37e
LP
2162};
2163
569a0e42 2164DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);