]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
tree-wide: use UINT64_MAX or friends
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
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"
7718ac97 26#include "discover-image.h"
8c1be37e 27#include "dissect-image.h"
a709a315 28#include "dm-util.h"
686d13b9 29#include "env-file.h"
93f59701 30#include "extension-release.h"
18b5886e 31#include "fd-util.h"
78ebe980 32#include "fileio.h"
2eedfd2d 33#include "fs-util.h"
cf32c486 34#include "fsck-util.h"
8c1be37e 35#include "gpt.h"
78ebe980 36#include "hexdecoct.h"
e2054217 37#include "hostname-setup.h"
3b925504 38#include "id128-util.h"
593fe6c0 39#include "import-util.h"
6aa05ebd 40#include "mkdir.h"
8c1be37e 41#include "mount-util.h"
e4de7287 42#include "mountpoint-util.h"
6aa05ebd 43#include "namespace-util.h"
d8b4d14d 44#include "nulstr-util.h"
d58ad743 45#include "os-util.h"
8c1be37e 46#include "path-util.h"
3b925504
LP
47#include "process-util.h"
48#include "raw-clone.h"
49#include "signal-util.h"
8c1be37e 50#include "stat-util.h"
18b5886e 51#include "stdio-util.h"
8c1be37e
LP
52#include "string-table.h"
53#include "string-util.h"
2eedfd2d 54#include "strv.h"
e4de7287 55#include "tmpfile-util.h"
a8040b6d 56#include "udev-util.h"
2d3a5a73 57#include "user-util.h"
41488e1f 58#include "xattr-util.h"
8c1be37e 59
28e2641a
FF
60/* how many times to wait for the device nodes to appear */
61#define N_DEVICE_NODE_LIST_ATTEMPTS 10
62
c34b75a1 63int probe_filesystem(const char *node, char **ret_fstype) {
7cc84b2c 64 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
5238e957 65 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
7cc84b2c
ZJS
66 * different error otherwise. */
67
349cc4a5 68#if HAVE_BLKID
8e766630 69 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
18b5886e
LP
70 const char *fstype;
71 int r;
72
995fa2e5 73 errno = 0;
18b5886e
LP
74 b = blkid_new_probe_from_filename(node);
75 if (!b)
66855de7 76 return errno_or_else(ENOMEM);
18b5886e
LP
77
78 blkid_probe_enable_superblocks(b, 1);
79 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
80
81 errno = 0;
82 r = blkid_do_safeprobe(b);
7cc84b2c
ZJS
83 if (r == 1) {
84 log_debug("No type detected on partition %s", node);
18b5886e
LP
85 goto not_found;
86 }
58dfbfbd
LP
87 if (r == -2)
88 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
89 "Results ambiguous for partition %s", node);
b382db9f 90 if (r != 0)
66855de7 91 return errno_or_else(EIO);
18b5886e
LP
92
93 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
94
95 if (fstype) {
96 char *t;
97
98 t = strdup(fstype);
99 if (!t)
100 return -ENOMEM;
101
102 *ret_fstype = t;
103 return 1;
104 }
105
106not_found:
107 *ret_fstype = NULL;
108 return 0;
d1c536f5
ZJS
109#else
110 return -EOPNOTSUPP;
a75e27eb 111#endif
d1c536f5 112}
18b5886e 113
40c10d3f 114#if HAVE_BLKID
4ba86848
LP
115static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
116 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
117 int r;
aae22eb3 118
f70e7f70 119 assert(d);
4ba86848 120 assert(ret);
f70e7f70 121
4ba86848
LP
122 r = sd_device_enumerator_new(&e);
123 if (r < 0)
124 return r;
3c1f2cee 125
4ba86848
LP
126 r = sd_device_enumerator_allow_uninitialized(e);
127 if (r < 0)
128 return r;
129
130 r = sd_device_enumerator_add_match_parent(e, d);
131 if (r < 0)
132 return r;
133
134 *ret = TAKE_PTR(e);
135 return 0;
cde942f6
JPRV
136}
137
4ba86848
LP
138static int device_is_partition(sd_device *d, blkid_partition pp) {
139 blkid_loff_t bsize, bstart;
140 uint64_t size, start;
141 int partno, bpartno, r;
142 const char *ss, *v;
aae22eb3 143
f70e7f70 144 assert(d);
4ba86848 145 assert(pp);
f70e7f70 146
4ba86848
LP
147 r = sd_device_get_subsystem(d, &ss);
148 if (r < 0)
149 return r;
150 if (!streq(ss, "block"))
aae22eb3
LP
151 return false;
152
4ba86848 153 r = sd_device_get_sysattr_value(d, "partition", &v);
acfc2a1d
YW
154 if (r == -ENOENT || /* Not a partition device */
155 ERRNO_IS_PRIVILEGE(r)) /* Not ready to access? */
4ba86848
LP
156 return false;
157 if (r < 0)
158 return r;
159 r = safe_atoi(v, &partno);
160 if (r < 0)
161 return r;
ea887be0 162
4ba86848
LP
163 errno = 0;
164 bpartno = blkid_partition_get_partno(pp);
165 if (bpartno < 0)
166 return errno_or_else(EIO);
ea887be0 167
4ba86848
LP
168 if (partno != bpartno)
169 return false;
f70e7f70 170
4ba86848 171 r = sd_device_get_sysattr_value(d, "start", &v);
ea887be0
ZJS
172 if (r < 0)
173 return r;
4ba86848 174 r = safe_atou64(v, &start);
ea887be0
ZJS
175 if (r < 0)
176 return r;
177
4ba86848
LP
178 errno = 0;
179 bstart = blkid_partition_get_start(pp);
180 if (bstart < 0)
181 return errno_or_else(EIO);
182
183 if (start != (uint64_t) bstart)
184 return false;
185
186 r = sd_device_get_sysattr_value(d, "size", &v);
187 if (r < 0)
188 return r;
189 r = safe_atou64(v, &size);
ea887be0
ZJS
190 if (r < 0)
191 return r;
192
4ba86848
LP
193 errno = 0;
194 bsize = blkid_partition_get_size(pp);
195 if (bsize < 0)
196 return errno_or_else(EIO);
197
198 if (size != (uint64_t) bsize)
199 return false;
200
201 return true;
ea887be0
ZJS
202}
203
4ba86848
LP
204static int find_partition(
205 sd_device *parent,
206 blkid_partition pp,
207 sd_device **ret) {
ea887be0
ZJS
208
209 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
210 sd_device *q;
ea887be0
ZJS
211 int r;
212
4ba86848
LP
213 assert(parent);
214 assert(pp);
215 assert(ret);
f70e7f70 216
4ba86848 217 r = enumerator_for_parent(parent, &e);
ea887be0
ZJS
218 if (r < 0)
219 return r;
220
ea887be0 221 FOREACH_DEVICE(e, q) {
4ba86848
LP
222 r = device_is_partition(q, pp);
223 if (r < 0)
224 return r;
225 if (r > 0) {
226 *ret = sd_device_ref(q);
227 return 0;
052eaf5c 228 }
ea887be0
ZJS
229 }
230
4ba86848
LP
231 return -ENXIO;
232}
10c1b188 233
4ba86848
LP
234struct wait_data {
235 sd_device *parent_device;
236 blkid_partition blkidp;
237 sd_device *found;
238};
ea887be0 239
4ba86848
LP
240static inline void wait_data_done(struct wait_data *d) {
241 sd_device_unref(d->found);
242}
ea887be0 243
4ba86848
LP
244static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) {
245 const char *parent1_path, *parent2_path;
246 struct wait_data *w = userdata;
247 sd_device *pp;
248 int r;
249
250 assert(w);
251
a1130022 252 if (device_for_action(device, SD_DEVICE_REMOVE))
4ba86848
LP
253 return 0;
254
255 r = sd_device_get_parent(device, &pp);
256 if (r < 0)
257 return 0; /* Doesn't have a parent? No relevant to us */
258
259 r = sd_device_get_syspath(pp, &parent1_path); /* Check parent of device of this action */
260 if (r < 0)
261 goto finish;
ea887be0 262
4ba86848
LP
263 r = sd_device_get_syspath(w->parent_device, &parent2_path); /* Check parent of device we are looking for */
264 if (r < 0)
265 goto finish;
266
267 if (!path_equal(parent1_path, parent2_path))
268 return 0; /* Has a different parent than what we need, not interesting to us */
269
270 r = device_is_partition(device, w->blkidp);
271 if (r < 0)
272 goto finish;
273 if (r == 0) /* Not the one we need */
274 return 0;
275
276 /* It's the one we need! Yay! */
277 assert(!w->found);
278 w->found = sd_device_ref(device);
279 r = 0;
280
281finish:
282 return sd_event_exit(sd_device_monitor_get_event(monitor), r);
ea887be0
ZJS
283}
284
4ba86848
LP
285static int wait_for_partition_device(
286 sd_device *parent,
287 blkid_partition pp,
288 usec_t deadline,
289 sd_device **ret) {
290
291 _cleanup_(sd_event_source_unrefp) sd_event_source *timeout_source = NULL;
292 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
293 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
ea887be0
ZJS
294 int r;
295
4ba86848
LP
296 assert(parent);
297 assert(pp);
298 assert(ret);
299
300 r = find_partition(parent, pp, ret);
301 if (r != -ENXIO)
302 return r;
303
304 r = sd_event_new(&event);
305 if (r < 0)
306 return r;
307
308 r = sd_device_monitor_new(&monitor);
309 if (r < 0)
310 return r;
311
312 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, "block", "partition");
313 if (r < 0)
314 return r;
315
316 r = sd_device_monitor_attach_event(monitor, event);
317 if (r < 0)
318 return r;
319
320 _cleanup_(wait_data_done) struct wait_data w = {
321 .parent_device = parent,
322 .blkidp = pp,
323 };
f70e7f70 324
4ba86848
LP
325 r = sd_device_monitor_start(monitor, device_monitor_handler, &w);
326 if (r < 0)
327 return r;
a8040b6d 328
4ba86848
LP
329 /* Check again, the partition might have appeared in the meantime */
330 r = find_partition(parent, pp, ret);
331 if (r != -ENXIO)
332 return r;
333
334 if (deadline != USEC_INFINITY) {
335 r = sd_event_add_time(
336 event, &timeout_source,
337 CLOCK_MONOTONIC, deadline, 0,
338 NULL, INT_TO_PTR(-ETIMEDOUT));
339 if (r < 0)
ea887be0
ZJS
340 return r;
341 }
342
4ba86848
LP
343 r = sd_event_loop(event);
344 if (r < 0)
345 return r;
346
347 assert(w.found);
348 *ret = TAKE_PTR(w.found);
349 return 0;
ea887be0
ZJS
350}
351
0f7c9a3d
LP
352static void check_partition_flags(
353 const char *node,
354 unsigned long long pflags,
355 unsigned long long supported) {
356
357 assert(node);
358
359 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
360 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
361
362 if (pflags == 0)
363 return;
364
365 /* If there are other bits set, then log about it, to make things discoverable */
366 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
367 unsigned long long bit = 1ULL << i;
368 if (!FLAGS_SET(pflags, bit))
369 continue;
370
371 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
372 }
373}
374
786e3a52
LP
375static int device_wait_for_initialization_harder(
376 sd_device *device,
377 const char *subsystem,
378 usec_t deadline,
379 sd_device **ret) {
380
381 _cleanup_free_ char *uevent = NULL;
382 usec_t start, left, retrigger_timeout;
383 int r;
384
385 start = now(CLOCK_MONOTONIC);
386 left = usec_sub_unsigned(deadline, start);
387
388 if (DEBUG_LOGGING) {
389 char buf[FORMAT_TIMESPAN_MAX];
390 const char *sn = NULL;
391
392 (void) sd_device_get_sysname(device, &sn);
393 log_debug("Waiting for device '%s' to initialize for %s.", strna(sn), format_timespan(buf, sizeof(buf), left, 0));
394 }
395
396 if (left != USEC_INFINITY)
397 retrigger_timeout = CLAMP(left / 4, 1 * USEC_PER_SEC, 5 * USEC_PER_SEC); /* A fourth of the total timeout, but let's clamp to 1s…5s range */
398 else
399 retrigger_timeout = 2 * USEC_PER_SEC;
400
401 for (;;) {
402 usec_t local_deadline, n;
403 bool last_try;
404
405 n = now(CLOCK_MONOTONIC);
406 assert(n >= start);
407
408 /* Find next deadline, when we'll retrigger */
409 local_deadline = start +
410 DIV_ROUND_UP(n - start, retrigger_timeout) * retrigger_timeout;
411
412 if (deadline != USEC_INFINITY && deadline <= local_deadline) {
413 local_deadline = deadline;
414 last_try = true;
415 } else
416 last_try = false;
417
418 r = device_wait_for_initialization(device, subsystem, local_deadline, ret);
419 if (r >= 0 && DEBUG_LOGGING) {
420 char buf[FORMAT_TIMESPAN_MAX];
421 const char *sn = NULL;
422
423 (void) sd_device_get_sysname(device, &sn);
424 log_debug("Successfully waited for device '%s' to initialize for %s.", strna(sn), format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
425
426 }
427 if (r != -ETIMEDOUT || last_try)
428 return r;
429
430 if (!uevent) {
431 const char *syspath;
432
433 r = sd_device_get_syspath(device, &syspath);
434 if (r < 0)
435 return r;
436
437 uevent = path_join(syspath, "uevent");
438 if (!uevent)
439 return -ENOMEM;
440 }
441
442 if (DEBUG_LOGGING) {
443 char buf[FORMAT_TIMESPAN_MAX];
444
445 log_debug("Device didn't initialize within %s, assuming lost event. Retriggering device through %s.",
446 format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0),
447 uevent);
448 }
449
450 r = write_string_file(uevent, "change", WRITE_STRING_FILE_DISABLE_BUFFER);
451 if (r < 0)
452 return r;
453 }
454}
40c10d3f 455#endif
aae22eb3 456
4ba86848
LP
457#define DEVICE_TIMEOUT_USEC (45 * USEC_PER_SEC)
458
4526113f
LP
459int dissect_image(
460 int fd,
89e62e0b 461 const VeritySettings *verity,
18d73705 462 const MountOptions *mount_options,
4526113f
LP
463 DissectImageFlags flags,
464 DissectedImage **ret) {
8c1be37e 465
349cc4a5 466#if HAVE_BLKID
62ea0ed0
LP
467#ifdef GPT_ROOT_NATIVE
468 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL;
469#endif
470#ifdef GPT_USR_NATIVE
471 sd_id128_t usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
472#endif
8c1be37e 473 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
3c1f2cee 474 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
8c1be37e 475 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
8e766630 476 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
8c1be37e 477 _cleanup_free_ char *generic_node = NULL;
be30ad41 478 sd_id128_t generic_uuid = SD_ID128_NULL;
593fe6c0 479 const char *pttype = NULL, *sysname = NULL;
8c1be37e 480 blkid_partlist pl;
4ba86848 481 int r, generic_nr, n_partitions;
8c1be37e 482 struct stat st;
4ba86848 483 usec_t deadline;
8c1be37e
LP
484
485 assert(fd >= 0);
486 assert(ret);
89e62e0b 487 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
e7cbe5cb 488 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
8c1be37e
LP
489
490 /* Probes a disk image, and returns information about what it found in *ret.
491 *
4623e8e6
LP
492 * Returns -ENOPKG if no suitable partition table or file system could be found.
493 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
494
89e62e0b 495 if (verity && verity->root_hash) {
aee36b4e
LP
496 sd_id128_t fsuuid, vuuid;
497
498 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
499 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
500 * the final 128bit. */
4623e8e6 501
89e62e0b 502 if (verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
503 return -EINVAL;
504
aee36b4e
LP
505 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
506 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
4623e8e6 507
aee36b4e 508 if (sd_id128_is_null(fsuuid))
4623e8e6 509 return -EINVAL;
aee36b4e 510 if (sd_id128_is_null(vuuid))
4623e8e6 511 return -EINVAL;
aee36b4e
LP
512
513 /* If the verity data declares it's for the /usr partition, then search for that, in all
514 * other cases assume it's for the root partition. */
62ea0ed0 515#ifdef GPT_USR_NATIVE
aee36b4e
LP
516 if (verity->designator == PARTITION_USR) {
517 usr_uuid = fsuuid;
518 usr_verity_uuid = vuuid;
519 } else {
62ea0ed0
LP
520#endif
521#ifdef GPT_ROOT_NATIVE
aee36b4e
LP
522 root_uuid = fsuuid;
523 root_verity_uuid = vuuid;
62ea0ed0
LP
524#endif
525#ifdef GPT_USR_NATIVE
aee36b4e 526 }
62ea0ed0 527#endif
4623e8e6 528 }
8c1be37e
LP
529
530 if (fstat(fd, &st) < 0)
531 return -errno;
532
533 if (!S_ISBLK(st.st_mode))
534 return -ENOTBLK;
535
930aa88f 536 r = sd_device_new_from_stat_rdev(&d, &st);
6c544d14
LP
537 if (r < 0)
538 return r;
539
540 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
541 _cleanup_(sd_device_unrefp) sd_device *initialized = NULL;
542
543 /* If udev support is enabled, then let's wait for the device to be initialized before we doing anything. */
544
786e3a52
LP
545 r = device_wait_for_initialization_harder(
546 d,
547 "block",
548 usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC),
549 &initialized);
6c544d14
LP
550 if (r < 0)
551 return r;
552
553 sd_device_unref(d);
554 d = TAKE_PTR(initialized);
555 }
556
8c1be37e
LP
557 b = blkid_new_probe();
558 if (!b)
559 return -ENOMEM;
560
561 errno = 0;
562 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f 563 if (r != 0)
66855de7 564 return errno_or_else(ENOMEM);
8c1be37e 565
9b6deb03
LP
566 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
567 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
568 blkid_probe_enable_superblocks(b, 1);
569 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
570 }
571
8c1be37e
LP
572 blkid_probe_enable_partitions(b, 1);
573 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
574
575 errno = 0;
576 r = blkid_do_safeprobe(b);
59ba6d0c
LP
577 if (IN_SET(r, -2, 1))
578 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
b382db9f 579 if (r != 0)
66855de7 580 return errno_or_else(EIO);
8c1be37e
LP
581
582 m = new0(DissectedImage, 1);
583 if (!m)
584 return -ENOMEM;
585
593fe6c0
LB
586 r = sd_device_get_sysname(d, &sysname);
587 if (r < 0)
588 return log_debug_errno(r, "Failed to get device sysname: %m");
589 if (startswith(sysname, "loop")) {
590 _cleanup_free_ char *name_stripped = NULL;
591 const char *full_path;
592
593 r = sd_device_get_sysattr_value(d, "loop/backing_file", &full_path);
594 if (r < 0)
595 log_debug_errno(r, "Failed to lookup image name via loop device backing file sysattr, ignoring: %m");
596 else {
597 r = raw_strip_suffixes(basename(full_path), &name_stripped);
598 if (r < 0)
599 return r;
600 }
601
602 free_and_replace(m->image_name, name_stripped);
603 } else {
604 r = free_and_strdup(&m->image_name, sysname);
605 if (r < 0)
606 return r;
607 }
608
609 if (!image_name_is_valid(m->image_name)) {
610 log_debug("Image name %s is not valid, ignoring", strempty(m->image_name));
611 m->image_name = mfree(m->image_name);
612 }
613
e7cbe5cb
LB
614 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
615 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) ||
616 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
9b6deb03 617 const char *usage = NULL;
8c1be37e 618
aee36b4e
LP
619 /* If flags permit this, also allow using non-partitioned single-filesystem images */
620
9b6deb03
LP
621 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
622 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
6c544d14 623 const char *fstype = NULL, *options = NULL, *devname = NULL;
18d73705 624 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
8c1be37e 625
9b6deb03
LP
626 /* OK, we have found a file system, that's our root partition then. */
627 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 628
9b6deb03
LP
629 if (fstype) {
630 t = strdup(fstype);
631 if (!t)
632 return -ENOMEM;
633 }
634
6c544d14 635 r = sd_device_get_devname(d, &devname);
54b22b26
LP
636 if (r < 0)
637 return r;
8c1be37e 638
6c544d14
LP
639 n = strdup(devname);
640 if (!n)
641 return -ENOMEM;
642
e7cbe5cb 643 m->single_file_system = true;
aee36b4e 644 m->verity = verity && verity->root_hash && verity->data_path && (verity->designator < 0 || verity->designator == PARTITION_ROOT);
89e62e0b 645 m->can_verity = verity && verity->data_path;
e7cbe5cb 646
f5215bc8 647 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
648 if (options) {
649 o = strdup(options);
650 if (!o)
651 return -ENOMEM;
652 }
653
9b6deb03
LP
654 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
655 .found = true,
e7cbe5cb 656 .rw = !m->verity,
9b6deb03
LP
657 .partno = -1,
658 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
659 .fstype = TAKE_PTR(t),
660 .node = TAKE_PTR(n),
18d73705 661 .mount_options = TAKE_PTR(o),
9b6deb03 662 };
8c1be37e 663
4db1879a 664 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
18b5886e 665
1cc6c93a 666 *ret = TAKE_PTR(m);
9b6deb03
LP
667 return 0;
668 }
8c1be37e
LP
669 }
670
671 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
672 if (!pttype)
673 return -ENOPKG;
674
675 is_gpt = streq_ptr(pttype, "gpt");
676 is_mbr = streq_ptr(pttype, "dos");
677
9b6deb03 678 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
679 return -ENOPKG;
680
4ba86848
LP
681 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
682 * do partition scanning. */
683 r = blockdev_partscan_enabled(fd);
684 if (r < 0)
685 return r;
686 if (r == 0)
687 return -EPROTONOSUPPORT;
688
8c1be37e
LP
689 errno = 0;
690 pl = blkid_probe_get_partitions(b);
b382db9f 691 if (!pl)
66855de7 692 return errno_or_else(ENOMEM);
8c1be37e 693
4ba86848
LP
694 errno = 0;
695 n_partitions = blkid_partlist_numof_partitions(pl);
696 if (n_partitions < 0)
697 return errno_or_else(EIO);
8c1be37e 698
4ba86848
LP
699 deadline = usec_add(now(CLOCK_MONOTONIC), DEVICE_TIMEOUT_USEC);
700 for (int i = 0; i < n_partitions; i++) {
701 _cleanup_(sd_device_unrefp) sd_device *q = NULL;
9b6deb03 702 unsigned long long pflags;
8c1be37e 703 blkid_partition pp;
cde942f6 704 const char *node;
8c1be37e
LP
705 int nr;
706
4ba86848
LP
707 errno = 0;
708 pp = blkid_partlist_get_partition(pl, i);
709 if (!pp)
710 return errno_or_else(EIO);
aae22eb3 711
4ba86848
LP
712 r = wait_for_partition_device(d, pp, deadline, &q);
713 if (r < 0)
714 return r;
7be1420f 715
3c1f2cee
YW
716 r = sd_device_get_devname(q, &node);
717 if (r < 0)
4ba86848 718 return r;
8c1be37e 719
9b6deb03 720 pflags = blkid_partition_get_flags(pp);
8c1be37e 721
4ba86848 722 errno = 0;
8c1be37e
LP
723 nr = blkid_partition_get_partno(pp);
724 if (nr < 0)
4ba86848 725 return errno_or_else(EIO);
8c1be37e
LP
726
727 if (is_gpt) {
569a0e42
LP
728 PartitionDesignator designator = _PARTITION_DESIGNATOR_INVALID;
729 int architecture = _ARCHITECTURE_INVALID;
4623e8e6
LP
730 const char *stype, *sid, *fstype = NULL;
731 sd_id128_t type_id, id;
8c1be37e
LP
732 bool rw = true;
733
4623e8e6
LP
734 sid = blkid_partition_get_uuid(pp);
735 if (!sid)
736 continue;
737 if (sd_id128_from_string(sid, &id) < 0)
738 continue;
739
8c1be37e
LP
740 stype = blkid_partition_get_type_string(pp);
741 if (!stype)
742 continue;
8c1be37e
LP
743 if (sd_id128_from_string(stype, &type_id) < 0)
744 continue;
745
746 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347 747
0f7c9a3d
LP
748 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
749
a48dd347
LP
750 if (pflags & GPT_FLAG_NO_AUTO)
751 continue;
752
8c1be37e 753 designator = PARTITION_HOME;
9b6deb03 754 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 755
8c1be37e 756 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347 757
0f7c9a3d
LP
758 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
759
a48dd347
LP
760 if (pflags & GPT_FLAG_NO_AUTO)
761 continue;
762
8c1be37e 763 designator = PARTITION_SRV;
9b6deb03 764 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 765
8c1be37e 766 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347 767
aee36b4e
LP
768 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is
769 * not defined there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
770 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
771 * Partitions"). */
a48dd347
LP
772
773 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
774 continue;
775
8c1be37e
LP
776 designator = PARTITION_ESP;
777 fstype = "vfat";
a8c47660
LP
778
779 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
780
0f7c9a3d
LP
781 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
782
a8c47660
LP
783 if (pflags & GPT_FLAG_NO_AUTO)
784 continue;
785
786 designator = PARTITION_XBOOTLDR;
787 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
788 }
789#ifdef GPT_ROOT_NATIVE
790 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 791
0f7c9a3d
LP
792 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
793
a48dd347
LP
794 if (pflags & GPT_FLAG_NO_AUTO)
795 continue;
796
4623e8e6
LP
797 /* If a root ID is specified, ignore everything but the root id */
798 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
799 continue;
800
8c1be37e
LP
801 designator = PARTITION_ROOT;
802 architecture = native_architecture();
9b6deb03 803 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 804
4f8b86e3 805 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 806
0f7c9a3d
LP
807 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
808
a48dd347
LP
809 if (pflags & GPT_FLAG_NO_AUTO)
810 continue;
811
4623e8e6
LP
812 m->can_verity = true;
813
814 /* Ignore verity unless a root hash is specified */
aee36b4e 815 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
4623e8e6
LP
816 continue;
817
818 designator = PARTITION_ROOT_VERITY;
819 fstype = "DM_verity_hash";
820 architecture = native_architecture();
821 rw = false;
822 }
823#endif
8c1be37e
LP
824#ifdef GPT_ROOT_SECONDARY
825 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 826
0f7c9a3d
LP
827 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
828
a48dd347
LP
829 if (pflags & GPT_FLAG_NO_AUTO)
830 continue;
831
4623e8e6
LP
832 /* If a root ID is specified, ignore everything but the root id */
833 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
834 continue;
835
8c1be37e
LP
836 designator = PARTITION_ROOT_SECONDARY;
837 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 838 rw = !(pflags & GPT_FLAG_READ_ONLY);
aee36b4e 839
4f8b86e3 840 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347 841
0f7c9a3d
LP
842 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
843
a48dd347
LP
844 if (pflags & GPT_FLAG_NO_AUTO)
845 continue;
846
4623e8e6
LP
847 m->can_verity = true;
848
849 /* Ignore verity unless root has is specified */
aee36b4e 850 if (sd_id128_is_null(root_verity_uuid) || !sd_id128_equal(root_verity_uuid, id))
4623e8e6
LP
851 continue;
852
853 designator = PARTITION_ROOT_SECONDARY_VERITY;
854 fstype = "DM_verity_hash";
855 architecture = SECONDARY_ARCHITECTURE;
856 rw = false;
857 }
aee36b4e
LP
858#endif
859#ifdef GPT_USR_NATIVE
860 else if (sd_id128_equal(type_id, GPT_USR_NATIVE)) {
861
862 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
863
864 if (pflags & GPT_FLAG_NO_AUTO)
865 continue;
866
867 /* If a usr ID is specified, ignore everything but the usr id */
868 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
869 continue;
870
871 designator = PARTITION_USR;
872 architecture = native_architecture();
873 rw = !(pflags & GPT_FLAG_READ_ONLY);
874
875 } else if (sd_id128_equal(type_id, GPT_USR_NATIVE_VERITY)) {
876
877 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
878
879 if (pflags & GPT_FLAG_NO_AUTO)
880 continue;
881
882 m->can_verity = true;
883
884 /* Ignore verity unless a usr hash is specified */
885 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
886 continue;
887
888 designator = PARTITION_USR_VERITY;
889 fstype = "DM_verity_hash";
890 architecture = native_architecture();
891 rw = false;
892 }
893#endif
894#ifdef GPT_USR_SECONDARY
895 else if (sd_id128_equal(type_id, GPT_USR_SECONDARY)) {
896
897 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
898
899 if (pflags & GPT_FLAG_NO_AUTO)
900 continue;
901
902 /* If a usr ID is specified, ignore everything but the usr id */
903 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
904 continue;
905
906 designator = PARTITION_USR_SECONDARY;
907 architecture = SECONDARY_ARCHITECTURE;
908 rw = !(pflags & GPT_FLAG_READ_ONLY);
909
910 } else if (sd_id128_equal(type_id, GPT_USR_SECONDARY_VERITY)) {
911
912 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
913
914 if (pflags & GPT_FLAG_NO_AUTO)
915 continue;
916
917 m->can_verity = true;
918
919 /* Ignore verity unless usr has is specified */
920 if (sd_id128_is_null(usr_verity_uuid) || !sd_id128_equal(usr_verity_uuid, id))
921 continue;
922
923 designator = PARTITION_USR_SECONDARY_VERITY;
924 fstype = "DM_verity_hash";
925 architecture = SECONDARY_ARCHITECTURE;
926 rw = false;
927 }
8c1be37e
LP
928#endif
929 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347 930
0f7c9a3d
LP
931 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
932
a48dd347
LP
933 if (pflags & GPT_FLAG_NO_AUTO)
934 continue;
935
8c1be37e
LP
936 designator = PARTITION_SWAP;
937 fstype = "swap";
aee36b4e 938
8c1be37e
LP
939 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
940
0f7c9a3d
LP
941 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
942
a48dd347
LP
943 if (pflags & GPT_FLAG_NO_AUTO)
944 continue;
945
8c1be37e
LP
946 if (generic_node)
947 multiple_generic = true;
948 else {
949 generic_nr = nr;
9b6deb03 950 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
be30ad41 951 generic_uuid = id;
8c1be37e
LP
952 generic_node = strdup(node);
953 if (!generic_node)
954 return -ENOMEM;
955 }
d4dffb85
LP
956
957 } else if (sd_id128_equal(type_id, GPT_TMP)) {
958
0f7c9a3d
LP
959 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
960
d4dffb85
LP
961 if (pflags & GPT_FLAG_NO_AUTO)
962 continue;
963
964 designator = PARTITION_TMP;
965 rw = !(pflags & GPT_FLAG_READ_ONLY);
966
967 } else if (sd_id128_equal(type_id, GPT_VAR)) {
968
0f7c9a3d
LP
969 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
970
d4dffb85
LP
971 if (pflags & GPT_FLAG_NO_AUTO)
972 continue;
973
974 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
975 sd_id128_t var_uuid;
976
977 /* For /var we insist that the uuid of the partition matches the
978 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
979 * ID. Why? Unlike the other partitions /var is inherently
980 * installation specific, hence we need to be careful not to mount it
981 * in the wrong installation. By hashing the partition UUID from
982 * /etc/machine-id we can securely bind the partition to the
983 * installation. */
984
985 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
986 if (r < 0)
987 return r;
988
989 if (!sd_id128_equal(var_uuid, id)) {
990 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
991 continue;
992 }
993 }
994
995 designator = PARTITION_VAR;
996 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
997 }
998
999 if (designator != _PARTITION_DESIGNATOR_INVALID) {
18d73705
LB
1000 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
1001 const char *options = NULL;
8c1be37e
LP
1002
1003 /* First one wins */
1004 if (m->partitions[designator].found)
1005 continue;
1006
1007 if (fstype) {
1008 t = strdup(fstype);
1009 if (!t)
1010 return -ENOMEM;
1011 }
1012
1013 n = strdup(node);
1014 if (!n)
1015 return -ENOMEM;
1016
f5215bc8 1017 options = mount_options_from_designator(mount_options, designator);
18d73705
LB
1018 if (options) {
1019 o = strdup(options);
1020 if (!o)
1021 return -ENOMEM;
1022 }
1023
8c1be37e
LP
1024 m->partitions[designator] = (DissectedPartition) {
1025 .found = true,
1026 .partno = nr,
1027 .rw = rw,
1028 .architecture = architecture,
1cc6c93a
YW
1029 .node = TAKE_PTR(n),
1030 .fstype = TAKE_PTR(t),
be30ad41 1031 .uuid = id,
18d73705 1032 .mount_options = TAKE_PTR(o),
8c1be37e 1033 };
8c1be37e
LP
1034 }
1035
1036 } else if (is_mbr) {
1037
a8c47660 1038 switch (blkid_partition_get_type(pp)) {
8c1be37e 1039
a8c47660
LP
1040 case 0x83: /* Linux partition */
1041
1042 if (pflags != 0x80) /* Bootable flag */
1043 continue;
8c1be37e 1044
a8c47660
LP
1045 if (generic_node)
1046 multiple_generic = true;
1047 else {
1048 generic_nr = nr;
1049 generic_rw = true;
1050 generic_node = strdup(node);
1051 if (!generic_node)
1052 return -ENOMEM;
1053 }
1054
1055 break;
1056
1057 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
18d73705 1058 _cleanup_free_ char *n = NULL, *o = NULL;
a8c47660 1059 sd_id128_t id = SD_ID128_NULL;
18d73705 1060 const char *sid, *options = NULL;
a8c47660
LP
1061
1062 /* First one wins */
1063 if (m->partitions[PARTITION_XBOOTLDR].found)
1064 continue;
1065
1066 sid = blkid_partition_get_uuid(pp);
1067 if (sid)
1068 (void) sd_id128_from_string(sid, &id);
1069
1070 n = strdup(node);
1071 if (!n)
8c1be37e 1072 return -ENOMEM;
a8c47660 1073
f5215bc8 1074 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
18d73705
LB
1075 if (options) {
1076 o = strdup(options);
1077 if (!o)
1078 return -ENOMEM;
1079 }
1080
a8c47660
LP
1081 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1082 .found = true,
1083 .partno = nr,
1084 .rw = true,
1085 .architecture = _ARCHITECTURE_INVALID,
1086 .node = TAKE_PTR(n),
1087 .uuid = id,
18d73705 1088 .mount_options = TAKE_PTR(o),
a8c47660
LP
1089 };
1090
1091 break;
1092 }}
8c1be37e
LP
1093 }
1094 }
1095
74cb2db9
LP
1096 if (m->partitions[PARTITION_ROOT].found) {
1097 /* If we found the primary arch, then invalidate the secondary arch to avoid any ambiguities,
1098 * since we never want to mount the secondary arch in this case. */
1099 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
1100 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
aee36b4e
LP
1101 m->partitions[PARTITION_USR_SECONDARY].found = false;
1102 m->partitions[PARTITION_USR_SECONDARY_VERITY].found = false;
74cb2db9 1103 } else {
8c1be37e
LP
1104 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
1105 * either, then check if there's a single generic one, and use that. */
1106
4623e8e6 1107 if (m->partitions[PARTITION_ROOT_VERITY].found)
e0f9e7bd 1108 return -EADDRNOTAVAIL;
4623e8e6 1109
aee36b4e
LP
1110 /* We didn't find a primary architecture root, but we found a primary architecture /usr? Refuse that for now. */
1111 if (m->partitions[PARTITION_USR].found || m->partitions[PARTITION_USR_VERITY].found)
1112 return -EADDRNOTAVAIL;
1113
8c1be37e 1114 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
aee36b4e 1115 /* Upgrade secondary arch to first */
8c1be37e
LP
1116 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
1117 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
4623e8e6
LP
1118 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
1119 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
1120
aee36b4e
LP
1121 m->partitions[PARTITION_USR] = m->partitions[PARTITION_USR_SECONDARY];
1122 zero(m->partitions[PARTITION_USR_SECONDARY]);
1123 m->partitions[PARTITION_USR_VERITY] = m->partitions[PARTITION_USR_SECONDARY_VERITY];
1124 zero(m->partitions[PARTITION_USR_SECONDARY_VERITY]);
1125
e0f9e7bd 1126 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
18d73705
LB
1127 _cleanup_free_ char *o = NULL;
1128 const char *options = NULL;
e0f9e7bd 1129
2aed63f4
ZJS
1130 /* If the root hash was set, then we won't fall back to a generic node, because the
1131 * root hash decides. */
89e62e0b 1132 if (verity && verity->root_hash)
e0f9e7bd 1133 return -EADDRNOTAVAIL;
8c1be37e 1134
e0f9e7bd
LP
1135 /* If we didn't find a generic node, then we can't fix this up either */
1136 if (!generic_node)
1137 return -ENXIO;
1138
1139 /* If we didn't find a properly marked root partition, but we did find a single suitable
1140 * generic Linux partition, then use this as root partition, if the caller asked for it. */
8c1be37e
LP
1141 if (multiple_generic)
1142 return -ENOTUNIQ;
1143
f5215bc8 1144 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
18d73705
LB
1145 if (options) {
1146 o = strdup(options);
1147 if (!o)
1148 return -ENOMEM;
1149 }
1150
8c1be37e
LP
1151 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1152 .found = true,
1153 .rw = generic_rw,
1154 .partno = generic_nr,
1155 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 1156 .node = TAKE_PTR(generic_node),
be30ad41 1157 .uuid = generic_uuid,
18d73705 1158 .mount_options = TAKE_PTR(o),
8c1be37e 1159 };
e0f9e7bd 1160 }
8c1be37e
LP
1161 }
1162
aee36b4e
LP
1163 /* Refuse if we found a verity partition for /usr but no matching file system partition */
1164 if (!m->partitions[PARTITION_USR].found && m->partitions[PARTITION_USR_VERITY].found)
1165 return -EADDRNOTAVAIL;
1166
1167 /* Combinations of verity /usr with verity-less root is OK, but the reverse is not */
c848516f 1168 if (m->partitions[PARTITION_ROOT_VERITY].found && m->partitions[PARTITION_USR].found && !m->partitions[PARTITION_USR_VERITY].found)
aee36b4e
LP
1169 return -EADDRNOTAVAIL;
1170
89e62e0b 1171 if (verity && verity->root_hash) {
aee36b4e
LP
1172 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1173 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1174 return -EADDRNOTAVAIL;
1175
1176 /* If we found a verity setup, then the root partition is necessarily read-only. */
1177 m->partitions[PARTITION_ROOT].rw = false;
1178 m->verity = true;
1179 }
4623e8e6 1180
aee36b4e
LP
1181 if (verity->designator == PARTITION_USR) {
1182 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1183 return -EADDRNOTAVAIL;
4623e8e6 1184
aee36b4e
LP
1185 m->partitions[PARTITION_USR].rw = false;
1186 m->verity = true;
1187 }
4623e8e6
LP
1188 }
1189
18b5886e
LP
1190 blkid_free_probe(b);
1191 b = NULL;
1192
8c1be37e 1193 /* Fill in file system types if we don't know them yet. */
569a0e42 1194 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 1195 DissectedPartition *p = m->partitions + i;
8c1be37e 1196
18b5886e 1197 if (!p->found)
8c1be37e
LP
1198 continue;
1199
18b5886e
LP
1200 if (!p->fstype && p->node) {
1201 r = probe_filesystem(p->node, &p->fstype);
7cc84b2c 1202 if (r < 0 && r != -EUCLEAN)
18b5886e 1203 return r;
8c1be37e
LP
1204 }
1205
18b5886e
LP
1206 if (streq_ptr(p->fstype, "crypto_LUKS"))
1207 m->encrypted = true;
896f937f
LP
1208
1209 if (p->fstype && fstype_is_ro(p->fstype))
1210 p->rw = false;
8c1be37e
LP
1211 }
1212
1cc6c93a 1213 *ret = TAKE_PTR(m);
8c1be37e
LP
1214 return 0;
1215#else
1216 return -EOPNOTSUPP;
1217#endif
1218}
1219
1220DissectedImage* dissected_image_unref(DissectedImage *m) {
8c1be37e
LP
1221 if (!m)
1222 return NULL;
1223
569a0e42 1224 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
8c1be37e
LP
1225 free(m->partitions[i].fstype);
1226 free(m->partitions[i].node);
18b5886e
LP
1227 free(m->partitions[i].decrypted_fstype);
1228 free(m->partitions[i].decrypted_node);
18d73705 1229 free(m->partitions[i].mount_options);
8c1be37e
LP
1230 }
1231
593fe6c0 1232 free(m->image_name);
3b925504
LP
1233 free(m->hostname);
1234 strv_free(m->machine_info);
1235 strv_free(m->os_release);
7718ac97 1236 strv_free(m->extension_release);
3b925504 1237
5fecf46d 1238 return mfree(m);
8c1be37e
LP
1239}
1240
18b5886e 1241static int is_loop_device(const char *path) {
553e15f2 1242 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
1243 struct stat st;
1244
1245 assert(path);
1246
1247 if (stat(path, &st) < 0)
1248 return -errno;
1249
1250 if (!S_ISBLK(st.st_mode))
1251 return -ENOTBLK;
1252
553e15f2 1253 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
1254 if (access(s, F_OK) < 0) {
1255 if (errno != ENOENT)
1256 return -errno;
1257
1258 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 1259 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
1260 if (access(s, F_OK) < 0)
1261 return errno == ENOENT ? false : -errno;
1262 }
1263
1264 return true;
1265}
1266
cf32c486
LP
1267static int run_fsck(const char *node, const char *fstype) {
1268 int r, exit_status;
1269 pid_t pid;
1270
1271 assert(node);
1272 assert(fstype);
1273
1274 r = fsck_exists(fstype);
1275 if (r < 0) {
1276 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1277 return 0;
1278 }
1279 if (r == 0) {
1280 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
1281 return 0;
1282 }
1283
1284 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
1285 if (r < 0)
1286 return log_debug_errno(r, "Failed to fork off fsck: %m");
1287 if (r == 0) {
1288 /* Child */
1289 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
1290 log_debug_errno(errno, "Failed to execl() fsck: %m");
1291 _exit(FSCK_OPERATIONAL_ERROR);
1292 }
1293
1294 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1295 if (exit_status < 0)
1296 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1297
1298 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1299 log_debug("fsck failed with exit status %i.", exit_status);
1300
1301 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1302 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1303
1304 log_debug("Ignoring fsck error.");
1305 }
1306
1307 return 0;
1308}
1309
18b5886e
LP
1310static int mount_partition(
1311 DissectedPartition *m,
1312 const char *where,
1313 const char *directory,
2d3a5a73 1314 uid_t uid_shift,
18b5886e
LP
1315 DissectImageFlags flags) {
1316
2d3a5a73
LP
1317 _cleanup_free_ char *chased = NULL, *options = NULL;
1318 const char *p, *node, *fstype;
8c1be37e 1319 bool rw;
2eedfd2d 1320 int r;
8c1be37e
LP
1321
1322 assert(m);
1323 assert(where);
1324
4dc28665 1325 /* Use decrypted node and matching fstype if available, otherwise use the original device */
18b5886e 1326 node = m->decrypted_node ?: m->node;
4dc28665 1327 fstype = m->decrypted_node ? m->decrypted_fstype: m->fstype;
18b5886e 1328
4dc28665 1329 if (!m->found || !node)
8c1be37e 1330 return 0;
4dc28665
LP
1331 if (!fstype)
1332 return -EAFNOSUPPORT;
8c1be37e 1333
fa45d12c 1334 /* 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 1335 if (streq(fstype, "crypto_LUKS"))
fa45d12c 1336 return -EUNATCH;
18b5886e
LP
1337
1338 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
8c1be37e 1339
cf32c486
LP
1340 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1341 r = run_fsck(node, fstype);
1342 if (r < 0)
1343 return r;
1344 }
1345
2eedfd2d 1346 if (directory) {
1f0f82f1
LP
1347 if (!FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY)) {
1348 /* Automatically create missing mount points, if necessary. */
1349 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1350 if (r < 0)
1351 return r;
1352 }
1353
a5648b80 1354 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2eedfd2d
LP
1355 if (r < 0)
1356 return r;
1357
1358 p = chased;
1359 } else
8c1be37e
LP
1360 p = where;
1361
18b5886e 1362 /* If requested, turn on discard support. */
154d2269 1363 if (fstype_can_discard(fstype) &&
18b5886e 1364 ((flags & DISSECT_IMAGE_DISCARD) ||
3afda7c7 1365 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0))) {
2d3a5a73
LP
1366 options = strdup("discard");
1367 if (!options)
1368 return -ENOMEM;
1369 }
1370
1371 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
1372 _cleanup_free_ char *uid_option = NULL;
1373
1374 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1375 return -ENOMEM;
1376
c2bc710b 1377 if (!strextend_with_separator(&options, ",", uid_option))
2d3a5a73
LP
1378 return -ENOMEM;
1379 }
8c1be37e 1380
18d73705 1381 if (!isempty(m->mount_options))
c2bc710b 1382 if (!strextend_with_separator(&options, ",", m->mount_options))
18d73705
LB
1383 return -ENOMEM;
1384
5c05f062
LP
1385 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1386 r = mkdir_p(p, 0755);
1387 if (r < 0)
1388 return r;
1389 }
1390
511a8cfe 1391 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
d9223c07
LP
1392 if (r < 0)
1393 return r;
1394
1395 return 1;
8c1be37e
LP
1396}
1397
2d3a5a73 1398int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1f0f82f1 1399 int r, xbootldr_mounted;
8c1be37e
LP
1400
1401 assert(m);
1402 assert(where);
1403
fa45d12c
LP
1404 /* Returns:
1405 *
1406 * -ENXIO → No root partition found
7718ac97 1407 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
fa45d12c
LP
1408 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1409 * -EUCLEAN → fsck for file system failed
1410 * -EBUSY → File system already mounted/used elsewhere (kernel)
4dc28665 1411 * -EAFNOSUPPORT → File system type not supported or not known
fa45d12c
LP
1412 */
1413
8c1be37e
LP
1414 if (!m->partitions[PARTITION_ROOT].found)
1415 return -ENXIO;
1416
2d3a5a73
LP
1417 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1418 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
1419 if (r < 0)
1420 return r;
aee36b4e
LP
1421 }
1422
1423 /* Mask DISSECT_IMAGE_MKDIR for all subdirs: the idea is that only the top-level mount point is
1424 * created if needed, but the image itself not modified. */
1425 flags &= ~DISSECT_IMAGE_MKDIR;
1426
1427 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1428 /* For us mounting root always means mounting /usr as well */
1429 r = mount_partition(m->partitions + PARTITION_USR, where, "/usr", uid_shift, flags);
1430 if (r < 0)
1431 return r;
03bcb6d4
LP
1432
1433 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
1434 r = path_is_os_tree(where);
1435 if (r < 0)
1436 return r;
7718ac97
LB
1437 if (r == 0) {
1438 r = path_is_extension_tree(where, m->image_name);
1439 if (r < 0)
1440 return r;
1441 if (r == 0)
1442 return -EMEDIUMTYPE;
1443 }
03bcb6d4 1444 }
2d3a5a73
LP
1445 }
1446
705727fd 1447 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 1448 return 0;
8c1be37e 1449
2d3a5a73 1450 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
8c1be37e
LP
1451 if (r < 0)
1452 return r;
1453
2d3a5a73 1454 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
8c1be37e
LP
1455 if (r < 0)
1456 return r;
1457
d4dffb85
LP
1458 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, flags);
1459 if (r < 0)
1460 return r;
1461
1462 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, flags);
1463 if (r < 0)
1464 return r;
1465
1f0f82f1
LP
1466 xbootldr_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, flags);
1467 if (xbootldr_mounted < 0)
1468 return xbootldr_mounted;
d9223c07 1469
8c1be37e 1470 if (m->partitions[PARTITION_ESP].found) {
1f0f82f1
LP
1471 int esp_done = false;
1472
d9223c07
LP
1473 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1474 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
8c1be37e 1475
a5648b80 1476 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
1f0f82f1
LP
1477 if (r < 0) {
1478 if (r != -ENOENT)
d9223c07 1479 return r;
8c1be37e 1480
1f0f82f1
LP
1481 /* /efi doesn't exist. Let's see if /boot is suitable then */
1482
1483 if (!xbootldr_mounted) {
1484 _cleanup_free_ char *p = NULL;
2eedfd2d 1485
1f0f82f1
LP
1486 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
1487 if (r < 0) {
1488 if (r != -ENOENT)
1489 return r;
1490 } else if (dir_is_empty(p) > 0) {
1491 /* It exists and is an empty directory. Let's mount the ESP there. */
1492 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, flags);
1493 if (r < 0)
1494 return r;
1495
1496 esp_done = true;
1497 }
2eedfd2d 1498 }
8c1be37e 1499 }
1f0f82f1
LP
1500
1501 if (!esp_done) {
1502 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1503
1504 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, flags);
1505 if (r < 0)
1506 return r;
1507 }
8c1be37e
LP
1508 }
1509
1510 return 0;
1511}
1512
af187ab2
LP
1513int dissected_image_mount_and_warn(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
1514 int r;
1515
1516 assert(m);
1517 assert(where);
1518
1519 r = dissected_image_mount(m, where, uid_shift, flags);
1520 if (r == -ENXIO)
1521 return log_error_errno(r, "Not root file system found in image.");
1522 if (r == -EMEDIUMTYPE)
7718ac97 1523 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
af187ab2
LP
1524 if (r == -EUNATCH)
1525 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
1526 if (r == -EUCLEAN)
1527 return log_error_errno(r, "File system check on image failed.");
1528 if (r == -EBUSY)
1529 return log_error_errno(r, "File system already mounted elsewhere.");
4dc28665
LP
1530 if (r == -EAFNOSUPPORT)
1531 return log_error_errno(r, "File system type not supported or not known.");
af187ab2
LP
1532 if (r < 0)
1533 return log_error_errno(r, "Failed to mount image: %m");
1534
1535 return r;
1536}
1537
349cc4a5 1538#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1539typedef struct DecryptedPartition {
1540 struct crypt_device *device;
1541 char *name;
1542 bool relinquished;
1543} DecryptedPartition;
1544
1545struct DecryptedImage {
1546 DecryptedPartition *decrypted;
1547 size_t n_decrypted;
1548 size_t n_allocated;
1549};
1550#endif
1551
1552DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
349cc4a5 1553#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1554 int r;
1555
1556 if (!d)
1557 return NULL;
1558
67f63ee5 1559 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
1560 DecryptedPartition *p = d->decrypted + i;
1561
1562 if (p->device && p->name && !p->relinquished) {
0d12936d 1563 r = sym_crypt_deactivate_by_name(p->device, p->name, 0);
18b5886e
LP
1564 if (r < 0)
1565 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1566 }
1567
1568 if (p->device)
0d12936d 1569 sym_crypt_free(p->device);
18b5886e
LP
1570 free(p->name);
1571 }
1572
1573 free(d);
1574#endif
1575 return NULL;
1576}
1577
349cc4a5 1578#if HAVE_LIBCRYPTSETUP
4623e8e6
LP
1579
1580static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1581 _cleanup_free_ char *name = NULL, *node = NULL;
1582 const char *base;
1583
1584 assert(original_node);
1585 assert(suffix);
1586 assert(ret_name);
1587 assert(ret_node);
1588
1589 base = strrchr(original_node, '/');
1590 if (!base)
ac1f3ad0
LB
1591 base = original_node;
1592 else
1593 base++;
4623e8e6
LP
1594 if (isempty(base))
1595 return -EINVAL;
1596
1597 name = strjoin(base, suffix);
1598 if (!name)
1599 return -ENOMEM;
1600 if (!filename_is_valid(name))
1601 return -EINVAL;
1602
0d12936d 1603 node = path_join(sym_crypt_get_dir(), name);
4623e8e6
LP
1604 if (!node)
1605 return -ENOMEM;
1606
1cc6c93a
YW
1607 *ret_name = TAKE_PTR(name);
1608 *ret_node = TAKE_PTR(node);
4623e8e6 1609
4623e8e6
LP
1610 return 0;
1611}
1612
18b5886e
LP
1613static int decrypt_partition(
1614 DissectedPartition *m,
1615 const char *passphrase,
1616 DissectImageFlags flags,
1617 DecryptedImage *d) {
1618
1619 _cleanup_free_ char *node = NULL, *name = NULL;
0d12936d 1620 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
18b5886e
LP
1621 int r;
1622
1623 assert(m);
1624 assert(d);
1625
1626 if (!m->found || !m->node || !m->fstype)
1627 return 0;
1628
1629 if (!streq(m->fstype, "crypto_LUKS"))
1630 return 0;
1631
bdd73ac5
ZJS
1632 if (!passphrase)
1633 return -ENOKEY;
1634
0d12936d
LP
1635 r = dlopen_cryptsetup();
1636 if (r < 0)
1637 return r;
1638
4623e8e6
LP
1639 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1640 if (r < 0)
1641 return r;
18b5886e
LP
1642
1643 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1644 return -ENOMEM;
1645
0d12936d 1646 r = sym_crypt_init(&cd, m->node);
18b5886e 1647 if (r < 0)
715cbb81 1648 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 1649
efc3b12f 1650 cryptsetup_enable_logging(cd);
1887032f 1651
0d12936d 1652 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
1653 if (r < 0)
1654 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e 1655
0d12936d
LP
1656 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1657 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1658 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 1659 if (r < 0) {
715cbb81 1660 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 1661 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 1662 }
18b5886e 1663
94344385
LP
1664 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1665 .name = TAKE_PTR(name),
1666 .device = TAKE_PTR(cd),
1667 };
18b5886e 1668
1cc6c93a 1669 m->decrypted_node = TAKE_PTR(node);
18b5886e
LP
1670
1671 return 0;
4623e8e6
LP
1672}
1673
89e62e0b
LP
1674static int verity_can_reuse(
1675 const VeritySettings *verity,
1676 const char *name,
1677 struct crypt_device **ret_cd) {
1678
ac1f3ad0
LB
1679 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1680 _cleanup_free_ char *root_hash_existing = NULL;
0d12936d 1681 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1682 struct crypt_params_verity crypt_params = {};
89e62e0b 1683 size_t root_hash_existing_size;
ac1f3ad0
LB
1684 int r;
1685
89e62e0b
LP
1686 assert(verity);
1687 assert(name);
ac1f3ad0
LB
1688 assert(ret_cd);
1689
0d12936d 1690 r = sym_crypt_init_by_name(&cd, name);
ac1f3ad0
LB
1691 if (r < 0)
1692 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
0d12936d
LP
1693
1694 r = sym_crypt_get_verity_info(cd, &crypt_params);
ac1f3ad0
LB
1695 if (r < 0)
1696 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
0d12936d 1697
89e62e0b
LP
1698 root_hash_existing_size = verity->root_hash_size;
1699 root_hash_existing = malloc0(root_hash_existing_size);
ac1f3ad0
LB
1700 if (!root_hash_existing)
1701 return -ENOMEM;
0d12936d
LP
1702
1703 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
ac1f3ad0
LB
1704 if (r < 0)
1705 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
89e62e0b
LP
1706 if (verity->root_hash_size != root_hash_existing_size ||
1707 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
ac1f3ad0 1708 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
89e62e0b 1709
ac1f3ad0 1710#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
1711 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1712 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
28423d9a 1713 * signing for the new one, and vice versa. */
89e62e0b 1714 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
ac1f3ad0
LB
1715 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1716#endif
1717
1718 *ret_cd = TAKE_PTR(cd);
1719 return 0;
1720}
1721
75db809a 1722static inline char* dm_deferred_remove_clean(char *name) {
ac1f3ad0 1723 if (!name)
75db809a 1724 return NULL;
0d12936d
LP
1725
1726 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
75db809a 1727 return mfree(name);
ac1f3ad0
LB
1728}
1729DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1730
4623e8e6 1731static int verity_partition(
aee36b4e 1732 PartitionDesignator designator,
4623e8e6
LP
1733 DissectedPartition *m,
1734 DissectedPartition *v,
89e62e0b 1735 const VeritySettings *verity,
4623e8e6
LP
1736 DissectImageFlags flags,
1737 DecryptedImage *d) {
1738
0d12936d 1739 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1740 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
89e62e0b 1741 _cleanup_free_ char *node = NULL, *name = NULL;
4623e8e6
LP
1742 int r;
1743
1744 assert(m);
89e62e0b 1745 assert(v || (verity && verity->data_path));
4623e8e6 1746
89e62e0b 1747 if (!verity || !verity->root_hash)
4623e8e6 1748 return 0;
aee36b4e
LP
1749 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
1750 (verity->designator == designator)))
1751 return 0;
4623e8e6
LP
1752
1753 if (!m->found || !m->node || !m->fstype)
1754 return 0;
89e62e0b 1755 if (!verity->data_path) {
e7cbe5cb
LB
1756 if (!v->found || !v->node || !v->fstype)
1757 return 0;
4623e8e6 1758
e7cbe5cb
LB
1759 if (!streq(v->fstype, "DM_verity_hash"))
1760 return 0;
1761 }
4623e8e6 1762
0d12936d
LP
1763 r = dlopen_cryptsetup();
1764 if (r < 0)
1765 return r;
1766
ac1f3ad0
LB
1767 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
1768 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1769 _cleanup_free_ char *root_hash_encoded = NULL;
0d12936d 1770
89e62e0b 1771 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
ac1f3ad0
LB
1772 if (!root_hash_encoded)
1773 return -ENOMEM;
aee36b4e 1774
ac1f3ad0
LB
1775 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
1776 } else
1777 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
4623e8e6
LP
1778 if (r < 0)
1779 return r;
1780
89e62e0b 1781 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
4623e8e6
LP
1782 if (r < 0)
1783 return r;
1784
efc3b12f 1785 cryptsetup_enable_logging(cd);
1887032f 1786
0d12936d 1787 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
4623e8e6 1788 if (r < 0)
294bd454 1789 return r;
4623e8e6 1790
0d12936d 1791 r = sym_crypt_set_data_device(cd, m->node);
4623e8e6 1792 if (r < 0)
294bd454 1793 return r;
4623e8e6 1794
ac1f3ad0
LB
1795 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1796 return -ENOMEM;
1797
1798 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1799 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1800 * retry a few times before giving up. */
1801 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
89e62e0b 1802 if (verity->root_hash_sig) {
c2923fdc 1803#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
89e62e0b
LP
1804 r = sym_crypt_activate_by_signed_key(
1805 cd,
1806 name,
1807 verity->root_hash,
1808 verity->root_hash_size,
1809 verity->root_hash_sig,
1810 verity->root_hash_sig_size,
1811 CRYPT_ACTIVATE_READONLY);
ac1f3ad0 1812#else
22043172
LP
1813 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1814 "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
1815#endif
1816 } else
89e62e0b
LP
1817 r = sym_crypt_activate_by_volume_key(
1818 cd,
1819 name,
1820 verity->root_hash,
1821 verity->root_hash_size,
1822 CRYPT_ACTIVATE_READONLY);
ac1f3ad0
LB
1823 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1824 * There's no way to distinguish this situation from a genuine error due to invalid
2aed63f4 1825 * parameters, so immediately fall back to activating the device with a unique name.
89e62e0b
LP
1826 * Improvements in libcrypsetup can ensure this never happens:
1827 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
ac1f3ad0 1828 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 1829 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10 1830 if (!IN_SET(r,
22043172 1831 0, /* Success */
9ecb5c10 1832 -EEXIST, /* Volume is already open and ready to be used */
22043172
LP
1833 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
1834 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
ac1f3ad0 1835 return r;
9ecb5c10 1836 if (IN_SET(r, -EEXIST, -EBUSY)) {
ac1f3ad0 1837 struct crypt_device *existing_cd = NULL;
c2923fdc 1838
ac1f3ad0
LB
1839 if (!restore_deferred_remove){
1840 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1841 r = dm_deferred_remove_cancel(name);
9ecb5c10
LB
1842 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
1843 if (r < 0 && r != -ENXIO)
ac1f3ad0 1844 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
9ecb5c10
LB
1845 if (r == 0) {
1846 restore_deferred_remove = strdup(name);
1847 if (!restore_deferred_remove)
1848 return -ENOMEM;
1849 }
ac1f3ad0 1850 }
c2923fdc 1851
89e62e0b 1852 r = verity_can_reuse(verity, name, &existing_cd);
ac1f3ad0
LB
1853 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1854 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 1855 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
9ecb5c10 1856 if (!IN_SET(r, 0, -ENODEV, -ENOENT, -EBUSY))
ac1f3ad0
LB
1857 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
1858 if (r == 0) {
c419b6f0
LB
1859 /* devmapper might say that the device exists, but the devlink might not yet have been
1860 * created. Check and wait for the udev event in that case. */
9e3d9067 1861 r = device_wait_for_devlink(node, "block", usec_add(now(CLOCK_MONOTONIC), 100 * USEC_PER_MSEC), NULL);
c419b6f0
LB
1862 /* Fallback to activation with a unique device if it's taking too long */
1863 if (r == -ETIMEDOUT)
1864 break;
1865 if (r < 0)
1866 return r;
1867
ac1f3ad0 1868 if (cd)
0d12936d 1869 sym_crypt_free(cd);
ac1f3ad0
LB
1870 cd = existing_cd;
1871 }
c2923fdc 1872 }
ac1f3ad0
LB
1873 if (r == 0)
1874 break;
ecab4c47
LB
1875
1876 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
1877 (void) usleep(2 * USEC_PER_MSEC);
ac1f3ad0
LB
1878 }
1879
ac1f3ad0
LB
1880 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1881 * Fall back to activating it with a unique device name. */
1882 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
aee36b4e 1883 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
ac1f3ad0
LB
1884
1885 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1886 restore_deferred_remove = mfree(restore_deferred_remove);
4623e8e6 1887
94344385
LP
1888 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
1889 .name = TAKE_PTR(name),
1890 .device = TAKE_PTR(cd),
1891 };
4623e8e6 1892
1cc6c93a 1893 m->decrypted_node = TAKE_PTR(node);
4623e8e6
LP
1894
1895 return 0;
18b5886e
LP
1896}
1897#endif
1898
1899int dissected_image_decrypt(
1900 DissectedImage *m,
1901 const char *passphrase,
89e62e0b 1902 const VeritySettings *verity,
18b5886e
LP
1903 DissectImageFlags flags,
1904 DecryptedImage **ret) {
1905
349cc4a5 1906#if HAVE_LIBCRYPTSETUP
49b5b3b4 1907 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
1908 int r;
1909#endif
1910
1911 assert(m);
89e62e0b 1912 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
18b5886e
LP
1913
1914 /* Returns:
1915 *
1916 * = 0 → There was nothing to decrypt
1917 * > 0 → Decrypted successfully
d1c536f5 1918 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
1919 * -EKEYREJECTED → Passed key was not correct
1920 */
1921
89e62e0b 1922 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
4623e8e6
LP
1923 return -EINVAL;
1924
1925 if (!m->encrypted && !m->verity) {
18b5886e
LP
1926 *ret = NULL;
1927 return 0;
1928 }
1929
349cc4a5 1930#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1931 d = new0(DecryptedImage, 1);
1932 if (!d)
1933 return -ENOMEM;
1934
569a0e42 1935 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 1936 DissectedPartition *p = m->partitions + i;
22043172 1937 PartitionDesignator k;
18b5886e
LP
1938
1939 if (!p->found)
1940 continue;
1941
1942 r = decrypt_partition(p, passphrase, flags, d);
1943 if (r < 0)
1944 return r;
1945
4623e8e6
LP
1946 k = PARTITION_VERITY_OF(i);
1947 if (k >= 0) {
aee36b4e 1948 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
4623e8e6
LP
1949 if (r < 0)
1950 return r;
1951 }
1952
18b5886e
LP
1953 if (!p->decrypted_fstype && p->decrypted_node) {
1954 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 1955 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
1956 return r;
1957 }
1958 }
1959
1cc6c93a 1960 *ret = TAKE_PTR(d);
18b5886e
LP
1961
1962 return 1;
1963#else
1964 return -EOPNOTSUPP;
1965#endif
1966}
1967
1968int dissected_image_decrypt_interactively(
1969 DissectedImage *m,
1970 const char *passphrase,
89e62e0b 1971 const VeritySettings *verity,
18b5886e
LP
1972 DissectImageFlags flags,
1973 DecryptedImage **ret) {
1974
1975 _cleanup_strv_free_erase_ char **z = NULL;
1976 int n = 3, r;
1977
1978 if (passphrase)
1979 n--;
1980
1981 for (;;) {
89e62e0b 1982 r = dissected_image_decrypt(m, passphrase, verity, flags, ret);
18b5886e
LP
1983 if (r >= 0)
1984 return r;
1985 if (r == -EKEYREJECTED)
1986 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
1987 else if (r != -ENOKEY)
1988 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 1989
baaa35ad
ZJS
1990 if (--n < 0)
1991 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1992 "Too many retries.");
18b5886e
LP
1993
1994 z = strv_free(z);
1995
a1c111c2 1996 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
18b5886e
LP
1997 if (r < 0)
1998 return log_error_errno(r, "Failed to query for passphrase: %m");
1999
2000 passphrase = z[0];
2001 }
2002}
2003
18b5886e 2004int decrypted_image_relinquish(DecryptedImage *d) {
18b5886e
LP
2005 assert(d);
2006
67f63ee5
ZJS
2007 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2008 * boolean so that we don't clean it up ourselves either anymore */
18b5886e 2009
349cc4a5 2010#if HAVE_LIBCRYPTSETUP
67f63ee5
ZJS
2011 int r;
2012
2013 for (size_t i = 0; i < d->n_decrypted; i++) {
18b5886e
LP
2014 DecryptedPartition *p = d->decrypted + i;
2015
2016 if (p->relinquished)
2017 continue;
2018
0d12936d 2019 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
2020 if (r < 0)
2021 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
2022
2023 p->relinquished = true;
2024 }
2025#endif
2026
2027 return 0;
2028}
2029
89e62e0b
LP
2030static char *build_auxiliary_path(const char *image, const char *suffix) {
2031 const char *e;
2032 char *n;
2033
2034 assert(image);
2035 assert(suffix);
2036
2037 e = endswith(image, ".raw");
2038 if (!e)
2039 return strjoin(e, suffix);
2040
2041 n = new(char, e - image + strlen(suffix) + 1);
2042 if (!n)
2043 return NULL;
2044
2045 strcpy(mempcpy(n, image, e - image), suffix);
2046 return n;
2047}
2048
2049void verity_settings_done(VeritySettings *v) {
2050 assert(v);
2051
2052 v->root_hash = mfree(v->root_hash);
2053 v->root_hash_size = 0;
2054
2055 v->root_hash_sig = mfree(v->root_hash_sig);
2056 v->root_hash_sig_size = 0;
2057
2058 v->data_path = mfree(v->data_path);
2059}
2060
2061int verity_settings_load(
2062 VeritySettings *verity,
f5ea63a5
LP
2063 const char *image,
2064 const char *root_hash_path,
89e62e0b
LP
2065 const char *root_hash_sig_path) {
2066
2067 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2068 size_t root_hash_size = 0, root_hash_sig_size = 0;
2069 _cleanup_free_ char *verity_data_path = NULL;
aee36b4e 2070 PartitionDesignator designator;
78ebe980
LP
2071 int r;
2072
89e62e0b 2073 assert(verity);
78ebe980 2074 assert(image);
aee36b4e 2075 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
78ebe980 2076
89e62e0b
LP
2077 /* If we are asked to load the root hash for a device node, exit early */
2078 if (is_device_path(image))
78ebe980 2079 return 0;
78ebe980 2080
aee36b4e
LP
2081 designator = verity->designator;
2082
89e62e0b 2083 /* We only fill in what isn't already filled in */
c2923fdc 2084
89e62e0b 2085 if (!verity->root_hash) {
e7cbe5cb 2086 _cleanup_free_ char *text = NULL;
e7cbe5cb 2087
0389f4fa 2088 if (root_hash_path) {
aee36b4e 2089 /* If explicitly specified it takes precedence */
0389f4fa
LB
2090 r = read_one_line_file(root_hash_path, &text);
2091 if (r < 0)
e7cbe5cb 2092 return r;
aee36b4e
LP
2093
2094 if (designator < 0)
2095 designator = PARTITION_ROOT;
0389f4fa 2096 } else {
aee36b4e
LP
2097 /* Otherwise look for xattr and separate file, and first for the data for root and if
2098 * that doesn't exist for /usr */
0389f4fa 2099
aee36b4e
LP
2100 if (designator < 0 || designator == PARTITION_ROOT) {
2101 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
2102 if (r < 0) {
2103 _cleanup_free_ char *p = NULL;
78ebe980 2104
aee36b4e
LP
2105 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2106 return r;
e7cbe5cb 2107
aee36b4e
LP
2108 p = build_auxiliary_path(image, ".roothash");
2109 if (!p)
2110 return -ENOMEM;
2111
2112 r = read_one_line_file(p, &text);
2113 if (r < 0 && r != -ENOENT)
2114 return r;
2115 }
2116
2117 if (text)
2118 designator = PARTITION_ROOT;
2119 }
2120
2121 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2122 /* So in the "roothash" xattr/file name above the "root" of course primarily
2123 * refers to the root of the Verity Merkle tree. But coincidentally it also
2124 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2125 * two distinct concepts called "root". Taking benefit of this happy
2126 * coincidence we call the file with the root hash for the /usr/ file system
2127 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2128 * confusing. We thus drop the reference to the root of the Merkle tree, and
2129 * just indicate which file system it's about. */
2130 r = getxattr_malloc(image, "user.verity.usrhash", &text, true);
2131 if (r < 0) {
2132 _cleanup_free_ char *p = NULL;
2133
2134 if (!IN_SET(r, -ENODATA, -ENOENT) && !ERRNO_IS_NOT_SUPPORTED(r))
2135 return r;
2136
2137 p = build_auxiliary_path(image, ".usrhash");
2138 if (!p)
2139 return -ENOMEM;
2140
2141 r = read_one_line_file(p, &text);
2142 if (r < 0 && r != -ENOENT)
2143 return r;
2144 }
2145
2146 if (text)
2147 designator = PARTITION_USR;
0389f4fa 2148 }
e7cbe5cb
LB
2149 }
2150
2151 if (text) {
89e62e0b 2152 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
e7cbe5cb
LB
2153 if (r < 0)
2154 return r;
89e62e0b 2155 if (root_hash_size < sizeof(sd_id128_t))
e7cbe5cb
LB
2156 return -EINVAL;
2157 }
2158 }
2159
90f98986 2160 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
aee36b4e 2161 if (root_hash_sig_path) {
ae9cf30b 2162 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2163 if (r < 0 && r != -ENOENT)
2164 return r;
2165
2166 if (designator < 0)
2167 designator = PARTITION_ROOT;
2168 } else {
2169 if (designator < 0 || designator == PARTITION_ROOT) {
2170 _cleanup_free_ char *p = NULL;
2171
2172 /* Follow naming convention recommended by the relevant RFC:
2173 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2174 p = build_auxiliary_path(image, ".roothash.p7s");
2175 if (!p)
2176 return -ENOMEM;
89e62e0b 2177
ae9cf30b 2178 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2179 if (r < 0 && r != -ENOENT)
2180 return r;
2181 if (r >= 0)
2182 designator = PARTITION_ROOT;
2183 }
2184
2185 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2186 _cleanup_free_ char *p = NULL;
2187
2188 p = build_auxiliary_path(image, ".usrhash.p7s");
2189 if (!p)
2190 return -ENOMEM;
89e62e0b 2191
ae9cf30b 2192 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
aee36b4e
LP
2193 if (r < 0 && r != -ENOENT)
2194 return r;
2195 if (r >= 0)
2196 designator = PARTITION_USR;
2197 }
89e62e0b
LP
2198 }
2199
aee36b4e 2200 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
89e62e0b
LP
2201 return -EINVAL;
2202 }
2203
2204 if (!verity->data_path) {
2205 _cleanup_free_ char *p = NULL;
2206
2207 p = build_auxiliary_path(image, ".verity");
2208 if (!p)
2209 return -ENOMEM;
2210
2211 if (access(p, F_OK) < 0) {
2212 if (errno != ENOENT)
2213 return -errno;
2214 } else
2215 verity_data_path = TAKE_PTR(p);
2216 }
2217
2218 if (root_hash) {
2219 verity->root_hash = TAKE_PTR(root_hash);
2220 verity->root_hash_size = root_hash_size;
2221 }
2222
2223 if (root_hash_sig) {
2224 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
2225 verity->root_hash_sig_size = root_hash_sig_size;
e7cbe5cb 2226 }
89e62e0b
LP
2227
2228 if (verity_data_path)
2229 verity->data_path = TAKE_PTR(verity_data_path);
78ebe980 2230
aee36b4e
LP
2231 if (verity->designator < 0)
2232 verity->designator = designator;
2233
78ebe980
LP
2234 return 1;
2235}
2236
3b925504
LP
2237int dissected_image_acquire_metadata(DissectedImage *m) {
2238
2239 enum {
2240 META_HOSTNAME,
2241 META_MACHINE_ID,
2242 META_MACHINE_INFO,
2243 META_OS_RELEASE,
7718ac97 2244 META_EXTENSION_RELEASE,
3b925504
LP
2245 _META_MAX,
2246 };
2247
7718ac97
LB
2248 static const char *paths[_META_MAX] = {
2249 [META_HOSTNAME] = "/etc/hostname\0",
2250 [META_MACHINE_ID] = "/etc/machine-id\0",
2251 [META_MACHINE_INFO] = "/etc/machine-info\0",
2252 [META_OS_RELEASE] = ("/etc/os-release\0"
2253 "/usr/lib/os-release\0"),
2254 [META_EXTENSION_RELEASE] = NULL,
3b925504
LP
2255 };
2256
7718ac97 2257 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **extension_release = NULL;
af8219d5 2258 _cleanup_close_pair_ int error_pipe[2] = { -1, -1 };
3b925504
LP
2259 _cleanup_(rmdir_and_freep) char *t = NULL;
2260 _cleanup_(sigkill_waitp) pid_t child = 0;
2261 sd_id128_t machine_id = SD_ID128_NULL;
2262 _cleanup_free_ char *hostname = NULL;
67f63ee5 2263 unsigned n_meta_initialized = 0;
af8219d5
LP
2264 int fds[2 * _META_MAX], r, v;
2265 ssize_t n;
3b925504
LP
2266
2267 BLOCK_SIGNALS(SIGCHLD);
2268
2269 assert(m);
2270
7718ac97
LB
2271 /* As per the os-release spec, if the image is an extension it will have a file
2272 * named after the image name in extension-release.d/ */
2273 if (m->image_name)
2274 paths[META_EXTENSION_RELEASE] = strjoina("/usr/lib/extension-release.d/extension-release.", m->image_name);
2275 else
2276 log_debug("No image name available, will skip extension-release metadata");
2277
2278 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++) {
d9119c00
LP
2279 if (!paths[n_meta_initialized]) {
2280 fds[2*n_meta_initialized] = fds[2*n_meta_initialized+1] = -1;
7718ac97 2281 continue;
d9119c00
LP
2282 }
2283
3b925504
LP
2284 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
2285 r = -errno;
2286 goto finish;
2287 }
7718ac97 2288 }
3b925504
LP
2289
2290 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
2291 if (r < 0)
2292 goto finish;
2293
af8219d5
LP
2294 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
2295 r = -errno;
2296 goto finish;
2297 }
2298
e2047ba9 2299 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 2300 if (r < 0)
3b925504 2301 goto finish;
be39f6ee 2302 if (r == 0) {
af8219d5
LP
2303 error_pipe[0] = safe_close(error_pipe[0]);
2304
03bcb6d4 2305 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
429d4e41 2306 if (r < 0) {
af8219d5
LP
2307 /* Let parent know the error */
2308 (void) write(error_pipe[1], &r, sizeof(r));
2309
429d4e41 2310 log_debug_errno(r, "Failed to mount dissected image: %m");
3b925504 2311 _exit(EXIT_FAILURE);
429d4e41 2312 }
3b925504 2313
67f63ee5 2314 for (unsigned k = 0; k < _META_MAX; k++) {
37e44c3f 2315 _cleanup_close_ int fd = -ENOENT;
3b925504
LP
2316 const char *p;
2317
7718ac97
LB
2318 if (!paths[k])
2319 continue;
2320
3b925504
LP
2321 fds[2*k] = safe_close(fds[2*k]);
2322
2323 NULSTR_FOREACH(p, paths[k]) {
36952d19 2324 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3b925504
LP
2325 if (fd >= 0)
2326 break;
2327 }
36952d19
LP
2328 if (fd < 0) {
2329 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
37e44c3f 2330 fds[2*k+1] = safe_close(fds[2*k+1]);
3b925504 2331 continue;
36952d19 2332 }
3b925504 2333
f5fbe71d 2334 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
af8219d5
LP
2335 if (r < 0) {
2336 (void) write(error_pipe[1], &r, sizeof(r));
3b925504 2337 _exit(EXIT_FAILURE);
af8219d5 2338 }
3b925504
LP
2339
2340 fds[2*k+1] = safe_close(fds[2*k+1]);
2341 }
2342
2343 _exit(EXIT_SUCCESS);
2344 }
2345
af8219d5
LP
2346 error_pipe[1] = safe_close(error_pipe[1]);
2347
67f63ee5 2348 for (unsigned k = 0; k < _META_MAX; k++) {
3b925504
LP
2349 _cleanup_fclose_ FILE *f = NULL;
2350
7718ac97
LB
2351 if (!paths[k])
2352 continue;
2353
3b925504
LP
2354 fds[2*k+1] = safe_close(fds[2*k+1]);
2355
4fa744a3 2356 f = take_fdopen(&fds[2*k], "r");
3b925504
LP
2357 if (!f) {
2358 r = -errno;
2359 goto finish;
2360 }
2361
3b925504
LP
2362 switch (k) {
2363
2364 case META_HOSTNAME:
2365 r = read_etc_hostname_stream(f, &hostname);
2366 if (r < 0)
2367 log_debug_errno(r, "Failed to read /etc/hostname: %m");
2368
2369 break;
2370
2371 case META_MACHINE_ID: {
2372 _cleanup_free_ char *line = NULL;
2373
2374 r = read_line(f, LONG_LINE_MAX, &line);
2375 if (r < 0)
2376 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
2377 else if (r == 33) {
2378 r = sd_id128_from_string(line, &machine_id);
2379 if (r < 0)
2380 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
2381 } else if (r == 0)
2382 log_debug("/etc/machine-id file is empty.");
ab763cb2
HS
2383 else if (streq(line, "uninitialized"))
2384 log_debug("/etc/machine-id file is uninitialized (likely aborted first boot).");
3b925504
LP
2385 else
2386 log_debug("/etc/machine-id has unexpected length %i.", r);
2387
2388 break;
2389 }
2390
2391 case META_MACHINE_INFO:
aa8fbc74 2392 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504
LP
2393 if (r < 0)
2394 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
2395
2396 break;
2397
2398 case META_OS_RELEASE:
aa8fbc74 2399 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504
LP
2400 if (r < 0)
2401 log_debug_errno(r, "Failed to read OS release file: %m");
2402
2403 break;
7718ac97
LB
2404
2405 case META_EXTENSION_RELEASE:
2406 r = load_env_file_pairs(f, "extension-release", &extension_release);
2407 if (r < 0)
2408 log_debug_errno(r, "Failed to read extension release file: %m");
2409
2410 break;
3b925504
LP
2411 }
2412 }
2413
2e87a1fd 2414 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 2415 child = 0;
2e87a1fd 2416 if (r < 0)
af8219d5
LP
2417 return r;
2418
2419 n = read(error_pipe[0], &v, sizeof(v));
2420 if (n < 0)
2421 return -errno;
2422 if (n == sizeof(v))
2423 return v; /* propagate error sent to us from child */
2424 if (n != 0)
2425 return -EIO;
2426
2e87a1fd
LP
2427 if (r != EXIT_SUCCESS)
2428 return -EPROTO;
3b925504
LP
2429
2430 free_and_replace(m->hostname, hostname);
2431 m->machine_id = machine_id;
2432 strv_free_and_replace(m->machine_info, machine_info);
2433 strv_free_and_replace(m->os_release, os_release);
7718ac97 2434 strv_free_and_replace(m->extension_release, extension_release);
3b925504
LP
2435
2436finish:
67f63ee5 2437 for (unsigned k = 0; k < n_meta_initialized; k++)
3b925504
LP
2438 safe_close_pair(fds + 2*k);
2439
2440 return r;
2441}
2442
4526113f
LP
2443int dissect_image_and_warn(
2444 int fd,
2445 const char *name,
89e62e0b 2446 const VeritySettings *verity,
18d73705 2447 const MountOptions *mount_options,
4526113f
LP
2448 DissectImageFlags flags,
2449 DissectedImage **ret) {
2450
2451 _cleanup_free_ char *buffer = NULL;
2452 int r;
2453
2454 if (!name) {
2455 r = fd_get_path(fd, &buffer);
2456 if (r < 0)
2457 return r;
2458
2459 name = buffer;
2460 }
2461
89e62e0b 2462 r = dissect_image(fd, verity, mount_options, flags, ret);
4526113f
LP
2463 switch (r) {
2464
2465 case -EOPNOTSUPP:
2466 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
2467
2468 case -ENOPKG:
2469 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
2470
2471 case -EADDRNOTAVAIL:
2472 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
2473
2474 case -ENOTUNIQ:
2475 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
2476
2477 case -ENXIO:
2478 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
2479
2480 case -EPROTONOSUPPORT:
2481 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
2482
2483 default:
2484 if (r < 0)
2485 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
2486
2487 return r;
2488 }
2489}
2490
569a0e42 2491bool dissected_image_can_do_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
e7cbe5cb
LB
2492 if (image->single_file_system)
2493 return partition_designator == PARTITION_ROOT && image->can_verity;
2494
2495 return PARTITION_VERITY_OF(partition_designator) >= 0;
2496}
2497
569a0e42 2498bool dissected_image_has_verity(const DissectedImage *image, PartitionDesignator partition_designator) {
e7cbe5cb
LB
2499 int k;
2500
2501 if (image->single_file_system)
2502 return partition_designator == PARTITION_ROOT && image->verity;
2503
2504 k = PARTITION_VERITY_OF(partition_designator);
2505 return k >= 0 && image->partitions[k].found;
2506}
2507
18d73705
LB
2508MountOptions* mount_options_free_all(MountOptions *options) {
2509 MountOptions *m;
2510
2511 while ((m = options)) {
2512 LIST_REMOVE(mount_options, options, m);
2513 free(m->options);
2514 free(m);
2515 }
2516
2517 return NULL;
2518}
2519
569a0e42 2520const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
f5215bc8 2521 const MountOptions *m;
18d73705 2522
f5215bc8 2523 LIST_FOREACH(mount_options, m, options)
9ece6444 2524 if (designator == m->partition_designator && !isempty(m->options))
18d73705 2525 return m->options;
6aa05ebd 2526
18d73705
LB
2527 return NULL;
2528}
2529
6aa05ebd
LP
2530int mount_image_privately_interactively(
2531 const char *image,
2532 DissectImageFlags flags,
2533 char **ret_directory,
2534 LoopDevice **ret_loop_device,
2535 DecryptedImage **ret_decrypted_image) {
2536
2537 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
2538 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2539 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2540 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
2541 _cleanup_free_ char *temp = NULL;
2542 int r;
2543
2544 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2545 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2546 * easily. */
2547
2548 assert(image);
2549 assert(ret_directory);
2550 assert(ret_loop_device);
2551 assert(ret_decrypted_image);
2552
2553 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
2554 if (r < 0)
2555 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
2556
2557 r = loop_device_make_by_path(
2558 image,
2559 FLAGS_SET(flags, DISSECT_IMAGE_READ_ONLY) ? O_RDONLY : O_RDWR,
2560 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2561 &d);
2562 if (r < 0)
2563 return log_error_errno(r, "Failed to set up loopback device: %m");
2564
89e62e0b 2565 r = dissect_image_and_warn(d->fd, image, NULL, NULL, flags, &dissected_image);
6aa05ebd
LP
2566 if (r < 0)
2567 return r;
2568
89e62e0b 2569 r = dissected_image_decrypt_interactively(dissected_image, NULL, NULL, flags, &decrypted_image);
6aa05ebd
LP
2570 if (r < 0)
2571 return r;
2572
2573 r = detach_mount_namespace();
2574 if (r < 0)
2575 return log_error_errno(r, "Failed to detach mount namespace: %m");
2576
2577 r = mkdir_p(temp, 0700);
2578 if (r < 0)
2579 return log_error_errno(r, "Failed to create mount point: %m");
2580
2581 created_dir = TAKE_PTR(temp);
2582
af187ab2 2583 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, flags);
6aa05ebd 2584 if (r < 0)
af187ab2 2585 return r;
6aa05ebd
LP
2586
2587 if (decrypted_image) {
2588 r = decrypted_image_relinquish(decrypted_image);
2589 if (r < 0)
2590 return log_error_errno(r, "Failed to relinquish DM devices: %m");
2591 }
2592
2593 loop_device_relinquish(d);
2594
2595 *ret_directory = TAKE_PTR(created_dir);
2596 *ret_loop_device = TAKE_PTR(d);
2597 *ret_decrypted_image = TAKE_PTR(decrypted_image);
2598
2599 return 0;
2600}
2601
8c1be37e
LP
2602static const char *const partition_designator_table[] = {
2603 [PARTITION_ROOT] = "root",
2604 [PARTITION_ROOT_SECONDARY] = "root-secondary",
aee36b4e
LP
2605 [PARTITION_USR] = "usr",
2606 [PARTITION_USR_SECONDARY] = "usr-secondary",
8c1be37e
LP
2607 [PARTITION_HOME] = "home",
2608 [PARTITION_SRV] = "srv",
2609 [PARTITION_ESP] = "esp",
a8c47660 2610 [PARTITION_XBOOTLDR] = "xbootldr",
8c1be37e 2611 [PARTITION_SWAP] = "swap",
4623e8e6
LP
2612 [PARTITION_ROOT_VERITY] = "root-verity",
2613 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
aee36b4e
LP
2614 [PARTITION_USR_VERITY] = "usr-verity",
2615 [PARTITION_USR_SECONDARY_VERITY] = "usr-secondary-verity",
d4dffb85
LP
2616 [PARTITION_TMP] = "tmp",
2617 [PARTITION_VAR] = "var",
8c1be37e
LP
2618};
2619
93f59701
LB
2620int verity_dissect_and_mount(
2621 const char *src,
2622 const char *dest,
2623 const MountOptions *options,
2624 const char *required_host_os_release_id,
2625 const char *required_host_os_release_version_id,
2626 const char *required_host_os_release_sysext_level) {
2627
4beda316
LB
2628 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
2629 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2630 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2631 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2632 DissectImageFlags dissect_image_flags;
2633 int r;
2634
2635 assert(src);
2636 assert(dest);
2637
2638 r = verity_settings_load(&verity, src, NULL, NULL);
2639 if (r < 0)
2640 return log_debug_errno(r, "Failed to load root hash: %m");
2641
2642 dissect_image_flags = verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0;
2643
2644 r = loop_device_make_by_path(
2645 src,
2646 -1,
2647 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
2648 &loop_device);
2649 if (r < 0)
2650 return log_debug_errno(r, "Failed to create loop device for image: %m");
2651
2652 r = dissect_image(
2653 loop_device->fd,
2654 &verity,
2655 options,
2656 dissect_image_flags,
2657 &dissected_image);
2658 /* No partition table? Might be a single-filesystem image, try again */
2659 if (!verity.data_path && r == -ENOPKG)
2660 r = dissect_image(
2661 loop_device->fd,
2662 &verity,
2663 options,
2664 dissect_image_flags|DISSECT_IMAGE_NO_PARTITION_TABLE,
2665 &dissected_image);
2666 if (r < 0)
2667 return log_debug_errno(r, "Failed to dissect image: %m");
2668
2669 r = dissected_image_decrypt(
2670 dissected_image,
2671 NULL,
2672 &verity,
2673 dissect_image_flags,
2674 &decrypted_image);
2675 if (r < 0)
2676 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
2677
2678 r = mkdir_p_label(dest, 0755);
2679 if (r < 0)
2680 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
2681 r = umount_recursive(dest, 0);
2682 if (r < 0)
2683 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
2684
2685 r = dissected_image_mount(dissected_image, dest, UID_INVALID, dissect_image_flags);
2686 if (r < 0)
2687 return log_debug_errno(r, "Failed to mount image: %m");
2688
93f59701
LB
2689 /* If we got os-release values from the caller, then we need to match them with the image's
2690 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
2691 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
2692 * available, or else fallback to VERSION_ID. */
2693 if (required_host_os_release_id &&
2694 (required_host_os_release_version_id || required_host_os_release_sysext_level)) {
2695 _cleanup_strv_free_ char **extension_release = NULL;
2696
2697 r = load_extension_release_pairs(dest, dissected_image->image_name, &extension_release);
2698 if (r < 0)
2699 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
2700
2701 r = extension_release_validate(
2702 dissected_image->image_name,
2703 required_host_os_release_id,
2704 required_host_os_release_version_id,
2705 required_host_os_release_sysext_level,
2706 extension_release);
2707 if (r == 0)
2708 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
2709 if (r < 0)
2710 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
2711 }
2712
4beda316
LB
2713 if (decrypted_image) {
2714 r = decrypted_image_relinquish(decrypted_image);
2715 if (r < 0)
2716 return log_debug_errno(r, "Failed to relinquish decrypted image: %m");
2717 }
2718
2719 loop_device_relinquish(loop_device);
2720
2721 return 0;
2722}
2723
569a0e42 2724DEFINE_STRING_TABLE_LOOKUP(partition_designator, PartitionDesignator);