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