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