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