]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
service: add new RootImageOptions feature
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
8c1be37e 2
10c1b188
LP
3#if HAVE_VALGRIND_MEMCHECK_H
4#include <valgrind/memcheck.h>
5#endif
6
01234e1f
YW
7#include <linux/dm-ioctl.h>
8#include <linux/loop.h>
8c1be37e 9#include <sys/mount.h>
3b925504
LP
10#include <sys/prctl.h>
11#include <sys/wait.h>
8c1be37e 12
3c1f2cee 13#include "sd-device.h"
dccca82b
LP
14#include "sd-id128.h"
15
8c1be37e 16#include "architecture.h"
18b5886e 17#include "ask-password-api.h"
8c1be37e 18#include "blkid-util.h"
18c528e9 19#include "blockdev-util.h"
3b925504 20#include "copy.h"
294bd454 21#include "crypt-util.h"
3b925504 22#include "def.h"
553e15f2 23#include "device-nodes.h"
8437c059 24#include "device-util.h"
8c1be37e 25#include "dissect-image.h"
a709a315 26#include "dm-util.h"
686d13b9 27#include "env-file.h"
18b5886e 28#include "fd-util.h"
78ebe980 29#include "fileio.h"
2eedfd2d 30#include "fs-util.h"
cf32c486 31#include "fsck-util.h"
8c1be37e 32#include "gpt.h"
78ebe980 33#include "hexdecoct.h"
3b925504
LP
34#include "hostname-util.h"
35#include "id128-util.h"
8c1be37e 36#include "mount-util.h"
e4de7287 37#include "mountpoint-util.h"
d8b4d14d 38#include "nulstr-util.h"
d58ad743 39#include "os-util.h"
8c1be37e 40#include "path-util.h"
3b925504
LP
41#include "process-util.h"
42#include "raw-clone.h"
43#include "signal-util.h"
8c1be37e 44#include "stat-util.h"
18b5886e 45#include "stdio-util.h"
8c1be37e
LP
46#include "string-table.h"
47#include "string-util.h"
2eedfd2d 48#include "strv.h"
e4de7287 49#include "tmpfile-util.h"
a8040b6d 50#include "udev-util.h"
2d3a5a73 51#include "user-util.h"
41488e1f 52#include "xattr-util.h"
8c1be37e 53
c34b75a1 54int probe_filesystem(const char *node, char **ret_fstype) {
7cc84b2c 55 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
5238e957 56 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
7cc84b2c
ZJS
57 * different error otherwise. */
58
349cc4a5 59#if HAVE_BLKID
8e766630 60 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
18b5886e
LP
61 const char *fstype;
62 int r;
63
995fa2e5 64 errno = 0;
18b5886e
LP
65 b = blkid_new_probe_from_filename(node);
66 if (!b)
66855de7 67 return errno_or_else(ENOMEM);
18b5886e
LP
68
69 blkid_probe_enable_superblocks(b, 1);
70 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
71
72 errno = 0;
73 r = blkid_do_safeprobe(b);
7cc84b2c
ZJS
74 if (r == 1) {
75 log_debug("No type detected on partition %s", node);
18b5886e
LP
76 goto not_found;
77 }
58dfbfbd
LP
78 if (r == -2)
79 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
80 "Results ambiguous for partition %s", node);
b382db9f 81 if (r != 0)
66855de7 82 return errno_or_else(EIO);
18b5886e
LP
83
84 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
85
86 if (fstype) {
87 char *t;
88
89 t = strdup(fstype);
90 if (!t)
91 return -ENOMEM;
92
93 *ret_fstype = t;
94 return 1;
95 }
96
97not_found:
98 *ret_fstype = NULL;
99 return 0;
d1c536f5
ZJS
100#else
101 return -EOPNOTSUPP;
a75e27eb 102#endif
d1c536f5 103}
18b5886e 104
40c10d3f 105#if HAVE_BLKID
cde942f6
JPRV
106/* Detect RPMB and Boot partitions, which are not listed by blkid.
107 * See https://github.com/systemd/systemd/issues/5806. */
3c1f2cee 108static bool device_is_mmc_special_partition(sd_device *d) {
aae22eb3
LP
109 const char *sysname;
110
f70e7f70
LP
111 assert(d);
112
3c1f2cee
YW
113 if (sd_device_get_sysname(d, &sysname) < 0)
114 return false;
115
116 return startswith(sysname, "mmcblk") &&
0cfa78dd 117 (endswith(sysname, "rpmb") || endswith(sysname, "boot0") || endswith(sysname, "boot1"));
cde942f6
JPRV
118}
119
3c1f2cee 120static bool device_is_block(sd_device *d) {
aae22eb3
LP
121 const char *ss;
122
f70e7f70
LP
123 assert(d);
124
3c1f2cee 125 if (sd_device_get_subsystem(d, &ss) < 0)
aae22eb3
LP
126 return false;
127
128 return streq(ss, "block");
129}
ea887be0
ZJS
130
131static int enumerator_for_parent(sd_device *d, sd_device_enumerator **ret) {
132 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
133 int r;
134
f70e7f70
LP
135 assert(d);
136 assert(ret);
137
ea887be0
ZJS
138 r = sd_device_enumerator_new(&e);
139 if (r < 0)
140 return r;
141
142 r = sd_device_enumerator_allow_uninitialized(e);
143 if (r < 0)
144 return r;
145
146 r = sd_device_enumerator_add_match_parent(e, d);
147 if (r < 0)
148 return r;
149
150 *ret = TAKE_PTR(e);
151 return 0;
152}
153
154/* how many times to wait for the device nodes to appear */
155#define N_DEVICE_NODE_LIST_ATTEMPTS 10
156
157static int wait_for_partitions_to_appear(
158 int fd,
159 sd_device *d,
160 unsigned num_partitions,
052eaf5c 161 DissectImageFlags flags,
ea887be0
ZJS
162 sd_device_enumerator **ret_enumerator) {
163
164 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
165 sd_device *q;
166 unsigned n;
167 int r;
168
f70e7f70
LP
169 assert(fd >= 0);
170 assert(d);
171 assert(ret_enumerator);
172
ea887be0
ZJS
173 r = enumerator_for_parent(d, &e);
174 if (r < 0)
175 return r;
176
177 /* Count the partitions enumerated by the kernel */
178 n = 0;
179 FOREACH_DEVICE(e, q) {
180 if (sd_device_get_devnum(q, NULL) < 0)
181 continue;
182 if (!device_is_block(q))
183 continue;
184 if (device_is_mmc_special_partition(q))
185 continue;
186
052eaf5c 187 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
1b47436e 188 r = device_wait_for_initialization(q, "block", USEC_INFINITY, NULL);
052eaf5c
LP
189 if (r < 0)
190 return r;
191 }
a8040b6d 192
ea887be0
ZJS
193 n++;
194 }
195
196 if (n == num_partitions + 1) {
197 *ret_enumerator = TAKE_PTR(e);
198 return 0; /* success! */
199 }
200 if (n > num_partitions + 1)
201 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
202 "blkid and kernel partition lists do not match.");
203
204 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
205 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
206 * call that waits until probing is complete. */
207
208 for (unsigned j = 0; ; j++) {
209 if (j++ > 20)
210 return -EBUSY;
211
212 if (ioctl(fd, BLKRRPART, 0) >= 0)
213 break;
214 r = -errno;
215 if (r == -EINVAL) {
216 struct loop_info64 info;
217
218 /* If we are running on a loop device that has partition scanning off, return
219 * an explicit recognizable error about this, so that callers can generate a
220 * proper message explaining the situation. */
221
10c1b188
LP
222 if (ioctl(fd, LOOP_GET_STATUS64, &info) >= 0) {
223#if HAVE_VALGRIND_MEMCHECK_H
224 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
225 VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
226#endif
227
228 if ((info.lo_flags & LO_FLAGS_PARTSCAN) == 0)
229 return log_debug_errno(EPROTONOSUPPORT,
230 "Device is a loop device and partition scanning is off!");
ea887be0
ZJS
231 }
232 }
233 if (r != -EBUSY)
234 return r;
235
236 /* If something else has the device open, such as an udev rule, the ioctl will return
237 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
238 * and try again.
239 *
240 * This is really something they should fix in the kernel! */
241 (void) usleep(50 * USEC_PER_MSEC);
242
243 }
244
245 return -EAGAIN; /* no success yet, try again */
246}
247
248static int loop_wait_for_partitions_to_appear(
249 int fd,
250 sd_device *d,
251 unsigned num_partitions,
052eaf5c 252 DissectImageFlags flags,
ea887be0 253 sd_device_enumerator **ret_enumerator) {
a8040b6d 254 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
ea887be0
ZJS
255 int r;
256
f70e7f70
LP
257 assert(fd >= 0);
258 assert(d);
259 assert(ret_enumerator);
260
b887c8b8
ZJS
261 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions);
262
052eaf5c 263 if (!FLAGS_SET(flags, DISSECT_IMAGE_NO_UDEV)) {
1b47436e 264 r = device_wait_for_initialization(d, "block", USEC_INFINITY, &device);
052eaf5c
LP
265 if (r < 0)
266 return r;
267 } else
268 device = sd_device_ref(d);
a8040b6d 269
ea887be0 270 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
052eaf5c 271 r = wait_for_partitions_to_appear(fd, device, num_partitions, flags, ret_enumerator);
ea887be0
ZJS
272 if (r != -EAGAIN)
273 return r;
274 }
275
276 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO),
277 "Kernel partitions dit not appear within %d attempts",
278 N_DEVICE_NODE_LIST_ATTEMPTS);
279}
280
0f7c9a3d
LP
281static void check_partition_flags(
282 const char *node,
283 unsigned long long pflags,
284 unsigned long long supported) {
285
286 assert(node);
287
288 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
289 pflags &= ~(supported | GPT_FLAG_REQUIRED_PARTITION | GPT_FLAG_NO_BLOCK_IO_PROTOCOL | GPT_FLAG_LEGACY_BIOS_BOOTABLE);
290
291 if (pflags == 0)
292 return;
293
294 /* If there are other bits set, then log about it, to make things discoverable */
295 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
296 unsigned long long bit = 1ULL << i;
297 if (!FLAGS_SET(pflags, bit))
298 continue;
299
300 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
301 }
302}
303
40c10d3f 304#endif
aae22eb3 305
4526113f
LP
306int dissect_image(
307 int fd,
308 const void *root_hash,
309 size_t root_hash_size,
e7cbe5cb 310 const char *verity_data,
18d73705 311 const MountOptions *mount_options,
4526113f
LP
312 DissectImageFlags flags,
313 DissectedImage **ret) {
8c1be37e 314
349cc4a5 315#if HAVE_BLKID
4623e8e6 316 sd_id128_t root_uuid = SD_ID128_NULL, verity_uuid = SD_ID128_NULL;
3c1f2cee 317 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
8c1be37e 318 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
3c1f2cee 319 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
8c1be37e 320 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
8e766630 321 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
8c1be37e 322 _cleanup_free_ char *generic_node = NULL;
be30ad41 323 sd_id128_t generic_uuid = SD_ID128_NULL;
9b6deb03 324 const char *pttype = NULL;
8c1be37e
LP
325 blkid_partlist pl;
326 int r, generic_nr;
327 struct stat st;
3c1f2cee 328 sd_device *q;
8c1be37e
LP
329 unsigned i;
330
331 assert(fd >= 0);
332 assert(ret);
4623e8e6 333 assert(root_hash || root_hash_size == 0);
e7cbe5cb 334 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
8c1be37e
LP
335
336 /* Probes a disk image, and returns information about what it found in *ret.
337 *
4623e8e6
LP
338 * Returns -ENOPKG if no suitable partition table or file system could be found.
339 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
340
341 if (root_hash) {
342 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
343 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
344 * 128bit. */
345
346 if (root_hash_size < sizeof(sd_id128_t))
347 return -EINVAL;
348
349 memcpy(&root_uuid, root_hash, sizeof(sd_id128_t));
350 memcpy(&verity_uuid, (const uint8_t*) root_hash + root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
351
352 if (sd_id128_is_null(root_uuid))
353 return -EINVAL;
354 if (sd_id128_is_null(verity_uuid))
355 return -EINVAL;
356 }
8c1be37e
LP
357
358 if (fstat(fd, &st) < 0)
359 return -errno;
360
361 if (!S_ISBLK(st.st_mode))
362 return -ENOTBLK;
363
364 b = blkid_new_probe();
365 if (!b)
366 return -ENOMEM;
367
368 errno = 0;
369 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f 370 if (r != 0)
66855de7 371 return errno_or_else(ENOMEM);
8c1be37e 372
9b6deb03
LP
373 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
374 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
375 blkid_probe_enable_superblocks(b, 1);
376 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
377 }
378
8c1be37e
LP
379 blkid_probe_enable_partitions(b, 1);
380 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
381
382 errno = 0;
383 r = blkid_do_safeprobe(b);
59ba6d0c
LP
384 if (IN_SET(r, -2, 1))
385 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
b382db9f 386 if (r != 0)
66855de7 387 return errno_or_else(EIO);
8c1be37e
LP
388
389 m = new0(DissectedImage, 1);
390 if (!m)
391 return -ENOMEM;
392
b887c8b8
ZJS
393 r = sd_device_new_from_devnum(&d, 'b', st.st_rdev);
394 if (r < 0)
395 return r;
396
e7cbe5cb
LB
397 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
398 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) ||
399 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
9b6deb03 400 const char *usage = NULL;
8c1be37e 401
9b6deb03
LP
402 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
403 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
18d73705
LB
404 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
405 const char *fstype = NULL, *options = NULL;
8c1be37e 406
9b6deb03
LP
407 /* OK, we have found a file system, that's our root partition then. */
408 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 409
9b6deb03
LP
410 if (fstype) {
411 t = strdup(fstype);
412 if (!t)
413 return -ENOMEM;
414 }
415
54b22b26
LP
416 r = device_path_make_major_minor(st.st_mode, st.st_rdev, &n);
417 if (r < 0)
418 return r;
8c1be37e 419
e7cbe5cb
LB
420 m->single_file_system = true;
421 m->verity = root_hash && verity_data;
422 m->can_verity = !!verity_data;
423
18d73705
LB
424 options = mount_options_from_part(mount_options, 0);
425 if (options) {
426 o = strdup(options);
427 if (!o)
428 return -ENOMEM;
429 }
430
9b6deb03
LP
431 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
432 .found = true,
e7cbe5cb 433 .rw = !m->verity,
9b6deb03
LP
434 .partno = -1,
435 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a
YW
436 .fstype = TAKE_PTR(t),
437 .node = TAKE_PTR(n),
18d73705 438 .mount_options = TAKE_PTR(o),
9b6deb03 439 };
8c1be37e 440
4db1879a 441 m->encrypted = streq_ptr(fstype, "crypto_LUKS");
18b5886e 442
b1806441
LB
443 /* Even on a single partition we need to wait for udev to create the
444 * /dev/block/X:Y symlink to /dev/loopZ */
445 r = loop_wait_for_partitions_to_appear(fd, d, 0, flags, &e);
446 if (r < 0)
447 return r;
1cc6c93a 448 *ret = TAKE_PTR(m);
8c1be37e 449
9b6deb03
LP
450 return 0;
451 }
8c1be37e
LP
452 }
453
454 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
455 if (!pttype)
456 return -ENOPKG;
457
458 is_gpt = streq_ptr(pttype, "gpt");
459 is_mbr = streq_ptr(pttype, "dos");
460
9b6deb03 461 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
462 return -ENOPKG;
463
464 errno = 0;
465 pl = blkid_probe_get_partitions(b);
b382db9f 466 if (!pl)
66855de7 467 return errno_or_else(ENOMEM);
8c1be37e 468
052eaf5c 469 r = loop_wait_for_partitions_to_appear(fd, d, blkid_partlist_numof_partitions(pl), flags, &e);
ea887be0
ZJS
470 if (r < 0)
471 return r;
8c1be37e 472
8437c059 473 FOREACH_DEVICE(e, q) {
9b6deb03 474 unsigned long long pflags;
8c1be37e 475 blkid_partition pp;
cde942f6 476 const char *node;
8c1be37e
LP
477 dev_t qn;
478 int nr;
479
3c1f2cee
YW
480 r = sd_device_get_devnum(q, &qn);
481 if (r < 0)
8c1be37e
LP
482 continue;
483
484 if (st.st_rdev == qn)
485 continue;
486
aae22eb3
LP
487 if (!device_is_block(q))
488 continue;
489
cde942f6 490 if (device_is_mmc_special_partition(q))
7be1420f
LP
491 continue;
492
3c1f2cee
YW
493 r = sd_device_get_devname(q, &node);
494 if (r < 0)
8c1be37e
LP
495 continue;
496
497 pp = blkid_partlist_devno_to_partition(pl, qn);
498 if (!pp)
499 continue;
500
9b6deb03 501 pflags = blkid_partition_get_flags(pp);
8c1be37e
LP
502
503 nr = blkid_partition_get_partno(pp);
504 if (nr < 0)
505 continue;
506
507 if (is_gpt) {
508 int designator = _PARTITION_DESIGNATOR_INVALID, architecture = _ARCHITECTURE_INVALID;
4623e8e6
LP
509 const char *stype, *sid, *fstype = NULL;
510 sd_id128_t type_id, id;
8c1be37e
LP
511 bool rw = true;
512
4623e8e6
LP
513 sid = blkid_partition_get_uuid(pp);
514 if (!sid)
515 continue;
516 if (sd_id128_from_string(sid, &id) < 0)
517 continue;
518
8c1be37e
LP
519 stype = blkid_partition_get_type_string(pp);
520 if (!stype)
521 continue;
8c1be37e
LP
522 if (sd_id128_from_string(stype, &type_id) < 0)
523 continue;
524
525 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347 526
0f7c9a3d
LP
527 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
528
a48dd347
LP
529 if (pflags & GPT_FLAG_NO_AUTO)
530 continue;
531
8c1be37e 532 designator = PARTITION_HOME;
9b6deb03 533 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 534 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347 535
0f7c9a3d
LP
536 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
537
a48dd347
LP
538 if (pflags & GPT_FLAG_NO_AUTO)
539 continue;
540
8c1be37e 541 designator = PARTITION_SRV;
9b6deb03 542 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 543 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347
LP
544
545 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
546 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
547 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
548
549 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
550 continue;
551
8c1be37e
LP
552 designator = PARTITION_ESP;
553 fstype = "vfat";
a8c47660
LP
554
555 } else if (sd_id128_equal(type_id, GPT_XBOOTLDR)) {
556
0f7c9a3d
LP
557 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
558
a8c47660
LP
559 if (pflags & GPT_FLAG_NO_AUTO)
560 continue;
561
562 designator = PARTITION_XBOOTLDR;
563 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
564 }
565#ifdef GPT_ROOT_NATIVE
566 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 567
0f7c9a3d
LP
568 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
569
a48dd347
LP
570 if (pflags & GPT_FLAG_NO_AUTO)
571 continue;
572
4623e8e6
LP
573 /* If a root ID is specified, ignore everything but the root id */
574 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
575 continue;
576
8c1be37e
LP
577 designator = PARTITION_ROOT;
578 architecture = native_architecture();
9b6deb03 579 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 580 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 581
0f7c9a3d
LP
582 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
583
a48dd347
LP
584 if (pflags & GPT_FLAG_NO_AUTO)
585 continue;
586
4623e8e6
LP
587 m->can_verity = true;
588
589 /* Ignore verity unless a root hash is specified */
590 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
591 continue;
592
593 designator = PARTITION_ROOT_VERITY;
594 fstype = "DM_verity_hash";
595 architecture = native_architecture();
596 rw = false;
597 }
598#endif
8c1be37e
LP
599#ifdef GPT_ROOT_SECONDARY
600 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 601
0f7c9a3d
LP
602 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
603
a48dd347
LP
604 if (pflags & GPT_FLAG_NO_AUTO)
605 continue;
606
4623e8e6
LP
607 /* If a root ID is specified, ignore everything but the root id */
608 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
609 continue;
610
8c1be37e
LP
611 designator = PARTITION_ROOT_SECONDARY;
612 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 613 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 614 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347 615
0f7c9a3d
LP
616 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
617
a48dd347
LP
618 if (pflags & GPT_FLAG_NO_AUTO)
619 continue;
620
4623e8e6
LP
621 m->can_verity = true;
622
623 /* Ignore verity unless root has is specified */
624 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
625 continue;
626
627 designator = PARTITION_ROOT_SECONDARY_VERITY;
628 fstype = "DM_verity_hash";
629 architecture = SECONDARY_ARCHITECTURE;
630 rw = false;
631 }
8c1be37e
LP
632#endif
633 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347 634
0f7c9a3d
LP
635 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO);
636
a48dd347
LP
637 if (pflags & GPT_FLAG_NO_AUTO)
638 continue;
639
8c1be37e
LP
640 designator = PARTITION_SWAP;
641 fstype = "swap";
642 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
643
0f7c9a3d
LP
644 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
645
a48dd347
LP
646 if (pflags & GPT_FLAG_NO_AUTO)
647 continue;
648
8c1be37e
LP
649 if (generic_node)
650 multiple_generic = true;
651 else {
652 generic_nr = nr;
9b6deb03 653 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
be30ad41 654 generic_uuid = id;
8c1be37e
LP
655 generic_node = strdup(node);
656 if (!generic_node)
657 return -ENOMEM;
658 }
d4dffb85
LP
659
660 } else if (sd_id128_equal(type_id, GPT_TMP)) {
661
0f7c9a3d
LP
662 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
663
d4dffb85
LP
664 if (pflags & GPT_FLAG_NO_AUTO)
665 continue;
666
667 designator = PARTITION_TMP;
668 rw = !(pflags & GPT_FLAG_READ_ONLY);
669
670 } else if (sd_id128_equal(type_id, GPT_VAR)) {
671
0f7c9a3d
LP
672 check_partition_flags(node, pflags, GPT_FLAG_NO_AUTO|GPT_FLAG_READ_ONLY);
673
d4dffb85
LP
674 if (pflags & GPT_FLAG_NO_AUTO)
675 continue;
676
677 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
678 sd_id128_t var_uuid;
679
680 /* For /var we insist that the uuid of the partition matches the
681 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
682 * ID. Why? Unlike the other partitions /var is inherently
683 * installation specific, hence we need to be careful not to mount it
684 * in the wrong installation. By hashing the partition UUID from
685 * /etc/machine-id we can securely bind the partition to the
686 * installation. */
687
688 r = sd_id128_get_machine_app_specific(GPT_VAR, &var_uuid);
689 if (r < 0)
690 return r;
691
692 if (!sd_id128_equal(var_uuid, id)) {
693 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
694 continue;
695 }
696 }
697
698 designator = PARTITION_VAR;
699 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e
LP
700 }
701
702 if (designator != _PARTITION_DESIGNATOR_INVALID) {
18d73705
LB
703 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
704 const char *options = NULL;
8c1be37e
LP
705
706 /* First one wins */
707 if (m->partitions[designator].found)
708 continue;
709
710 if (fstype) {
711 t = strdup(fstype);
712 if (!t)
713 return -ENOMEM;
714 }
715
716 n = strdup(node);
717 if (!n)
718 return -ENOMEM;
719
18d73705
LB
720 options = mount_options_from_part(mount_options, nr);
721 if (options) {
722 o = strdup(options);
723 if (!o)
724 return -ENOMEM;
725 }
726
8c1be37e
LP
727 m->partitions[designator] = (DissectedPartition) {
728 .found = true,
729 .partno = nr,
730 .rw = rw,
731 .architecture = architecture,
1cc6c93a
YW
732 .node = TAKE_PTR(n),
733 .fstype = TAKE_PTR(t),
be30ad41 734 .uuid = id,
18d73705 735 .mount_options = TAKE_PTR(o),
8c1be37e 736 };
8c1be37e
LP
737 }
738
739 } else if (is_mbr) {
740
a8c47660 741 switch (blkid_partition_get_type(pp)) {
8c1be37e 742
a8c47660
LP
743 case 0x83: /* Linux partition */
744
745 if (pflags != 0x80) /* Bootable flag */
746 continue;
8c1be37e 747
a8c47660
LP
748 if (generic_node)
749 multiple_generic = true;
750 else {
751 generic_nr = nr;
752 generic_rw = true;
753 generic_node = strdup(node);
754 if (!generic_node)
755 return -ENOMEM;
756 }
757
758 break;
759
760 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
18d73705 761 _cleanup_free_ char *n = NULL, *o = NULL;
a8c47660 762 sd_id128_t id = SD_ID128_NULL;
18d73705 763 const char *sid, *options = NULL;
a8c47660
LP
764
765 /* First one wins */
766 if (m->partitions[PARTITION_XBOOTLDR].found)
767 continue;
768
769 sid = blkid_partition_get_uuid(pp);
770 if (sid)
771 (void) sd_id128_from_string(sid, &id);
772
773 n = strdup(node);
774 if (!n)
8c1be37e 775 return -ENOMEM;
a8c47660 776
18d73705
LB
777 options = mount_options_from_part(mount_options, nr);
778 if (options) {
779 o = strdup(options);
780 if (!o)
781 return -ENOMEM;
782 }
783
a8c47660
LP
784 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
785 .found = true,
786 .partno = nr,
787 .rw = true,
788 .architecture = _ARCHITECTURE_INVALID,
789 .node = TAKE_PTR(n),
790 .uuid = id,
18d73705 791 .mount_options = TAKE_PTR(o),
a8c47660
LP
792 };
793
794 break;
795 }}
8c1be37e
LP
796 }
797 }
798
799 if (!m->partitions[PARTITION_ROOT].found) {
800 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
801 * either, then check if there's a single generic one, and use that. */
802
4623e8e6 803 if (m->partitions[PARTITION_ROOT_VERITY].found)
e0f9e7bd 804 return -EADDRNOTAVAIL;
4623e8e6 805
8c1be37e
LP
806 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
807 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
808 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
4623e8e6
LP
809
810 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
811 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
812
e0f9e7bd 813 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
18d73705
LB
814 _cleanup_free_ char *o = NULL;
815 const char *options = NULL;
e0f9e7bd
LP
816
817 /* If the root has was set, then we won't fallback to a generic node, because the root hash
818 * decides */
819 if (root_hash)
820 return -EADDRNOTAVAIL;
8c1be37e 821
e0f9e7bd
LP
822 /* If we didn't find a generic node, then we can't fix this up either */
823 if (!generic_node)
824 return -ENXIO;
825
826 /* If we didn't find a properly marked root partition, but we did find a single suitable
827 * generic Linux partition, then use this as root partition, if the caller asked for it. */
8c1be37e
LP
828 if (multiple_generic)
829 return -ENOTUNIQ;
830
18d73705
LB
831 options = mount_options_from_part(mount_options, generic_nr);
832 if (options) {
833 o = strdup(options);
834 if (!o)
835 return -ENOMEM;
836 }
837
8c1be37e
LP
838 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
839 .found = true,
840 .rw = generic_rw,
841 .partno = generic_nr,
842 .architecture = _ARCHITECTURE_INVALID,
1cc6c93a 843 .node = TAKE_PTR(generic_node),
be30ad41 844 .uuid = generic_uuid,
18d73705 845 .mount_options = TAKE_PTR(o),
8c1be37e 846 };
e0f9e7bd 847 }
8c1be37e
LP
848 }
849
4623e8e6 850 if (root_hash) {
e0f9e7bd 851 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
4623e8e6
LP
852 return -EADDRNOTAVAIL;
853
854 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
855 * (which would be weird, after all the root hash should only be assigned to one pair of
856 * partitions... */
857 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
858 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
859
860 /* If we found a verity setup, then the root partition is necessarily read-only. */
861 m->partitions[PARTITION_ROOT].rw = false;
862
863 m->verity = true;
864 }
865
18b5886e
LP
866 blkid_free_probe(b);
867 b = NULL;
868
8c1be37e
LP
869 /* Fill in file system types if we don't know them yet. */
870 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 871 DissectedPartition *p = m->partitions + i;
8c1be37e 872
18b5886e 873 if (!p->found)
8c1be37e
LP
874 continue;
875
18b5886e
LP
876 if (!p->fstype && p->node) {
877 r = probe_filesystem(p->node, &p->fstype);
7cc84b2c 878 if (r < 0 && r != -EUCLEAN)
18b5886e 879 return r;
8c1be37e
LP
880 }
881
18b5886e
LP
882 if (streq_ptr(p->fstype, "crypto_LUKS"))
883 m->encrypted = true;
896f937f
LP
884
885 if (p->fstype && fstype_is_ro(p->fstype))
886 p->rw = false;
8c1be37e
LP
887 }
888
1cc6c93a 889 *ret = TAKE_PTR(m);
8c1be37e
LP
890
891 return 0;
892#else
893 return -EOPNOTSUPP;
894#endif
895}
896
897DissectedImage* dissected_image_unref(DissectedImage *m) {
898 unsigned i;
899
900 if (!m)
901 return NULL;
902
903 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
904 free(m->partitions[i].fstype);
905 free(m->partitions[i].node);
18b5886e
LP
906 free(m->partitions[i].decrypted_fstype);
907 free(m->partitions[i].decrypted_node);
18d73705 908 free(m->partitions[i].mount_options);
8c1be37e
LP
909 }
910
3b925504
LP
911 free(m->hostname);
912 strv_free(m->machine_info);
913 strv_free(m->os_release);
914
5fecf46d 915 return mfree(m);
8c1be37e
LP
916}
917
18b5886e 918static int is_loop_device(const char *path) {
553e15f2 919 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
18b5886e
LP
920 struct stat st;
921
922 assert(path);
923
924 if (stat(path, &st) < 0)
925 return -errno;
926
927 if (!S_ISBLK(st.st_mode))
928 return -ENOTBLK;
929
553e15f2 930 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
18b5886e
LP
931 if (access(s, F_OK) < 0) {
932 if (errno != ENOENT)
933 return -errno;
934
935 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
553e15f2 936 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
18b5886e
LP
937 if (access(s, F_OK) < 0)
938 return errno == ENOENT ? false : -errno;
939 }
940
941 return true;
942}
943
cf32c486
LP
944static int run_fsck(const char *node, const char *fstype) {
945 int r, exit_status;
946 pid_t pid;
947
948 assert(node);
949 assert(fstype);
950
951 r = fsck_exists(fstype);
952 if (r < 0) {
953 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
954 return 0;
955 }
956 if (r == 0) {
957 log_debug("Not checking partition %s, as fsck for %s does not exist.", node, fstype);
958 return 0;
959 }
960
961 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_NULL_STDIO, &pid);
962 if (r < 0)
963 return log_debug_errno(r, "Failed to fork off fsck: %m");
964 if (r == 0) {
965 /* Child */
966 execl("/sbin/fsck", "/sbin/fsck", "-aT", node, NULL);
967 log_debug_errno(errno, "Failed to execl() fsck: %m");
968 _exit(FSCK_OPERATIONAL_ERROR);
969 }
970
971 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
972 if (exit_status < 0)
973 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
974
975 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
976 log_debug("fsck failed with exit status %i.", exit_status);
977
978 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
979 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
980
981 log_debug("Ignoring fsck error.");
982 }
983
984 return 0;
985}
986
18b5886e
LP
987static int mount_partition(
988 DissectedPartition *m,
989 const char *where,
990 const char *directory,
2d3a5a73 991 uid_t uid_shift,
18b5886e
LP
992 DissectImageFlags flags) {
993
2d3a5a73
LP
994 _cleanup_free_ char *chased = NULL, *options = NULL;
995 const char *p, *node, *fstype;
8c1be37e 996 bool rw;
2eedfd2d 997 int r;
8c1be37e
LP
998
999 assert(m);
1000 assert(where);
1001
18b5886e
LP
1002 node = m->decrypted_node ?: m->node;
1003 fstype = m->decrypted_fstype ?: m->fstype;
1004
1005 if (!m->found || !node || !fstype)
8c1be37e
LP
1006 return 0;
1007
18b5886e
LP
1008 /* Stacked encryption? Yuck */
1009 if (streq_ptr(fstype, "crypto_LUKS"))
1010 return -ELOOP;
1011
1012 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
8c1be37e 1013
cf32c486
LP
1014 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1015 r = run_fsck(node, fstype);
1016 if (r < 0)
1017 return r;
1018 }
1019
2eedfd2d 1020 if (directory) {
a5648b80 1021 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2eedfd2d
LP
1022 if (r < 0)
1023 return r;
1024
1025 p = chased;
1026 } else
8c1be37e
LP
1027 p = where;
1028
18b5886e 1029 /* If requested, turn on discard support. */
154d2269 1030 if (fstype_can_discard(fstype) &&
18b5886e 1031 ((flags & DISSECT_IMAGE_DISCARD) ||
2d3a5a73
LP
1032 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node)))) {
1033 options = strdup("discard");
1034 if (!options)
1035 return -ENOMEM;
1036 }
1037
1038 if (uid_is_valid(uid_shift) && uid_shift != 0 && fstype_can_uid_gid(fstype)) {
1039 _cleanup_free_ char *uid_option = NULL;
1040
1041 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1042 return -ENOMEM;
1043
1044 if (!strextend_with_separator(&options, ",", uid_option, NULL))
1045 return -ENOMEM;
1046 }
8c1be37e 1047
18d73705
LB
1048 if (!isempty(m->mount_options))
1049 if (!strextend_with_separator(&options, ",", m->mount_options, NULL))
1050 return -ENOMEM;
1051
d9223c07
LP
1052 r = mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
1053 if (r < 0)
1054 return r;
1055
1056 return 1;
8c1be37e
LP
1057}
1058
2d3a5a73 1059int dissected_image_mount(DissectedImage *m, const char *where, uid_t uid_shift, DissectImageFlags flags) {
d9223c07 1060 int r, boot_mounted;
8c1be37e
LP
1061
1062 assert(m);
1063 assert(where);
1064
1065 if (!m->partitions[PARTITION_ROOT].found)
1066 return -ENXIO;
1067
2d3a5a73
LP
1068 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1069 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, uid_shift, flags);
1070 if (r < 0)
1071 return r;
03bcb6d4
LP
1072
1073 if (flags & DISSECT_IMAGE_VALIDATE_OS) {
1074 r = path_is_os_tree(where);
1075 if (r < 0)
1076 return r;
1077 if (r == 0)
1078 return -EMEDIUMTYPE;
1079 }
2d3a5a73
LP
1080 }
1081
705727fd 1082 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2d3a5a73 1083 return 0;
8c1be37e 1084
2d3a5a73 1085 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", uid_shift, flags);
8c1be37e
LP
1086 if (r < 0)
1087 return r;
1088
2d3a5a73 1089 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", uid_shift, flags);
8c1be37e
LP
1090 if (r < 0)
1091 return r;
1092
d4dffb85
LP
1093 r = mount_partition(m->partitions + PARTITION_VAR, where, "/var", uid_shift, flags);
1094 if (r < 0)
1095 return r;
1096
1097 r = mount_partition(m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, flags);
1098 if (r < 0)
1099 return r;
1100
d9223c07
LP
1101 boot_mounted = mount_partition(m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, flags);
1102 if (boot_mounted < 0)
1103 return boot_mounted;
1104
8c1be37e 1105 if (m->partitions[PARTITION_ESP].found) {
d9223c07
LP
1106 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1107 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
8c1be37e 1108
a5648b80 1109 r = chase_symlinks("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
d9223c07
LP
1110 if (r >= 0) {
1111 r = mount_partition(m->partitions + PARTITION_ESP, where, "/efi", uid_shift, flags);
1112 if (r < 0)
1113 return r;
8c1be37e 1114
d9223c07 1115 } else if (boot_mounted <= 0) {
2eedfd2d
LP
1116 _cleanup_free_ char *p = NULL;
1117
a5648b80 1118 r = chase_symlinks("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
d9223c07
LP
1119 if (r >= 0 && dir_is_empty(p) > 0) {
1120 r = mount_partition(m->partitions + PARTITION_ESP, where, "/boot", uid_shift, flags);
2eedfd2d
LP
1121 if (r < 0)
1122 return r;
1123 }
8c1be37e
LP
1124 }
1125 }
1126
1127 return 0;
1128}
1129
349cc4a5 1130#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1131typedef struct DecryptedPartition {
1132 struct crypt_device *device;
1133 char *name;
1134 bool relinquished;
1135} DecryptedPartition;
1136
1137struct DecryptedImage {
1138 DecryptedPartition *decrypted;
1139 size_t n_decrypted;
1140 size_t n_allocated;
1141};
1142#endif
1143
1144DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
349cc4a5 1145#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1146 size_t i;
1147 int r;
1148
1149 if (!d)
1150 return NULL;
1151
1152 for (i = 0; i < d->n_decrypted; i++) {
1153 DecryptedPartition *p = d->decrypted + i;
1154
1155 if (p->device && p->name && !p->relinquished) {
1156 r = crypt_deactivate(p->device, p->name);
1157 if (r < 0)
1158 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
1159 }
1160
1161 if (p->device)
1162 crypt_free(p->device);
1163 free(p->name);
1164 }
1165
1166 free(d);
1167#endif
1168 return NULL;
1169}
1170
349cc4a5 1171#if HAVE_LIBCRYPTSETUP
4623e8e6
LP
1172
1173static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
1174 _cleanup_free_ char *name = NULL, *node = NULL;
1175 const char *base;
1176
1177 assert(original_node);
1178 assert(suffix);
1179 assert(ret_name);
1180 assert(ret_node);
1181
1182 base = strrchr(original_node, '/');
1183 if (!base)
ac1f3ad0
LB
1184 base = original_node;
1185 else
1186 base++;
4623e8e6
LP
1187 if (isempty(base))
1188 return -EINVAL;
1189
1190 name = strjoin(base, suffix);
1191 if (!name)
1192 return -ENOMEM;
1193 if (!filename_is_valid(name))
1194 return -EINVAL;
1195
657ee2d8 1196 node = path_join(crypt_get_dir(), name);
4623e8e6
LP
1197 if (!node)
1198 return -ENOMEM;
1199
1cc6c93a
YW
1200 *ret_name = TAKE_PTR(name);
1201 *ret_node = TAKE_PTR(node);
4623e8e6 1202
4623e8e6
LP
1203 return 0;
1204}
1205
18b5886e
LP
1206static int decrypt_partition(
1207 DissectedPartition *m,
1208 const char *passphrase,
1209 DissectImageFlags flags,
1210 DecryptedImage *d) {
1211
1212 _cleanup_free_ char *node = NULL, *name = NULL;
294bd454 1213 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
18b5886e
LP
1214 int r;
1215
1216 assert(m);
1217 assert(d);
1218
1219 if (!m->found || !m->node || !m->fstype)
1220 return 0;
1221
1222 if (!streq(m->fstype, "crypto_LUKS"))
1223 return 0;
1224
bdd73ac5
ZJS
1225 if (!passphrase)
1226 return -ENOKEY;
1227
4623e8e6
LP
1228 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
1229 if (r < 0)
1230 return r;
18b5886e
LP
1231
1232 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1233 return -ENOMEM;
1234
1235 r = crypt_init(&cd, m->node);
1236 if (r < 0)
715cbb81 1237 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
18b5886e 1238
1887032f
TM
1239 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
1240
dd59868b 1241 r = crypt_load(cd, CRYPT_LUKS, NULL);
294bd454
ZJS
1242 if (r < 0)
1243 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
18b5886e
LP
1244
1245 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
1246 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
1247 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
294bd454 1248 if (r < 0) {
715cbb81 1249 log_debug_errno(r, "Failed to activate LUKS device: %m");
294bd454 1250 return r == -EPERM ? -EKEYREJECTED : r;
18b5886e 1251 }
18b5886e 1252
1cc6c93a
YW
1253 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1254 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
18b5886e
LP
1255 d->n_decrypted++;
1256
1cc6c93a 1257 m->decrypted_node = TAKE_PTR(node);
18b5886e
LP
1258
1259 return 0;
4623e8e6
LP
1260}
1261
ac1f3ad0
LB
1262static int verity_can_reuse(const void *root_hash, size_t root_hash_size, bool has_sig, const char *name, struct crypt_device **ret_cd) {
1263 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1264 _cleanup_free_ char *root_hash_existing = NULL;
1265 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
1266 struct crypt_params_verity crypt_params = {};
1267 size_t root_hash_existing_size = root_hash_size;
1268 int r;
1269
1270 assert(ret_cd);
1271
1272 r = crypt_init_by_name(&cd, name);
1273 if (r < 0)
1274 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
1275 r = crypt_get_verity_info(cd, &crypt_params);
1276 if (r < 0)
1277 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
1278 root_hash_existing = malloc0(root_hash_size);
1279 if (!root_hash_existing)
1280 return -ENOMEM;
1281 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
1282 if (r < 0)
1283 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
1284 if (root_hash_size != root_hash_existing_size || memcmp(root_hash_existing, root_hash, root_hash_size) != 0)
1285 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
1286#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1287 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount
1288 * used the same settings, so that a previous unsigned mount will not be reused if the user
1289 * asks to use signing for the new one, and viceversa. */
1290 if (has_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
1291 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
1292#endif
1293
1294 *ret_cd = TAKE_PTR(cd);
1295 return 0;
1296}
1297
1298static inline void dm_deferred_remove_clean(char *name) {
1299 if (!name)
1300 return;
1301 (void) crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
1302 free(name);
1303}
1304DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
1305
4623e8e6
LP
1306static int verity_partition(
1307 DissectedPartition *m,
1308 DissectedPartition *v,
1309 const void *root_hash,
1310 size_t root_hash_size,
e7cbe5cb 1311 const char *verity_data,
c2923fdc
LB
1312 const char *root_hash_sig_path,
1313 const void *root_hash_sig,
1314 size_t root_hash_sig_size,
4623e8e6
LP
1315 DissectImageFlags flags,
1316 DecryptedImage *d) {
1317
ac1f3ad0 1318 _cleanup_free_ char *node = NULL, *name = NULL, *hash_sig_from_file = NULL;
294bd454 1319 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
ac1f3ad0 1320 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
4623e8e6
LP
1321 int r;
1322
1323 assert(m);
e7cbe5cb 1324 assert(v || verity_data);
4623e8e6
LP
1325
1326 if (!root_hash)
1327 return 0;
1328
1329 if (!m->found || !m->node || !m->fstype)
1330 return 0;
e7cbe5cb
LB
1331 if (!verity_data) {
1332 if (!v->found || !v->node || !v->fstype)
1333 return 0;
4623e8e6 1334
e7cbe5cb
LB
1335 if (!streq(v->fstype, "DM_verity_hash"))
1336 return 0;
1337 }
4623e8e6 1338
ac1f3ad0
LB
1339 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
1340 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1341 _cleanup_free_ char *root_hash_encoded = NULL;
1342 root_hash_encoded = hexmem(root_hash, root_hash_size);
1343 if (!root_hash_encoded)
1344 return -ENOMEM;
1345 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
1346 } else
1347 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
4623e8e6
LP
1348 if (r < 0)
1349 return r;
1350
ac1f3ad0
LB
1351 if (!root_hash_sig && root_hash_sig_path) {
1352 r = read_full_file_full(AT_FDCWD, root_hash_sig_path, 0, &hash_sig_from_file, &root_hash_sig_size);
1353 if (r < 0)
1354 return r;
1355 }
4623e8e6 1356
e7cbe5cb 1357 r = crypt_init(&cd, verity_data ?: v->node);
4623e8e6
LP
1358 if (r < 0)
1359 return r;
1360
1887032f
TM
1361 crypt_set_log_callback(cd, cryptsetup_log_glue, NULL);
1362
4623e8e6
LP
1363 r = crypt_load(cd, CRYPT_VERITY, NULL);
1364 if (r < 0)
294bd454 1365 return r;
4623e8e6
LP
1366
1367 r = crypt_set_data_device(cd, m->node);
1368 if (r < 0)
294bd454 1369 return r;
4623e8e6 1370
ac1f3ad0
LB
1371 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
1372 return -ENOMEM;
1373
1374 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1375 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1376 * retry a few times before giving up. */
1377 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
1378 if (root_hash_sig || hash_sig_from_file) {
c2923fdc 1379#if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
ac1f3ad0
LB
1380 r = crypt_activate_by_signed_key(cd, name, root_hash, root_hash_size, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, CRYPT_ACTIVATE_READONLY);
1381#else
1382 r = log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "activation of verity device with signature requested, but not supported by cryptsetup due to missing crypt_activate_by_signed_key()");
1383#endif
1384 } else
1385 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
1386 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1387 * There's no way to distinguish this situation from a genuine error due to invalid
1388 * parameters, so immediately fallback to activating the device with a unique name.
1389 * Improvements in libcrypsetup can ensure this never happens: https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1390 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1391 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1392 if (!IN_SET(r, 0, -EEXIST, -ENODEV))
1393 return r;
1394 if (r == -EEXIST) {
1395 struct crypt_device *existing_cd = NULL;
c2923fdc 1396
ac1f3ad0
LB
1397 if (!restore_deferred_remove){
1398 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1399 r = dm_deferred_remove_cancel(name);
1400 if (r < 0)
1401 return log_debug_errno(r, "Disabling automated deferred removal for verity device %s failed: %m", node);
1402 restore_deferred_remove = strdup(name);
1403 if (!restore_deferred_remove)
1404 return -ENOMEM;
1405 }
c2923fdc 1406
ac1f3ad0
LB
1407 r = verity_can_reuse(root_hash, root_hash_size, !!root_hash_sig || !!hash_sig_from_file, name, &existing_cd);
1408 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1409 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1410 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1411 if (!IN_SET(r, 0, -ENODEV, -ENOENT))
1412 return log_debug_errno(r, "Checking whether existing verity device %s can be reused failed: %m", node);
1413 if (r == 0) {
1414 if (cd)
1415 crypt_free(cd);
1416 cd = existing_cd;
1417 }
c2923fdc 1418 }
ac1f3ad0
LB
1419 if (r == 0)
1420 break;
1421 }
1422
1423 /* Sanity check: libdevmapper is known to report that the device already exists and is active,
1424 * but it's actually not there, so the later filesystem probe or mount would fail. */
1425 if (r == 0)
1426 r = access(node, F_OK);
1427 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1428 * Fall back to activating it with a unique device name. */
1429 if (r != 0 && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
1430 return verity_partition(m, v, root_hash, root_hash_size, verity_data, NULL, root_hash_sig ?: hash_sig_from_file, root_hash_sig_size, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
1431
1432 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1433 restore_deferred_remove = mfree(restore_deferred_remove);
4623e8e6 1434
1cc6c93a
YW
1435 d->decrypted[d->n_decrypted].name = TAKE_PTR(name);
1436 d->decrypted[d->n_decrypted].device = TAKE_PTR(cd);
4623e8e6
LP
1437 d->n_decrypted++;
1438
1cc6c93a 1439 m->decrypted_node = TAKE_PTR(node);
4623e8e6
LP
1440
1441 return 0;
18b5886e
LP
1442}
1443#endif
1444
1445int dissected_image_decrypt(
1446 DissectedImage *m,
1447 const char *passphrase,
4623e8e6
LP
1448 const void *root_hash,
1449 size_t root_hash_size,
e7cbe5cb 1450 const char *verity_data,
c2923fdc
LB
1451 const char *root_hash_sig_path,
1452 const void *root_hash_sig,
1453 size_t root_hash_sig_size,
18b5886e
LP
1454 DissectImageFlags flags,
1455 DecryptedImage **ret) {
1456
349cc4a5 1457#if HAVE_LIBCRYPTSETUP
49b5b3b4 1458 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
18b5886e
LP
1459 unsigned i;
1460 int r;
1461#endif
1462
1463 assert(m);
4623e8e6 1464 assert(root_hash || root_hash_size == 0);
18b5886e
LP
1465
1466 /* Returns:
1467 *
1468 * = 0 → There was nothing to decrypt
1469 * > 0 → Decrypted successfully
d1c536f5 1470 * -ENOKEY → There's something to decrypt but no key was supplied
18b5886e
LP
1471 * -EKEYREJECTED → Passed key was not correct
1472 */
1473
4623e8e6
LP
1474 if (root_hash && root_hash_size < sizeof(sd_id128_t))
1475 return -EINVAL;
1476
1477 if (!m->encrypted && !m->verity) {
18b5886e
LP
1478 *ret = NULL;
1479 return 0;
1480 }
1481
349cc4a5 1482#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1483 d = new0(DecryptedImage, 1);
1484 if (!d)
1485 return -ENOMEM;
1486
1487 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
1488 DissectedPartition *p = m->partitions + i;
4623e8e6 1489 int k;
18b5886e
LP
1490
1491 if (!p->found)
1492 continue;
1493
1494 r = decrypt_partition(p, passphrase, flags, d);
1495 if (r < 0)
1496 return r;
1497
4623e8e6
LP
1498 k = PARTITION_VERITY_OF(i);
1499 if (k >= 0) {
ac1f3ad0 1500 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, verity_data, root_hash_sig_path, root_hash_sig, root_hash_sig_size, flags | DISSECT_IMAGE_VERITY_SHARE, d);
4623e8e6
LP
1501 if (r < 0)
1502 return r;
1503 }
1504
18b5886e
LP
1505 if (!p->decrypted_fstype && p->decrypted_node) {
1506 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
7cc84b2c 1507 if (r < 0 && r != -EUCLEAN)
18b5886e
LP
1508 return r;
1509 }
1510 }
1511
1cc6c93a 1512 *ret = TAKE_PTR(d);
18b5886e
LP
1513
1514 return 1;
1515#else
1516 return -EOPNOTSUPP;
1517#endif
1518}
1519
1520int dissected_image_decrypt_interactively(
1521 DissectedImage *m,
1522 const char *passphrase,
4623e8e6
LP
1523 const void *root_hash,
1524 size_t root_hash_size,
e7cbe5cb 1525 const char *verity_data,
c2923fdc
LB
1526 const char *root_hash_sig_path,
1527 const void *root_hash_sig,
1528 size_t root_hash_sig_size,
18b5886e
LP
1529 DissectImageFlags flags,
1530 DecryptedImage **ret) {
1531
1532 _cleanup_strv_free_erase_ char **z = NULL;
1533 int n = 3, r;
1534
1535 if (passphrase)
1536 n--;
1537
1538 for (;;) {
c2923fdc 1539 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, verity_data, root_hash_sig_path, root_hash_sig, root_hash_sig_size, flags, ret);
18b5886e
LP
1540 if (r >= 0)
1541 return r;
1542 if (r == -EKEYREJECTED)
1543 log_error_errno(r, "Incorrect passphrase, try again!");
fc95c359
YW
1544 else if (r != -ENOKEY)
1545 return log_error_errno(r, "Failed to decrypt image: %m");
18b5886e 1546
baaa35ad
ZJS
1547 if (--n < 0)
1548 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
1549 "Too many retries.");
18b5886e
LP
1550
1551 z = strv_free(z);
1552
a1c111c2 1553 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
18b5886e
LP
1554 if (r < 0)
1555 return log_error_errno(r, "Failed to query for passphrase: %m");
1556
1557 passphrase = z[0];
1558 }
1559}
1560
18b5886e
LP
1561int decrypted_image_relinquish(DecryptedImage *d) {
1562
349cc4a5 1563#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1564 size_t i;
1565 int r;
1566#endif
1567
1568 assert(d);
1569
1570 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1571 * that we don't clean it up ourselves either anymore */
1572
349cc4a5 1573#if HAVE_LIBCRYPTSETUP
18b5886e
LP
1574 for (i = 0; i < d->n_decrypted; i++) {
1575 DecryptedPartition *p = d->decrypted + i;
1576
1577 if (p->relinquished)
1578 continue;
1579
53687948 1580 r = crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
18b5886e
LP
1581 if (r < 0)
1582 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1583
1584 p->relinquished = true;
1585 }
1586#endif
1587
1588 return 0;
1589}
1590
c2923fdc
LB
1591int verity_metadata_load(const char *image, const char *root_hash_path, void **ret_roothash, size_t *ret_roothash_size, char **ret_verity_data, char **ret_roothashsig) {
1592 _cleanup_free_ char *verity_filename = NULL, *roothashsig_filename = NULL;
e7cbe5cb
LB
1593 _cleanup_free_ void *roothash_decoded = NULL;
1594 size_t roothash_decoded_size = 0;
78ebe980
LP
1595 int r;
1596
1597 assert(image);
78ebe980
LP
1598
1599 if (is_device_path(image)) {
1600 /* If we are asked to load the root hash for a device node, exit early */
e7cbe5cb
LB
1601 if (ret_roothash)
1602 *ret_roothash = NULL;
1603 if (ret_roothash_size)
1604 *ret_roothash_size = 0;
1605 if (ret_verity_data)
1606 *ret_verity_data = NULL;
c2923fdc
LB
1607 if (ret_roothashsig)
1608 *ret_roothashsig = NULL;
78ebe980
LP
1609 return 0;
1610 }
1611
e7cbe5cb
LB
1612 if (ret_verity_data) {
1613 char *e;
78ebe980 1614
e7cbe5cb
LB
1615 verity_filename = new(char, strlen(image) + STRLEN(".verity") + 1);
1616 if (!verity_filename)
1617 return -ENOMEM;
1618 strcpy(verity_filename, image);
1619 e = endswith(verity_filename, ".raw");
41488e1f 1620 if (e)
e7cbe5cb
LB
1621 strcpy(e, ".verity");
1622 else
1623 strcat(verity_filename, ".verity");
41488e1f 1624
e7cbe5cb
LB
1625 r = access(verity_filename, F_OK);
1626 if (r < 0) {
1627 if (errno != ENOENT)
1628 return -errno;
1629 verity_filename = mfree(verity_filename);
41488e1f 1630 }
78ebe980 1631 }
78ebe980 1632
c2923fdc
LB
1633 if (ret_roothashsig) {
1634 char *e;
1635
1636 /* Follow naming convention recommended by the relevant RFC:
1637 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1638 roothashsig_filename = new(char, strlen(image) + STRLEN(".roothash.p7s") + 1);
1639 if (!roothashsig_filename)
1640 return -ENOMEM;
1641 strcpy(roothashsig_filename, image);
1642 e = endswith(roothashsig_filename, ".raw");
1643 if (e)
1644 strcpy(e, ".roothash.p7s");
1645 else
1646 strcat(roothashsig_filename, ".roothash.p7s");
1647
1648 r = access(roothashsig_filename, R_OK);
1649 if (r < 0) {
1650 if (errno != ENOENT)
1651 return -errno;
1652 roothashsig_filename = mfree(roothashsig_filename);
1653 }
1654 }
1655
e7cbe5cb
LB
1656 if (ret_roothash) {
1657 _cleanup_free_ char *text = NULL;
1658 assert(ret_roothash_size);
1659
0389f4fa
LB
1660 if (root_hash_path) {
1661 /* We have the path to a roothash to load and decode, eg: RootHash=/foo/bar.roothash */
1662 r = read_one_line_file(root_hash_path, &text);
1663 if (r < 0)
e7cbe5cb 1664 return r;
0389f4fa
LB
1665 } else {
1666 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1667 if (r < 0) {
1668 char *fn, *e, *n;
1669
1670 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1671 return r;
78ebe980 1672
0389f4fa
LB
1673 fn = newa(char, strlen(image) + STRLEN(".roothash") + 1);
1674 n = stpcpy(fn, image);
1675 e = endswith(fn, ".raw");
1676 if (e)
1677 n = e;
e7cbe5cb 1678
0389f4fa 1679 strcpy(n, ".roothash");
e7cbe5cb 1680
0389f4fa
LB
1681 r = read_one_line_file(fn, &text);
1682 if (r < 0 && r != -ENOENT)
1683 return r;
1684 }
e7cbe5cb
LB
1685 }
1686
1687 if (text) {
1688 r = unhexmem(text, strlen(text), &roothash_decoded, &roothash_decoded_size);
1689 if (r < 0)
1690 return r;
1691 if (roothash_decoded_size < sizeof(sd_id128_t))
1692 return -EINVAL;
1693 }
1694 }
1695
1696 if (ret_roothash) {
1697 *ret_roothash = TAKE_PTR(roothash_decoded);
1698 *ret_roothash_size = roothash_decoded_size;
1699 }
1700 if (ret_verity_data)
1701 *ret_verity_data = TAKE_PTR(verity_filename);
c2923fdc
LB
1702 if (roothashsig_filename)
1703 *ret_roothashsig = TAKE_PTR(roothashsig_filename);
78ebe980 1704
78ebe980
LP
1705 return 1;
1706}
1707
3b925504
LP
1708int dissected_image_acquire_metadata(DissectedImage *m) {
1709
1710 enum {
1711 META_HOSTNAME,
1712 META_MACHINE_ID,
1713 META_MACHINE_INFO,
1714 META_OS_RELEASE,
1715 _META_MAX,
1716 };
1717
1718 static const char *const paths[_META_MAX] = {
1719 [META_HOSTNAME] = "/etc/hostname\0",
1720 [META_MACHINE_ID] = "/etc/machine-id\0",
1721 [META_MACHINE_INFO] = "/etc/machine-info\0",
d4dffb85
LP
1722 [META_OS_RELEASE] = "/etc/os-release\0"
1723 "/usr/lib/os-release\0",
3b925504
LP
1724 };
1725
1726 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL;
1727 _cleanup_(rmdir_and_freep) char *t = NULL;
1728 _cleanup_(sigkill_waitp) pid_t child = 0;
1729 sd_id128_t machine_id = SD_ID128_NULL;
1730 _cleanup_free_ char *hostname = NULL;
1731 unsigned n_meta_initialized = 0, k;
1732 int fds[2 * _META_MAX], r;
3b925504
LP
1733
1734 BLOCK_SIGNALS(SIGCHLD);
1735
1736 assert(m);
1737
1738 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++)
1739 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
1740 r = -errno;
1741 goto finish;
1742 }
1743
1744 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
1745 if (r < 0)
1746 goto finish;
1747
e2047ba9 1748 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
be39f6ee 1749 if (r < 0)
3b925504 1750 goto finish;
be39f6ee 1751 if (r == 0) {
03bcb6d4 1752 r = dissected_image_mount(m, t, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_VALIDATE_OS);
429d4e41
LP
1753 if (r < 0) {
1754 log_debug_errno(r, "Failed to mount dissected image: %m");
3b925504 1755 _exit(EXIT_FAILURE);
429d4e41 1756 }
3b925504
LP
1757
1758 for (k = 0; k < _META_MAX; k++) {
1759 _cleanup_close_ int fd = -1;
1760 const char *p;
1761
1762 fds[2*k] = safe_close(fds[2*k]);
1763
1764 NULSTR_FOREACH(p, paths[k]) {
36952d19 1765 fd = chase_symlinks_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3b925504
LP
1766 if (fd >= 0)
1767 break;
1768 }
36952d19
LP
1769 if (fd < 0) {
1770 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
3b925504 1771 continue;
36952d19 1772 }
3b925504
LP
1773
1774 r = copy_bytes(fd, fds[2*k+1], (uint64_t) -1, 0);
1775 if (r < 0)
1776 _exit(EXIT_FAILURE);
1777
1778 fds[2*k+1] = safe_close(fds[2*k+1]);
1779 }
1780
1781 _exit(EXIT_SUCCESS);
1782 }
1783
1784 for (k = 0; k < _META_MAX; k++) {
1785 _cleanup_fclose_ FILE *f = NULL;
1786
1787 fds[2*k+1] = safe_close(fds[2*k+1]);
1788
4fa744a3 1789 f = take_fdopen(&fds[2*k], "r");
3b925504
LP
1790 if (!f) {
1791 r = -errno;
1792 goto finish;
1793 }
1794
3b925504
LP
1795 switch (k) {
1796
1797 case META_HOSTNAME:
1798 r = read_etc_hostname_stream(f, &hostname);
1799 if (r < 0)
1800 log_debug_errno(r, "Failed to read /etc/hostname: %m");
1801
1802 break;
1803
1804 case META_MACHINE_ID: {
1805 _cleanup_free_ char *line = NULL;
1806
1807 r = read_line(f, LONG_LINE_MAX, &line);
1808 if (r < 0)
1809 log_debug_errno(r, "Failed to read /etc/machine-id: %m");
1810 else if (r == 33) {
1811 r = sd_id128_from_string(line, &machine_id);
1812 if (r < 0)
1813 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
1814 } else if (r == 0)
1815 log_debug("/etc/machine-id file is empty.");
1816 else
1817 log_debug("/etc/machine-id has unexpected length %i.", r);
1818
1819 break;
1820 }
1821
1822 case META_MACHINE_INFO:
aa8fbc74 1823 r = load_env_file_pairs(f, "machine-info", &machine_info);
3b925504
LP
1824 if (r < 0)
1825 log_debug_errno(r, "Failed to read /etc/machine-info: %m");
1826
1827 break;
1828
1829 case META_OS_RELEASE:
aa8fbc74 1830 r = load_env_file_pairs(f, "os-release", &os_release);
3b925504
LP
1831 if (r < 0)
1832 log_debug_errno(r, "Failed to read OS release file: %m");
1833
1834 break;
1835 }
1836 }
1837
2e87a1fd 1838 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3b925504 1839 child = 0;
2e87a1fd 1840 if (r < 0)
3b925504 1841 goto finish;
2e87a1fd
LP
1842 if (r != EXIT_SUCCESS)
1843 return -EPROTO;
3b925504
LP
1844
1845 free_and_replace(m->hostname, hostname);
1846 m->machine_id = machine_id;
1847 strv_free_and_replace(m->machine_info, machine_info);
1848 strv_free_and_replace(m->os_release, os_release);
1849
1850finish:
1851 for (k = 0; k < n_meta_initialized; k++)
1852 safe_close_pair(fds + 2*k);
1853
1854 return r;
1855}
1856
4526113f
LP
1857int dissect_image_and_warn(
1858 int fd,
1859 const char *name,
1860 const void *root_hash,
1861 size_t root_hash_size,
e7cbe5cb 1862 const char *verity_data,
18d73705 1863 const MountOptions *mount_options,
4526113f
LP
1864 DissectImageFlags flags,
1865 DissectedImage **ret) {
1866
1867 _cleanup_free_ char *buffer = NULL;
1868 int r;
1869
1870 if (!name) {
1871 r = fd_get_path(fd, &buffer);
1872 if (r < 0)
1873 return r;
1874
1875 name = buffer;
1876 }
1877
18d73705 1878 r = dissect_image(fd, root_hash, root_hash_size, verity_data, mount_options, flags, ret);
4526113f
LP
1879
1880 switch (r) {
1881
1882 case -EOPNOTSUPP:
1883 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
1884
1885 case -ENOPKG:
1886 return log_error_errno(r, "Couldn't identify a suitable partition table or file system in '%s'.", name);
1887
1888 case -EADDRNOTAVAIL:
1889 return log_error_errno(r, "No root partition for specified root hash found in '%s'.", name);
1890
1891 case -ENOTUNIQ:
1892 return log_error_errno(r, "Multiple suitable root partitions found in image '%s'.", name);
1893
1894 case -ENXIO:
1895 return log_error_errno(r, "No suitable root partition found in image '%s'.", name);
1896
1897 case -EPROTONOSUPPORT:
1898 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
1899
1900 default:
1901 if (r < 0)
1902 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
1903
1904 return r;
1905 }
1906}
1907
e7cbe5cb
LB
1908bool dissected_image_can_do_verity(const DissectedImage *image, unsigned partition_designator) {
1909 if (image->single_file_system)
1910 return partition_designator == PARTITION_ROOT && image->can_verity;
1911
1912 return PARTITION_VERITY_OF(partition_designator) >= 0;
1913}
1914
1915bool dissected_image_has_verity(const DissectedImage *image, unsigned partition_designator) {
1916 int k;
1917
1918 if (image->single_file_system)
1919 return partition_designator == PARTITION_ROOT && image->verity;
1920
1921 k = PARTITION_VERITY_OF(partition_designator);
1922 return k >= 0 && image->partitions[k].found;
1923}
1924
18d73705
LB
1925MountOptions* mount_options_free_all(MountOptions *options) {
1926 MountOptions *m;
1927
1928 while ((m = options)) {
1929 LIST_REMOVE(mount_options, options, m);
1930 free(m->options);
1931 free(m);
1932 }
1933
1934 return NULL;
1935}
1936
1937const char* mount_options_from_part(const MountOptions *options, unsigned int partition_number) {
1938 MountOptions *m;
1939
1940 LIST_FOREACH(mount_options, m, (MountOptions *)options)
1941 if (partition_number == m->partition_number && !isempty(m->options))
1942 return m->options;
1943 return NULL;
1944}
1945
8c1be37e
LP
1946static const char *const partition_designator_table[] = {
1947 [PARTITION_ROOT] = "root",
1948 [PARTITION_ROOT_SECONDARY] = "root-secondary",
1949 [PARTITION_HOME] = "home",
1950 [PARTITION_SRV] = "srv",
1951 [PARTITION_ESP] = "esp",
a8c47660 1952 [PARTITION_XBOOTLDR] = "xbootldr",
8c1be37e 1953 [PARTITION_SWAP] = "swap",
4623e8e6
LP
1954 [PARTITION_ROOT_VERITY] = "root-verity",
1955 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
d4dffb85
LP
1956 [PARTITION_TMP] = "tmp",
1957 [PARTITION_VAR] = "var",
8c1be37e
LP
1958};
1959
1960DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);