]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/dissect-image.c
build-sys: do not require everything to be rebuild to push man pages (#5521)
[thirdparty/systemd.git] / src / shared / dissect-image.c
CommitLineData
8c1be37e
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2016 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
18b5886e
LP
20#ifdef HAVE_LIBCRYPTSETUP
21#include <libcryptsetup.h>
22#endif
23#include <linux/dm-ioctl.h>
8c1be37e
LP
24#include <sys/mount.h>
25
26#include "architecture.h"
18b5886e 27#include "ask-password-api.h"
8c1be37e
LP
28#include "blkid-util.h"
29#include "dissect-image.h"
18b5886e 30#include "fd-util.h"
78ebe980 31#include "fileio.h"
2eedfd2d 32#include "fs-util.h"
8c1be37e 33#include "gpt.h"
78ebe980 34#include "hexdecoct.h"
8c1be37e
LP
35#include "mount-util.h"
36#include "path-util.h"
37#include "stat-util.h"
18b5886e 38#include "stdio-util.h"
8c1be37e
LP
39#include "string-table.h"
40#include "string-util.h"
2eedfd2d 41#include "strv.h"
8c1be37e 42#include "udev-util.h"
41488e1f 43#include "xattr-util.h"
8c1be37e 44
18b5886e
LP
45static int probe_filesystem(const char *node, char **ret_fstype) {
46#ifdef HAVE_BLKID
47 _cleanup_blkid_free_probe_ blkid_probe b = NULL;
48 const char *fstype;
49 int r;
50
51 b = blkid_new_probe_from_filename(node);
52 if (!b)
53 return -ENOMEM;
54
55 blkid_probe_enable_superblocks(b, 1);
56 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
57
58 errno = 0;
59 r = blkid_do_safeprobe(b);
60 if (r == -2 || r == 1) {
61 log_debug("Failed to identify any partition type on partition %s", node);
62 goto not_found;
63 }
b382db9f
ZJS
64 if (r != 0)
65 return -errno ?: -EIO;
18b5886e
LP
66
67 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
68
69 if (fstype) {
70 char *t;
71
72 t = strdup(fstype);
73 if (!t)
74 return -ENOMEM;
75
76 *ret_fstype = t;
77 return 1;
78 }
79
80not_found:
81 *ret_fstype = NULL;
82 return 0;
83#else
84 return -EOPNOTSUPP;
85#endif
86}
87
9b6deb03 88int dissect_image(int fd, const void *root_hash, size_t root_hash_size, DissectImageFlags flags, DissectedImage **ret) {
8c1be37e
LP
89
90#ifdef HAVE_BLKID
4623e8e6 91 sd_id128_t root_uuid = SD_ID128_NULL, verity_uuid = SD_ID128_NULL;
8c1be37e
LP
92 _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
93 bool is_gpt, is_mbr, generic_rw, multiple_generic = false;
94 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
95 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
96 _cleanup_blkid_free_probe_ blkid_probe b = NULL;
97 _cleanup_udev_unref_ struct udev *udev = NULL;
98 _cleanup_free_ char *generic_node = NULL;
be30ad41 99 sd_id128_t generic_uuid = SD_ID128_NULL;
9b6deb03 100 const char *pttype = NULL;
8c1be37e
LP
101 struct udev_list_entry *first, *item;
102 blkid_partlist pl;
103 int r, generic_nr;
104 struct stat st;
105 unsigned i;
106
107 assert(fd >= 0);
108 assert(ret);
4623e8e6 109 assert(root_hash || root_hash_size == 0);
8c1be37e
LP
110
111 /* Probes a disk image, and returns information about what it found in *ret.
112 *
4623e8e6
LP
113 * Returns -ENOPKG if no suitable partition table or file system could be found.
114 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
115
116 if (root_hash) {
117 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
118 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
119 * 128bit. */
120
121 if (root_hash_size < sizeof(sd_id128_t))
122 return -EINVAL;
123
124 memcpy(&root_uuid, root_hash, sizeof(sd_id128_t));
125 memcpy(&verity_uuid, (const uint8_t*) root_hash + root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
126
127 if (sd_id128_is_null(root_uuid))
128 return -EINVAL;
129 if (sd_id128_is_null(verity_uuid))
130 return -EINVAL;
131 }
8c1be37e
LP
132
133 if (fstat(fd, &st) < 0)
134 return -errno;
135
136 if (!S_ISBLK(st.st_mode))
137 return -ENOTBLK;
138
139 b = blkid_new_probe();
140 if (!b)
141 return -ENOMEM;
142
143 errno = 0;
144 r = blkid_probe_set_device(b, fd, 0, 0);
b382db9f
ZJS
145 if (r != 0)
146 return -errno ?: -ENOMEM;
8c1be37e 147
9b6deb03
LP
148 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
149 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
150 blkid_probe_enable_superblocks(b, 1);
151 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE);
152 }
153
8c1be37e
LP
154 blkid_probe_enable_partitions(b, 1);
155 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
156
157 errno = 0;
158 r = blkid_do_safeprobe(b);
159 if (r == -2 || r == 1) {
160 log_debug("Failed to identify any partition table.");
161 return -ENOPKG;
162 }
b382db9f
ZJS
163 if (r != 0)
164 return -errno ?: -EIO;
8c1be37e
LP
165
166 m = new0(DissectedImage, 1);
167 if (!m)
168 return -ENOMEM;
169
e0f9e7bd
LP
170 if (!(flags & DISSECT_IMAGE_GPT_ONLY) &&
171 (flags & DISSECT_IMAGE_REQUIRE_ROOT)) {
9b6deb03 172 const char *usage = NULL;
8c1be37e 173
9b6deb03
LP
174 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
175 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
176 _cleanup_free_ char *t = NULL, *n = NULL;
177 const char *fstype = NULL;
8c1be37e 178
9b6deb03
LP
179 /* OK, we have found a file system, that's our root partition then. */
180 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
8c1be37e 181
9b6deb03
LP
182 if (fstype) {
183 t = strdup(fstype);
184 if (!t)
185 return -ENOMEM;
186 }
187
188 if (asprintf(&n, "/dev/block/%u:%u", major(st.st_rdev), minor(st.st_rdev)) < 0)
189 return -ENOMEM;
8c1be37e 190
9b6deb03
LP
191 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
192 .found = true,
193 .rw = true,
194 .partno = -1,
195 .architecture = _ARCHITECTURE_INVALID,
196 .fstype = t,
197 .node = n,
198 };
8c1be37e 199
9b6deb03 200 t = n = NULL;
8c1be37e 201
9b6deb03 202 m->encrypted = streq(fstype, "crypto_LUKS");
18b5886e 203
9b6deb03
LP
204 *ret = m;
205 m = NULL;
8c1be37e 206
9b6deb03
LP
207 return 0;
208 }
8c1be37e
LP
209 }
210
211 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
212 if (!pttype)
213 return -ENOPKG;
214
215 is_gpt = streq_ptr(pttype, "gpt");
216 is_mbr = streq_ptr(pttype, "dos");
217
9b6deb03 218 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
8c1be37e
LP
219 return -ENOPKG;
220
221 errno = 0;
222 pl = blkid_probe_get_partitions(b);
b382db9f
ZJS
223 if (!pl)
224 return -errno ?: -ENOMEM;
8c1be37e
LP
225
226 udev = udev_new();
227 if (!udev)
228 return -errno;
229
230 d = udev_device_new_from_devnum(udev, 'b', st.st_rdev);
231 if (!d)
232 return -ENOMEM;
233
234 for (i = 0;; i++) {
235 int n, z;
236
237 if (i >= 10) {
238 log_debug("Kernel partitions never appeared.");
239 return -ENXIO;
240 }
241
242 e = udev_enumerate_new(udev);
243 if (!e)
244 return -errno;
245
246 r = udev_enumerate_add_match_parent(e, d);
247 if (r < 0)
248 return r;
249
250 r = udev_enumerate_scan_devices(e);
251 if (r < 0)
252 return r;
253
254 /* Count the partitions enumerated by the kernel */
255 n = 0;
256 first = udev_enumerate_get_list_entry(e);
257 udev_list_entry_foreach(item, first)
258 n++;
259
260 /* Count the partitions enumerated by blkid */
261 z = blkid_partlist_numof_partitions(pl);
262 if (n == z + 1)
263 break;
264 if (n > z + 1) {
265 log_debug("blkid and kernel partition list do not match.");
266 return -EIO;
267 }
268 if (n < z + 1) {
269 unsigned j;
270
271 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running
272 * or it got EBUSY because udev already opened the device. Let's reprobe the device, which is a
273 * synchronous call that waits until probing is complete. */
274
275 for (j = 0; j < 20; j++) {
276
277 r = ioctl(fd, BLKRRPART, 0);
278 if (r < 0)
279 r = -errno;
280 if (r >= 0 || r != -EBUSY)
281 break;
282
283 /* If something else has the device open, such as an udev rule, the ioctl will return
284 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a
285 * bit, and try again.
286 *
287 * This is really something they should fix in the kernel! */
288
289 usleep(50 * USEC_PER_MSEC);
290 }
291
292 if (r < 0)
293 return r;
294 }
295
296 e = udev_enumerate_unref(e);
297 }
298
299 first = udev_enumerate_get_list_entry(e);
300 udev_list_entry_foreach(item, first) {
301 _cleanup_udev_device_unref_ struct udev_device *q;
9b6deb03 302 unsigned long long pflags;
8c1be37e
LP
303 blkid_partition pp;
304 const char *node;
305 dev_t qn;
306 int nr;
307
308 q = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
309 if (!q)
310 return -errno;
311
312 qn = udev_device_get_devnum(q);
313 if (major(qn) == 0)
314 continue;
315
316 if (st.st_rdev == qn)
317 continue;
318
319 node = udev_device_get_devnode(q);
320 if (!node)
321 continue;
322
323 pp = blkid_partlist_devno_to_partition(pl, qn);
324 if (!pp)
325 continue;
326
9b6deb03 327 pflags = blkid_partition_get_flags(pp);
8c1be37e
LP
328
329 nr = blkid_partition_get_partno(pp);
330 if (nr < 0)
331 continue;
332
333 if (is_gpt) {
334 int designator = _PARTITION_DESIGNATOR_INVALID, architecture = _ARCHITECTURE_INVALID;
4623e8e6
LP
335 const char *stype, *sid, *fstype = NULL;
336 sd_id128_t type_id, id;
8c1be37e
LP
337 bool rw = true;
338
4623e8e6
LP
339 sid = blkid_partition_get_uuid(pp);
340 if (!sid)
341 continue;
342 if (sd_id128_from_string(sid, &id) < 0)
343 continue;
344
8c1be37e
LP
345 stype = blkid_partition_get_type_string(pp);
346 if (!stype)
347 continue;
8c1be37e
LP
348 if (sd_id128_from_string(stype, &type_id) < 0)
349 continue;
350
351 if (sd_id128_equal(type_id, GPT_HOME)) {
a48dd347
LP
352
353 if (pflags & GPT_FLAG_NO_AUTO)
354 continue;
355
8c1be37e 356 designator = PARTITION_HOME;
9b6deb03 357 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 358 } else if (sd_id128_equal(type_id, GPT_SRV)) {
a48dd347
LP
359
360 if (pflags & GPT_FLAG_NO_AUTO)
361 continue;
362
8c1be37e 363 designator = PARTITION_SRV;
9b6deb03 364 rw = !(pflags & GPT_FLAG_READ_ONLY);
8c1be37e 365 } else if (sd_id128_equal(type_id, GPT_ESP)) {
a48dd347
LP
366
367 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
368 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
369 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
370
371 if (pflags & GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
372 continue;
373
8c1be37e
LP
374 designator = PARTITION_ESP;
375 fstype = "vfat";
376 }
377#ifdef GPT_ROOT_NATIVE
378 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
4623e8e6 379
a48dd347
LP
380 if (pflags & GPT_FLAG_NO_AUTO)
381 continue;
382
4623e8e6
LP
383 /* If a root ID is specified, ignore everything but the root id */
384 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
385 continue;
386
8c1be37e
LP
387 designator = PARTITION_ROOT;
388 architecture = native_architecture();
9b6deb03 389 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 390 } else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE_VERITY)) {
4623e8e6 391
a48dd347
LP
392 if (pflags & GPT_FLAG_NO_AUTO)
393 continue;
394
4623e8e6
LP
395 m->can_verity = true;
396
397 /* Ignore verity unless a root hash is specified */
398 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
399 continue;
400
401 designator = PARTITION_ROOT_VERITY;
402 fstype = "DM_verity_hash";
403 architecture = native_architecture();
404 rw = false;
405 }
406#endif
8c1be37e
LP
407#ifdef GPT_ROOT_SECONDARY
408 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
4623e8e6 409
a48dd347
LP
410 if (pflags & GPT_FLAG_NO_AUTO)
411 continue;
412
4623e8e6
LP
413 /* If a root ID is specified, ignore everything but the root id */
414 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
415 continue;
416
8c1be37e
LP
417 designator = PARTITION_ROOT_SECONDARY;
418 architecture = SECONDARY_ARCHITECTURE;
9b6deb03 419 rw = !(pflags & GPT_FLAG_READ_ONLY);
4f8b86e3 420 } else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY_VERITY)) {
a48dd347
LP
421
422 if (pflags & GPT_FLAG_NO_AUTO)
423 continue;
424
4623e8e6
LP
425 m->can_verity = true;
426
427 /* Ignore verity unless root has is specified */
428 if (sd_id128_is_null(verity_uuid) || !sd_id128_equal(verity_uuid, id))
429 continue;
430
431 designator = PARTITION_ROOT_SECONDARY_VERITY;
432 fstype = "DM_verity_hash";
433 architecture = SECONDARY_ARCHITECTURE;
434 rw = false;
435 }
8c1be37e
LP
436#endif
437 else if (sd_id128_equal(type_id, GPT_SWAP)) {
a48dd347
LP
438
439 if (pflags & GPT_FLAG_NO_AUTO)
440 continue;
441
8c1be37e
LP
442 designator = PARTITION_SWAP;
443 fstype = "swap";
444 } else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
445
a48dd347
LP
446 if (pflags & GPT_FLAG_NO_AUTO)
447 continue;
448
8c1be37e
LP
449 if (generic_node)
450 multiple_generic = true;
451 else {
452 generic_nr = nr;
9b6deb03 453 generic_rw = !(pflags & GPT_FLAG_READ_ONLY);
be30ad41 454 generic_uuid = id;
8c1be37e
LP
455 generic_node = strdup(node);
456 if (!generic_node)
457 return -ENOMEM;
458 }
459 }
460
461 if (designator != _PARTITION_DESIGNATOR_INVALID) {
462 _cleanup_free_ char *t = NULL, *n = NULL;
463
464 /* First one wins */
465 if (m->partitions[designator].found)
466 continue;
467
468 if (fstype) {
469 t = strdup(fstype);
470 if (!t)
471 return -ENOMEM;
472 }
473
474 n = strdup(node);
475 if (!n)
476 return -ENOMEM;
477
478 m->partitions[designator] = (DissectedPartition) {
479 .found = true,
480 .partno = nr,
481 .rw = rw,
482 .architecture = architecture,
483 .node = n,
484 .fstype = t,
be30ad41 485 .uuid = id,
8c1be37e
LP
486 };
487
488 n = t = NULL;
489 }
490
491 } else if (is_mbr) {
492
9b6deb03 493 if (pflags != 0x80) /* Bootable flag */
8c1be37e
LP
494 continue;
495
496 if (blkid_partition_get_type(pp) != 0x83) /* Linux partition */
497 continue;
498
499 if (generic_node)
500 multiple_generic = true;
501 else {
502 generic_nr = nr;
503 generic_rw = true;
504 generic_node = strdup(node);
505 if (!generic_node)
506 return -ENOMEM;
507 }
508 }
509 }
510
511 if (!m->partitions[PARTITION_ROOT].found) {
512 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
513 * either, then check if there's a single generic one, and use that. */
514
4623e8e6 515 if (m->partitions[PARTITION_ROOT_VERITY].found)
e0f9e7bd 516 return -EADDRNOTAVAIL;
4623e8e6 517
8c1be37e
LP
518 if (m->partitions[PARTITION_ROOT_SECONDARY].found) {
519 m->partitions[PARTITION_ROOT] = m->partitions[PARTITION_ROOT_SECONDARY];
520 zero(m->partitions[PARTITION_ROOT_SECONDARY]);
4623e8e6
LP
521
522 m->partitions[PARTITION_ROOT_VERITY] = m->partitions[PARTITION_ROOT_SECONDARY_VERITY];
523 zero(m->partitions[PARTITION_ROOT_SECONDARY_VERITY]);
524
e0f9e7bd
LP
525 } else if (flags & DISSECT_IMAGE_REQUIRE_ROOT) {
526
527 /* If the root has was set, then we won't fallback to a generic node, because the root hash
528 * decides */
529 if (root_hash)
530 return -EADDRNOTAVAIL;
8c1be37e 531
e0f9e7bd
LP
532 /* If we didn't find a generic node, then we can't fix this up either */
533 if (!generic_node)
534 return -ENXIO;
535
536 /* If we didn't find a properly marked root partition, but we did find a single suitable
537 * generic Linux partition, then use this as root partition, if the caller asked for it. */
8c1be37e
LP
538 if (multiple_generic)
539 return -ENOTUNIQ;
540
541 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
542 .found = true,
543 .rw = generic_rw,
544 .partno = generic_nr,
545 .architecture = _ARCHITECTURE_INVALID,
546 .node = generic_node,
be30ad41 547 .uuid = generic_uuid,
8c1be37e
LP
548 };
549
550 generic_node = NULL;
e0f9e7bd 551 }
8c1be37e
LP
552 }
553
4623e8e6 554 if (root_hash) {
e0f9e7bd 555 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
4623e8e6
LP
556 return -EADDRNOTAVAIL;
557
558 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
559 * (which would be weird, after all the root hash should only be assigned to one pair of
560 * partitions... */
561 m->partitions[PARTITION_ROOT_SECONDARY].found = false;
562 m->partitions[PARTITION_ROOT_SECONDARY_VERITY].found = false;
563
564 /* If we found a verity setup, then the root partition is necessarily read-only. */
565 m->partitions[PARTITION_ROOT].rw = false;
566
567 m->verity = true;
568 }
569
18b5886e
LP
570 blkid_free_probe(b);
571 b = NULL;
572
8c1be37e
LP
573 /* Fill in file system types if we don't know them yet. */
574 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
18b5886e 575 DissectedPartition *p = m->partitions + i;
8c1be37e 576
18b5886e 577 if (!p->found)
8c1be37e
LP
578 continue;
579
18b5886e
LP
580 if (!p->fstype && p->node) {
581 r = probe_filesystem(p->node, &p->fstype);
582 if (r < 0)
583 return r;
8c1be37e
LP
584 }
585
18b5886e
LP
586 if (streq_ptr(p->fstype, "crypto_LUKS"))
587 m->encrypted = true;
8c1be37e
LP
588 }
589
590 *ret = m;
591 m = NULL;
592
593 return 0;
594#else
595 return -EOPNOTSUPP;
596#endif
597}
598
599DissectedImage* dissected_image_unref(DissectedImage *m) {
600 unsigned i;
601
602 if (!m)
603 return NULL;
604
605 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
606 free(m->partitions[i].fstype);
607 free(m->partitions[i].node);
18b5886e
LP
608 free(m->partitions[i].decrypted_fstype);
609 free(m->partitions[i].decrypted_node);
8c1be37e
LP
610 }
611
612 free(m);
613 return NULL;
614}
615
18b5886e
LP
616static int is_loop_device(const char *path) {
617 char s[strlen("/sys/dev/block/") + DECIMAL_STR_MAX(dev_t) + 1 + DECIMAL_STR_MAX(dev_t) + strlen("/../loop/")];
618 struct stat st;
619
620 assert(path);
621
622 if (stat(path, &st) < 0)
623 return -errno;
624
625 if (!S_ISBLK(st.st_mode))
626 return -ENOTBLK;
627
628 xsprintf(s, "/sys/dev/block/%u:%u/loop/", major(st.st_rdev), minor(st.st_rdev));
629 if (access(s, F_OK) < 0) {
630 if (errno != ENOENT)
631 return -errno;
632
633 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
634 xsprintf(s, "/sys/dev/block/%u:%u/../loop/", major(st.st_rdev), minor(st.st_rdev));
635 if (access(s, F_OK) < 0)
636 return errno == ENOENT ? false : -errno;
637 }
638
639 return true;
640}
641
642static int mount_partition(
643 DissectedPartition *m,
644 const char *where,
645 const char *directory,
646 DissectImageFlags flags) {
647
648 const char *p, *options = NULL, *node, *fstype;
2eedfd2d 649 _cleanup_free_ char *chased = NULL;
8c1be37e 650 bool rw;
2eedfd2d 651 int r;
8c1be37e
LP
652
653 assert(m);
654 assert(where);
655
18b5886e
LP
656 node = m->decrypted_node ?: m->node;
657 fstype = m->decrypted_fstype ?: m->fstype;
658
659 if (!m->found || !node || !fstype)
8c1be37e
LP
660 return 0;
661
18b5886e
LP
662 /* Stacked encryption? Yuck */
663 if (streq_ptr(fstype, "crypto_LUKS"))
664 return -ELOOP;
665
666 rw = m->rw && !(flags & DISSECT_IMAGE_READ_ONLY);
8c1be37e 667
2eedfd2d
LP
668 if (directory) {
669 r = chase_symlinks(directory, where, CHASE_PREFIX_ROOT, &chased);
670 if (r < 0)
671 return r;
672
673 p = chased;
674 } else
8c1be37e
LP
675 p = where;
676
18b5886e
LP
677 /* If requested, turn on discard support. */
678 if (STR_IN_SET(fstype, "btrfs", "ext4", "vfat", "xfs") &&
679 ((flags & DISSECT_IMAGE_DISCARD) ||
680 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node))))
681 options = "discard";
8c1be37e 682
18b5886e 683 return mount_verbose(LOG_DEBUG, node, p, fstype, MS_NODEV|(rw ? 0 : MS_RDONLY), options);
8c1be37e
LP
684}
685
18b5886e 686int dissected_image_mount(DissectedImage *m, const char *where, DissectImageFlags flags) {
8c1be37e
LP
687 int r;
688
689 assert(m);
690 assert(where);
691
692 if (!m->partitions[PARTITION_ROOT].found)
693 return -ENXIO;
694
695 r = mount_partition(m->partitions + PARTITION_ROOT, where, NULL, flags);
696 if (r < 0)
697 return r;
698
699 r = mount_partition(m->partitions + PARTITION_HOME, where, "/home", flags);
700 if (r < 0)
701 return r;
702
703 r = mount_partition(m->partitions + PARTITION_SRV, where, "/srv", flags);
704 if (r < 0)
705 return r;
706
707 if (m->partitions[PARTITION_ESP].found) {
2eedfd2d 708 const char *mp;
8c1be37e
LP
709
710 /* Mount the ESP to /efi if it exists and is empty. If it doesn't exist, use /boot instead. */
711
2eedfd2d
LP
712 FOREACH_STRING(mp, "/efi", "/boot") {
713 _cleanup_free_ char *p = NULL;
714
715 r = chase_symlinks(mp, where, CHASE_PREFIX_ROOT, &p);
8c1be37e 716 if (r < 0)
2eedfd2d
LP
717 continue;
718
719 r = dir_is_empty(p);
720 if (r > 0) {
721 r = mount_partition(m->partitions + PARTITION_ESP, where, mp, flags);
722 if (r < 0)
723 return r;
724 }
8c1be37e
LP
725 }
726 }
727
728 return 0;
729}
730
18b5886e
LP
731#ifdef HAVE_LIBCRYPTSETUP
732typedef struct DecryptedPartition {
733 struct crypt_device *device;
734 char *name;
735 bool relinquished;
736} DecryptedPartition;
737
738struct DecryptedImage {
739 DecryptedPartition *decrypted;
740 size_t n_decrypted;
741 size_t n_allocated;
742};
743#endif
744
745DecryptedImage* decrypted_image_unref(DecryptedImage* d) {
746#ifdef HAVE_LIBCRYPTSETUP
747 size_t i;
748 int r;
749
750 if (!d)
751 return NULL;
752
753 for (i = 0; i < d->n_decrypted; i++) {
754 DecryptedPartition *p = d->decrypted + i;
755
756 if (p->device && p->name && !p->relinquished) {
757 r = crypt_deactivate(p->device, p->name);
758 if (r < 0)
759 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
760 }
761
762 if (p->device)
763 crypt_free(p->device);
764 free(p->name);
765 }
766
767 free(d);
768#endif
769 return NULL;
770}
771
772#ifdef HAVE_LIBCRYPTSETUP
4623e8e6
LP
773
774static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
775 _cleanup_free_ char *name = NULL, *node = NULL;
776 const char *base;
777
778 assert(original_node);
779 assert(suffix);
780 assert(ret_name);
781 assert(ret_node);
782
783 base = strrchr(original_node, '/');
784 if (!base)
785 return -EINVAL;
786 base++;
787 if (isempty(base))
788 return -EINVAL;
789
790 name = strjoin(base, suffix);
791 if (!name)
792 return -ENOMEM;
793 if (!filename_is_valid(name))
794 return -EINVAL;
795
796 node = strjoin(crypt_get_dir(), "/", name);
797 if (!node)
798 return -ENOMEM;
799
800 *ret_name = name;
801 *ret_node = node;
802
803 name = node = NULL;
804 return 0;
805}
806
18b5886e
LP
807static int decrypt_partition(
808 DissectedPartition *m,
809 const char *passphrase,
810 DissectImageFlags flags,
811 DecryptedImage *d) {
812
813 _cleanup_free_ char *node = NULL, *name = NULL;
814 struct crypt_device *cd;
18b5886e
LP
815 int r;
816
817 assert(m);
818 assert(d);
819
820 if (!m->found || !m->node || !m->fstype)
821 return 0;
822
823 if (!streq(m->fstype, "crypto_LUKS"))
824 return 0;
825
4623e8e6
LP
826 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
827 if (r < 0)
828 return r;
18b5886e
LP
829
830 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
831 return -ENOMEM;
832
833 r = crypt_init(&cd, m->node);
834 if (r < 0)
835 return r;
836
837 r = crypt_load(cd, CRYPT_LUKS1, NULL);
838 if (r < 0)
839 goto fail;
840
841 r = crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
842 ((flags & DISSECT_IMAGE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
843 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
844 if (r == -EPERM) {
845 r = -EKEYREJECTED;
846 goto fail;
847 }
848 if (r < 0)
849 goto fail;
850
851 d->decrypted[d->n_decrypted].name = name;
852 name = NULL;
853
854 d->decrypted[d->n_decrypted].device = cd;
855 d->n_decrypted++;
856
857 m->decrypted_node = node;
858 node = NULL;
859
860 return 0;
861
4623e8e6
LP
862fail:
863 crypt_free(cd);
864 return r;
865}
866
867static int verity_partition(
868 DissectedPartition *m,
869 DissectedPartition *v,
870 const void *root_hash,
871 size_t root_hash_size,
872 DissectImageFlags flags,
873 DecryptedImage *d) {
874
875 _cleanup_free_ char *node = NULL, *name = NULL;
876 struct crypt_device *cd;
877 int r;
878
879 assert(m);
880 assert(v);
881
882 if (!root_hash)
883 return 0;
884
885 if (!m->found || !m->node || !m->fstype)
886 return 0;
887 if (!v->found || !v->node || !v->fstype)
888 return 0;
889
890 if (!streq(v->fstype, "DM_verity_hash"))
891 return 0;
892
893 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
894 if (r < 0)
895 return r;
896
897 if (!GREEDY_REALLOC0(d->decrypted, d->n_allocated, d->n_decrypted + 1))
898 return -ENOMEM;
899
900 r = crypt_init(&cd, v->node);
901 if (r < 0)
902 return r;
903
904 r = crypt_load(cd, CRYPT_VERITY, NULL);
905 if (r < 0)
906 goto fail;
907
908 r = crypt_set_data_device(cd, m->node);
909 if (r < 0)
910 goto fail;
911
912 r = crypt_activate_by_volume_key(cd, name, root_hash, root_hash_size, CRYPT_ACTIVATE_READONLY);
913 if (r < 0)
914 goto fail;
915
916 d->decrypted[d->n_decrypted].name = name;
917 name = NULL;
918
919 d->decrypted[d->n_decrypted].device = cd;
920 d->n_decrypted++;
921
922 m->decrypted_node = node;
923 node = NULL;
924
925 return 0;
926
18b5886e
LP
927fail:
928 crypt_free(cd);
929 return r;
930}
931#endif
932
933int dissected_image_decrypt(
934 DissectedImage *m,
935 const char *passphrase,
4623e8e6
LP
936 const void *root_hash,
937 size_t root_hash_size,
18b5886e
LP
938 DissectImageFlags flags,
939 DecryptedImage **ret) {
940
941 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
942#ifdef HAVE_LIBCRYPTSETUP
943 unsigned i;
944 int r;
945#endif
946
947 assert(m);
4623e8e6 948 assert(root_hash || root_hash_size == 0);
18b5886e
LP
949
950 /* Returns:
951 *
952 * = 0 → There was nothing to decrypt
953 * > 0 → Decrypted successfully
954 * -ENOKEY → There's some to decrypt but no key was supplied
955 * -EKEYREJECTED → Passed key was not correct
956 */
957
4623e8e6
LP
958 if (root_hash && root_hash_size < sizeof(sd_id128_t))
959 return -EINVAL;
960
961 if (!m->encrypted && !m->verity) {
18b5886e
LP
962 *ret = NULL;
963 return 0;
964 }
965
966#ifdef HAVE_LIBCRYPTSETUP
4623e8e6 967 if (m->encrypted && !passphrase)
18b5886e
LP
968 return -ENOKEY;
969
970 d = new0(DecryptedImage, 1);
971 if (!d)
972 return -ENOMEM;
973
974 for (i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
975 DissectedPartition *p = m->partitions + i;
4623e8e6 976 int k;
18b5886e
LP
977
978 if (!p->found)
979 continue;
980
981 r = decrypt_partition(p, passphrase, flags, d);
982 if (r < 0)
983 return r;
984
4623e8e6
LP
985 k = PARTITION_VERITY_OF(i);
986 if (k >= 0) {
987 r = verity_partition(p, m->partitions + k, root_hash, root_hash_size, flags, d);
988 if (r < 0)
989 return r;
990 }
991
18b5886e
LP
992 if (!p->decrypted_fstype && p->decrypted_node) {
993 r = probe_filesystem(p->decrypted_node, &p->decrypted_fstype);
994 if (r < 0)
995 return r;
996 }
997 }
998
999 *ret = d;
1000 d = NULL;
1001
1002 return 1;
1003#else
1004 return -EOPNOTSUPP;
1005#endif
1006}
1007
1008int dissected_image_decrypt_interactively(
1009 DissectedImage *m,
1010 const char *passphrase,
4623e8e6
LP
1011 const void *root_hash,
1012 size_t root_hash_size,
18b5886e
LP
1013 DissectImageFlags flags,
1014 DecryptedImage **ret) {
1015
1016 _cleanup_strv_free_erase_ char **z = NULL;
1017 int n = 3, r;
1018
1019 if (passphrase)
1020 n--;
1021
1022 for (;;) {
4623e8e6 1023 r = dissected_image_decrypt(m, passphrase, root_hash, root_hash_size, flags, ret);
18b5886e
LP
1024 if (r >= 0)
1025 return r;
1026 if (r == -EKEYREJECTED)
1027 log_error_errno(r, "Incorrect passphrase, try again!");
1028 else if (r != -ENOKEY) {
1029 log_error_errno(r, "Failed to decrypt image: %m");
1030 return r;
1031 }
1032
1033 if (--n < 0) {
1034 log_error("Too many retries.");
1035 return -EKEYREJECTED;
1036 }
1037
1038 z = strv_free(z);
1039
1040 r = ask_password_auto("Please enter image passphrase!", NULL, "dissect", "dissect", USEC_INFINITY, 0, &z);
1041 if (r < 0)
1042 return log_error_errno(r, "Failed to query for passphrase: %m");
1043
1044 passphrase = z[0];
1045 }
1046}
1047
1048#ifdef HAVE_LIBCRYPTSETUP
1049static int deferred_remove(DecryptedPartition *p) {
1050
1051 struct dm_ioctl dm = {
1052 .version = {
1053 DM_VERSION_MAJOR,
1054 DM_VERSION_MINOR,
1055 DM_VERSION_PATCHLEVEL
1056 },
1057 .data_size = sizeof(dm),
1058 .flags = DM_DEFERRED_REMOVE,
1059 };
1060
1061 _cleanup_close_ int fd = -1;
1062
1063 assert(p);
1064
1065 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1066
1067 fd = open("/dev/mapper/control", O_RDWR|O_CLOEXEC);
1068 if (fd < 0)
1069 return -errno;
1070
1071 strncpy(dm.name, p->name, sizeof(dm.name));
1072
1073 if (ioctl(fd, DM_DEV_REMOVE, &dm))
1074 return -errno;
1075
1076 return 0;
1077}
1078#endif
1079
1080int decrypted_image_relinquish(DecryptedImage *d) {
1081
1082#ifdef HAVE_LIBCRYPTSETUP
1083 size_t i;
1084 int r;
1085#endif
1086
1087 assert(d);
1088
1089 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1090 * that we don't clean it up ourselves either anymore */
1091
1092#ifdef HAVE_LIBCRYPTSETUP
1093 for (i = 0; i < d->n_decrypted; i++) {
1094 DecryptedPartition *p = d->decrypted + i;
1095
1096 if (p->relinquished)
1097 continue;
1098
1099 r = deferred_remove(p);
1100 if (r < 0)
1101 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
1102
1103 p->relinquished = true;
1104 }
1105#endif
1106
1107 return 0;
1108}
1109
78ebe980
LP
1110int root_hash_load(const char *image, void **ret, size_t *ret_size) {
1111 _cleanup_free_ char *text = NULL;
1112 _cleanup_free_ void *k = NULL;
78ebe980
LP
1113 size_t l;
1114 int r;
1115
1116 assert(image);
1117 assert(ret);
1118 assert(ret_size);
1119
1120 if (is_device_path(image)) {
1121 /* If we are asked to load the root hash for a device node, exit early */
1122 *ret = NULL;
1123 *ret_size = 0;
1124 return 0;
1125 }
1126
41488e1f
LP
1127 r = getxattr_malloc(image, "user.verity.roothash", &text, true);
1128 if (r < 0) {
1129 char *fn, *e, *n;
78ebe980 1130
41488e1f
LP
1131 if (!IN_SET(r, -ENODATA, -EOPNOTSUPP, -ENOENT))
1132 return r;
78ebe980 1133
41488e1f
LP
1134 fn = newa(char, strlen(image) + strlen(".roothash") + 1);
1135 n = stpcpy(fn, image);
1136 e = endswith(fn, ".raw");
1137 if (e)
1138 n = e;
1139
1140 strcpy(n, ".roothash");
1141
1142 r = read_one_line_file(fn, &text);
1143 if (r == -ENOENT) {
1144 *ret = NULL;
1145 *ret_size = 0;
1146 return 0;
1147 }
1148 if (r < 0)
1149 return r;
78ebe980 1150 }
78ebe980
LP
1151
1152 r = unhexmem(text, strlen(text), &k, &l);
1153 if (r < 0)
1154 return r;
1155 if (l < sizeof(sd_id128_t))
1156 return -EINVAL;
1157
1158 *ret = k;
1159 *ret_size = l;
1160
1161 k = NULL;
1162
1163 return 1;
1164}
1165
8c1be37e
LP
1166static const char *const partition_designator_table[] = {
1167 [PARTITION_ROOT] = "root",
1168 [PARTITION_ROOT_SECONDARY] = "root-secondary",
1169 [PARTITION_HOME] = "home",
1170 [PARTITION_SRV] = "srv",
1171 [PARTITION_ESP] = "esp",
1172 [PARTITION_SWAP] = "swap",
4623e8e6
LP
1173 [PARTITION_ROOT_VERITY] = "root-verity",
1174 [PARTITION_ROOT_SECONDARY_VERITY] = "root-secondary-verity",
8c1be37e
LP
1175};
1176
1177DEFINE_STRING_TABLE_LOOKUP(partition_designator, int);