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