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