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