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