Merge branch 'upstream' into tizen
[platform/upstream/cryptsetup.git] / lib / setup.c
1 /*
2  * libcryptsetup - cryptsetup library
3  *
4  * Copyright (C) 2004 Jana Saout <jana@saout.de>
5  * Copyright (C) 2004-2007 Clemens Fruhwirth <clemens@endorphin.org>
6  * Copyright (C) 2009-2021 Red Hat, Inc. All rights reserved.
7  * Copyright (C) 2009-2021 Milan Broz
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <sys/utsname.h>
29 #include <errno.h>
30
31 #include "libcryptsetup.h"
32 #include "luks.h"
33 #include "luks2.h"
34 #include "loopaes.h"
35 #include "verity.h"
36 #include "tcrypt.h"
37 #include "integrity.h"
38 #include "bitlk.h"
39 #include "utils_device_locking.h"
40 #include "internal.h"
41
42 #define CRYPT_CD_UNRESTRICTED   (1 << 0)
43 #define CRYPT_CD_QUIET          (1 << 1)
44
45 struct crypt_device {
46         char *type;
47
48         struct device *device;
49         struct device *metadata_device;
50
51         struct volume_key *volume_key;
52         int rng_type;
53         uint32_t compatibility;
54         struct crypt_pbkdf_type pbkdf;
55
56         /* global context scope settings */
57         unsigned key_in_keyring:1;
58
59         uint64_t data_offset;
60         uint64_t metadata_size; /* Used in LUKS2 format */
61         uint64_t keyslots_size; /* Used in LUKS2 format */
62
63         /* Workaround for OOM during parallel activation (like in systemd) */
64         bool memory_hard_pbkdf_lock_enabled;
65         struct crypt_lock_handle *pbkdf_memory_hard_lock;
66
67         // FIXME: private binary headers and access it properly
68         // through sub-library (LUKS1, TCRYPT)
69
70         union {
71         struct { /* used in CRYPT_LUKS1 */
72                 struct luks_phdr hdr;
73                 char *cipher_spec;
74         } luks1;
75         struct { /* used in CRYPT_LUKS2 */
76                 struct luks2_hdr hdr;
77                 char cipher[MAX_CIPHER_LEN];      /* only for compatibility */
78                 char cipher_mode[MAX_CIPHER_LEN]; /* only for compatibility */
79                 char *keyslot_cipher;
80                 unsigned int keyslot_key_size;
81                 struct luks2_reencrypt *rh;
82         } luks2;
83         struct { /* used in CRYPT_PLAIN */
84                 struct crypt_params_plain hdr;
85                 char *cipher_spec;
86                 char *cipher;
87                 const char *cipher_mode;
88                 unsigned int key_size;
89         } plain;
90         struct { /* used in CRYPT_LOOPAES */
91                 struct crypt_params_loopaes hdr;
92                 char *cipher_spec;
93                 char *cipher;
94                 const char *cipher_mode;
95                 unsigned int key_size;
96         } loopaes;
97         struct { /* used in CRYPT_VERITY */
98                 struct crypt_params_verity hdr;
99                 const char *root_hash;
100                 unsigned int root_hash_size;
101                 char *uuid;
102                 struct device *fec_device;
103         } verity;
104         struct { /* used in CRYPT_TCRYPT */
105                 struct crypt_params_tcrypt params;
106                 struct tcrypt_phdr hdr;
107         } tcrypt;
108         struct { /* used in CRYPT_INTEGRITY */
109                 struct crypt_params_integrity params;
110                 struct volume_key *journal_mac_key;
111                 struct volume_key *journal_crypt_key;
112                 uint32_t sb_flags;
113         } integrity;
114         struct { /* used in CRYPT_BITLK */
115                 struct bitlk_metadata params;
116                 char *cipher_spec;
117         } bitlk;
118         struct { /* used if initialized without header by name */
119                 char *active_name;
120                 /* buffers, must refresh from kernel on every query */
121                 char cipher_spec[MAX_CIPHER_LEN*2+1];
122                 char cipher[MAX_CIPHER_LEN];
123                 const char *cipher_mode;
124                 unsigned int key_size;
125         } none;
126         } u;
127
128         /* callbacks definitions */
129         void (*log)(int level, const char *msg, void *usrptr);
130         void *log_usrptr;
131         int (*confirm)(const char *msg, void *usrptr);
132         void *confirm_usrptr;
133 };
134
135 /* Just to suppress redundant messages about crypto backend */
136 static int _crypto_logged = 0;
137
138 /* Log helper */
139 static void (*_default_log)(int level, const char *msg, void *usrptr) = NULL;
140 static int _debug_level = 0;
141
142 /* Library can do metadata locking  */
143 static int _metadata_locking = 1;
144
145 /* Library scope detection for kernel keyring support */
146 static int _kernel_keyring_supported;
147
148 /* Library allowed to use kernel keyring for loading VK in kernel crypto layer */
149 static int _vk_via_keyring = 1;
150
151 void crypt_set_debug_level(int level)
152 {
153         _debug_level = level;
154 }
155
156 int crypt_get_debug_level(void)
157 {
158         return _debug_level;
159 }
160
161 void crypt_log(struct crypt_device *cd, int level, const char *msg)
162 {
163         if (!msg)
164                 return;
165
166         if (level < _debug_level)
167                 return;
168
169         if (cd && cd->log)
170                 cd->log(level, msg, cd->log_usrptr);
171         else if (_default_log)
172                 _default_log(level, msg, NULL);
173         /* Default to stdout/stderr if there is no callback. */
174         else
175                 fprintf(level == CRYPT_LOG_ERROR ? stderr : stdout, "%s", msg);
176 }
177
178 __attribute__((format(printf, 5, 6)))
179 void logger(struct crypt_device *cd, int level, const char *file,
180             int line, const char *format, ...)
181 {
182         va_list argp;
183         char target[LOG_MAX_LEN + 2];
184         int len;
185
186         va_start(argp, format);
187
188         len = vsnprintf(&target[0], LOG_MAX_LEN, format, argp);
189         if (len > 0 && len < LOG_MAX_LEN) {
190                 /* All verbose and error messages in tools end with EOL. */
191                 if (level == CRYPT_LOG_VERBOSE || level == CRYPT_LOG_ERROR ||
192                     level == CRYPT_LOG_DEBUG || level == CRYPT_LOG_DEBUG_JSON)
193                         strncat(target, "\n", LOG_MAX_LEN);
194
195                 crypt_log(cd, level, target);
196         }
197
198         va_end(argp);
199 }
200
201 static const char *mdata_device_path(struct crypt_device *cd)
202 {
203         return device_path(cd->metadata_device ?: cd->device);
204 }
205
206 static const char *data_device_path(struct crypt_device *cd)
207 {
208         return device_path(cd->device);
209 }
210
211 /* internal only */
212 struct device *crypt_metadata_device(struct crypt_device *cd)
213 {
214         return cd->metadata_device ?: cd->device;
215 }
216
217 struct device *crypt_data_device(struct crypt_device *cd)
218 {
219         return cd->device;
220 }
221
222 int init_crypto(struct crypt_device *ctx)
223 {
224         struct utsname uts;
225         int r;
226
227         r = crypt_random_init(ctx);
228         if (r < 0) {
229                 log_err(ctx, _("Cannot initialize crypto RNG backend."));
230                 return r;
231         }
232
233         r = crypt_backend_init();
234         if (r < 0)
235                 log_err(ctx, _("Cannot initialize crypto backend."));
236
237         if (!r && !_crypto_logged) {
238                 log_dbg(ctx, "Crypto backend (%s) initialized in cryptsetup library version %s.",
239                         crypt_backend_version(), PACKAGE_VERSION);
240                 if (!uname(&uts))
241                         log_dbg(ctx, "Detected kernel %s %s %s.",
242                                 uts.sysname, uts.release, uts.machine);
243                 _crypto_logged = 1;
244         }
245
246         return r;
247 }
248
249 static int process_key(struct crypt_device *cd, const char *hash_name,
250                        size_t key_size, const char *pass, size_t passLen,
251                        struct volume_key **vk)
252 {
253         int r;
254
255         if (!key_size)
256                 return -EINVAL;
257
258         *vk = crypt_alloc_volume_key(key_size, NULL);
259         if (!*vk)
260                 return -ENOMEM;
261
262         if (hash_name) {
263                 r = crypt_plain_hash(cd, hash_name, (*vk)->key, key_size, pass, passLen);
264                 if (r < 0) {
265                         if (r == -ENOENT)
266                                 log_err(cd, _("Hash algorithm %s not supported."),
267                                         hash_name);
268                         else
269                                 log_err(cd, _("Key processing error (using hash %s)."),
270                                         hash_name);
271                         crypt_free_volume_key(*vk);
272                         *vk = NULL;
273                         return -EINVAL;
274                 }
275         } else if (passLen > key_size) {
276                 memcpy((*vk)->key, pass, key_size);
277         } else {
278                 memcpy((*vk)->key, pass, passLen);
279         }
280
281         return 0;
282 }
283
284 static int isPLAIN(const char *type)
285 {
286         return (type && !strcmp(CRYPT_PLAIN, type));
287 }
288
289 static int isLUKS1(const char *type)
290 {
291         return (type && !strcmp(CRYPT_LUKS1, type));
292 }
293
294 static int isLUKS2(const char *type)
295 {
296         return (type && !strcmp(CRYPT_LUKS2, type));
297 }
298
299 static int isLUKS(const char *type)
300 {
301         return (isLUKS2(type) || isLUKS1(type));
302 }
303
304 static int isLOOPAES(const char *type)
305 {
306         return (type && !strcmp(CRYPT_LOOPAES, type));
307 }
308
309 static int isVERITY(const char *type)
310 {
311         return (type && !strcmp(CRYPT_VERITY, type));
312 }
313
314 static int isTCRYPT(const char *type)
315 {
316         return (type && !strcmp(CRYPT_TCRYPT, type));
317 }
318
319 static int isINTEGRITY(const char *type)
320 {
321         return (type && !strcmp(CRYPT_INTEGRITY, type));
322 }
323
324 static int isBITLK(const char *type)
325 {
326         return (type && !strcmp(CRYPT_BITLK, type));
327 }
328
329 static int _onlyLUKS(struct crypt_device *cd, uint32_t cdflags)
330 {
331         int r = 0;
332
333         if (cd && !cd->type) {
334                 if (!(cdflags & CRYPT_CD_QUIET))
335                         log_err(cd, _("Cannot determine device type. Incompatible activation of device?"));
336                 r = -EINVAL;
337         }
338
339         if (!cd || !isLUKS(cd->type)) {
340                 if (!(cdflags & CRYPT_CD_QUIET))
341                         log_err(cd, _("This operation is supported only for LUKS device."));
342                 r = -EINVAL;
343         }
344
345         if (r || (cdflags & CRYPT_CD_UNRESTRICTED) || isLUKS1(cd->type))
346                 return r;
347
348         return LUKS2_unmet_requirements(cd, &cd->u.luks2.hdr, 0, cdflags & CRYPT_CD_QUIET);
349 }
350
351 static int onlyLUKS(struct crypt_device *cd)
352 {
353         return _onlyLUKS(cd, 0);
354 }
355
356 static int _onlyLUKS2(struct crypt_device *cd, uint32_t cdflags, uint32_t mask)
357 {
358         int r = 0;
359
360         if (cd && !cd->type) {
361                 if (!(cdflags & CRYPT_CD_QUIET))
362                         log_err(cd, _("Cannot determine device type. Incompatible activation of device?"));
363                 r = -EINVAL;
364         }
365
366         if (!cd || !isLUKS2(cd->type)) {
367                 if (!(cdflags & CRYPT_CD_QUIET))
368                         log_err(cd, _("This operation is supported only for LUKS2 device."));
369                 r = -EINVAL;
370         }
371
372         if (r || (cdflags & CRYPT_CD_UNRESTRICTED))
373                 return r;
374
375         return LUKS2_unmet_requirements(cd, &cd->u.luks2.hdr, mask, cdflags & CRYPT_CD_QUIET);
376 }
377
378 /* Internal only */
379 int onlyLUKS2(struct crypt_device *cd)
380 {
381         return _onlyLUKS2(cd, 0, 0);
382 }
383
384 /* Internal only */
385 int onlyLUKS2mask(struct crypt_device *cd, uint32_t mask)
386 {
387         return _onlyLUKS2(cd, 0, mask);
388 }
389
390 static void crypt_set_null_type(struct crypt_device *cd)
391 {
392         if (!cd->type)
393                 return;
394
395         free(cd->type);
396         cd->type = NULL;
397         cd->u.none.active_name = NULL;
398         cd->data_offset = 0;
399         cd->metadata_size = 0;
400         cd->keyslots_size = 0;
401 }
402
403 static void crypt_reset_null_type(struct crypt_device *cd)
404 {
405         if (cd->type)
406                 return;
407
408         free(cd->u.none.active_name);
409         cd->u.none.active_name = NULL;
410 }
411
412 /* keyslot helpers */
413 static int keyslot_verify_or_find_empty(struct crypt_device *cd, int *keyslot)
414 {
415         crypt_keyslot_info ki;
416
417         if (*keyslot == CRYPT_ANY_SLOT) {
418                 if (isLUKS1(cd->type))
419                         *keyslot = LUKS_keyslot_find_empty(&cd->u.luks1.hdr);
420                 else
421                         *keyslot = LUKS2_keyslot_find_empty(&cd->u.luks2.hdr);
422                 if (*keyslot < 0) {
423                         log_err(cd, _("All key slots full."));
424                         return -EINVAL;
425                 }
426         }
427
428         if (isLUKS1(cd->type))
429                 ki = LUKS_keyslot_info(&cd->u.luks1.hdr, *keyslot);
430         else
431                 ki = LUKS2_keyslot_info(&cd->u.luks2.hdr, *keyslot);
432         switch (ki) {
433                 case CRYPT_SLOT_INVALID:
434                         log_err(cd, _("Key slot %d is invalid, please select between 0 and %d."),
435                                 *keyslot, LUKS_NUMKEYS - 1);
436                         return -EINVAL;
437                 case CRYPT_SLOT_INACTIVE:
438                         break;
439                 default:
440                         log_err(cd, _("Key slot %d is full, please select another one."),
441                                 *keyslot);
442                         return -EINVAL;
443         }
444
445         log_dbg(cd, "Selected keyslot %d.", *keyslot);
446         return 0;
447 }
448
449 /*
450  * compares UUIDs returned by device-mapper (striped by cryptsetup) and uuid in header
451  */
452 int crypt_uuid_cmp(const char *dm_uuid, const char *hdr_uuid)
453 {
454         int i, j;
455         char *str;
456
457         if (!dm_uuid || !hdr_uuid)
458                 return -EINVAL;
459
460         str = strchr(dm_uuid, '-');
461         if (!str)
462                 return -EINVAL;
463
464         for (i = 0, j = 1; hdr_uuid[i]; i++) {
465                 if (hdr_uuid[i] == '-')
466                         continue;
467
468                 if (!str[j] || str[j] == '-')
469                         return -EINVAL;
470
471                 if (str[j] != hdr_uuid[i])
472                         return -EINVAL;
473                 j++;
474         }
475
476         return 0;
477 }
478
479 /*
480  * compares type of active device to provided string (only if there is no explicit type)
481  */
482 static int crypt_uuid_type_cmp(struct crypt_device *cd, const char *type)
483 {
484         struct crypt_dm_active_device dmd;
485         size_t len;
486         int r;
487
488         /* Must user header-on-disk if we know type here */
489         if (cd->type || !cd->u.none.active_name)
490                 return -EINVAL;
491
492         log_dbg(cd, "Checking if active device %s without header has UUID type %s.",
493                 cd->u.none.active_name, type);
494
495         r = dm_query_device(cd, cd->u.none.active_name, DM_ACTIVE_UUID, &dmd);
496         if (r < 0)
497                 return r;
498
499         r = -ENODEV;
500         len = strlen(type);
501         if (dmd.uuid && strlen(dmd.uuid) > len &&
502             !strncmp(dmd.uuid, type, len) && dmd.uuid[len] == '-')
503                 r = 0;
504
505         free(CONST_CAST(void*)dmd.uuid);
506         return r;
507 }
508
509 int PLAIN_activate(struct crypt_device *cd,
510                      const char *name,
511                      struct volume_key *vk,
512                      uint64_t size,
513                      uint32_t flags)
514 {
515         int r;
516         struct crypt_dm_active_device dmd = {
517                 .flags = flags,
518                 .size = size,
519         };
520
521         log_dbg(cd, "Trying to activate PLAIN device %s using cipher %s.",
522                 name, crypt_get_cipher_spec(cd));
523
524         if (MISALIGNED(size, device_block_size(cd, crypt_data_device(cd)) >> SECTOR_SHIFT)) {
525                 log_err(cd, _("Device size is not aligned to device logical block size."));
526                 return -EINVAL;
527         }
528
529         r = dm_crypt_target_set(&dmd.segment, 0, dmd.size, crypt_data_device(cd),
530                         vk, crypt_get_cipher_spec(cd), crypt_get_iv_offset(cd),
531                         crypt_get_data_offset(cd), crypt_get_integrity(cd),
532                         crypt_get_integrity_tag_size(cd), crypt_get_sector_size(cd));
533         if (r < 0)
534                 return r;
535
536         r = create_or_reload_device(cd, name, CRYPT_PLAIN, &dmd);
537
538         dm_targets_free(cd, &dmd);
539         return r;
540 }
541
542 int crypt_confirm(struct crypt_device *cd, const char *msg)
543 {
544         if (!cd || !cd->confirm)
545                 return 1;
546         else
547                 return cd->confirm(msg, cd->confirm_usrptr);
548 }
549
550 void crypt_set_log_callback(struct crypt_device *cd,
551         void (*log)(int level, const char *msg, void *usrptr),
552         void *usrptr)
553 {
554         if (!cd)
555                 _default_log = log;
556         else {
557                 cd->log = log;
558                 cd->log_usrptr = usrptr;
559         }
560 }
561
562 void crypt_set_confirm_callback(struct crypt_device *cd,
563         int (*confirm)(const char *msg, void *usrptr),
564         void *usrptr)
565 {
566         if (cd) {
567                 cd->confirm = confirm;
568                 cd->confirm_usrptr = usrptr;
569         }
570 }
571
572 const char *crypt_get_dir(void)
573 {
574         return dm_get_dir();
575 }
576
577 int crypt_init(struct crypt_device **cd, const char *device)
578 {
579         struct crypt_device *h = NULL;
580         int r;
581
582         if (!cd)
583                 return -EINVAL;
584
585         log_dbg(NULL, "Allocating context for crypt device %s.", device ?: "(none)");
586 #if !HAVE_DECL_O_CLOEXEC
587         log_dbg(NULL, "Running without O_CLOEXEC.");
588 #endif
589
590         if (!(h = malloc(sizeof(struct crypt_device))))
591                 return -ENOMEM;
592
593         memset(h, 0, sizeof(*h));
594
595         r = device_alloc(NULL, &h->device, device);
596         if (r < 0)
597                 goto bad;
598
599         dm_backend_init(NULL);
600
601         h->rng_type = crypt_random_default_key_rng();
602
603         *cd = h;
604         return 0;
605 bad:
606         device_free(NULL, h->device);
607         free(h);
608         return r;
609 }
610
611 static int crypt_check_data_device_size(struct crypt_device *cd)
612 {
613         int r;
614         uint64_t size, size_min;
615
616         /* Check data device size, require at least header or one sector */
617         size_min = crypt_get_data_offset(cd) << SECTOR_SHIFT ?: SECTOR_SIZE;
618
619         r = device_size(cd->device, &size);
620         if (r < 0)
621                 return r;
622
623         if (size < size_min) {
624                 log_err(cd, _("Header detected but device %s is too small."),
625                         device_path(cd->device));
626                 return -EINVAL;
627         }
628
629         return r;
630 }
631
632 static int _crypt_set_data_device(struct crypt_device *cd, const char *device)
633 {
634         struct device *dev = NULL;
635         int r;
636
637         r = device_alloc(cd, &dev, device);
638         if (r < 0)
639                 return r;
640
641         if (!cd->metadata_device) {
642                 cd->metadata_device = cd->device;
643         } else
644                 device_free(cd, cd->device);
645
646         cd->device = dev;
647
648         return crypt_check_data_device_size(cd);
649 }
650
651 int crypt_set_data_device(struct crypt_device *cd, const char *device)
652 {
653         /* metadata device must be set */
654         if (!cd || !cd->device || !device)
655                 return -EINVAL;
656
657         log_dbg(cd, "Setting ciphertext data device to %s.", device ?: "(none)");
658
659         if (!isLUKS1(cd->type) && !isLUKS2(cd->type) && !isVERITY(cd->type) &&
660             !isINTEGRITY(cd->type) && !isTCRYPT(cd->type)) {
661                 log_err(cd, _("This operation is not supported for this device type."));
662                 return -EINVAL;
663         }
664
665         if (isLUKS2(cd->type) && crypt_get_luks2_reencrypt(cd)) {
666                 log_err(cd, _("Illegal operation with reencryption in-progress."));
667                 return -EINVAL;
668         }
669
670         return _crypt_set_data_device(cd, device);
671 }
672
673 int crypt_init_data_device(struct crypt_device **cd, const char *device, const char *data_device)
674 {
675         int r;
676
677         if (!cd)
678                 return -EINVAL;
679
680         r = crypt_init(cd, device);
681         if (r || !data_device || !strcmp(device, data_device))
682                 return r;
683
684         log_dbg(NULL, "Setting ciphertext data device to %s.", data_device);
685         r = _crypt_set_data_device(*cd, data_device);
686         if (r) {
687                 crypt_free(*cd);
688                 *cd = NULL;
689         }
690
691         return r;
692 }
693
694
695 /* internal only */
696 struct crypt_pbkdf_type *crypt_get_pbkdf(struct crypt_device *cd)
697 {
698         return &cd->pbkdf;
699 }
700
701 /*
702  * crypt_load() helpers
703  */
704 static int _crypt_load_luks2(struct crypt_device *cd, int reload, int repair)
705 {
706         int r;
707         char *type = NULL;
708         struct luks2_hdr hdr2 = {};
709
710         log_dbg(cd, "%soading LUKS2 header (repair %sabled).", reload ? "Rel" : "L", repair ? "en" : "dis");
711
712         r = LUKS2_hdr_read(cd, &hdr2, repair);
713         if (r)
714                 return r;
715
716         if (!reload && !(type = strdup(CRYPT_LUKS2))) {
717                 r = -ENOMEM;
718                 goto out;
719         }
720
721         if (verify_pbkdf_params(cd, &cd->pbkdf)) {
722                 r = init_pbkdf_type(cd, NULL, CRYPT_LUKS2);
723                 if (r)
724                         goto out;
725         }
726
727         if (reload) {
728                 LUKS2_hdr_free(cd, &cd->u.luks2.hdr);
729                 free(cd->u.luks2.keyslot_cipher);
730         } else
731                 cd->type = type;
732
733         r = 0;
734         memcpy(&cd->u.luks2.hdr, &hdr2, sizeof(hdr2));
735         cd->u.luks2.keyslot_cipher = NULL;
736         cd->u.luks2.rh = NULL;
737
738 out:
739         if (r) {
740                 free(type);
741                 LUKS2_hdr_free(cd, &hdr2);
742         }
743         return r;
744 }
745
746 static void _luks2_reload(struct crypt_device *cd)
747 {
748         if (!cd || !isLUKS2(cd->type))
749                 return;
750
751         (void) _crypt_load_luks2(cd, 1, 0);
752 }
753
754 static int _crypt_load_luks(struct crypt_device *cd, const char *requested_type,
755                             int require_header, int repair)
756 {
757         char *cipher_spec;
758         struct luks_phdr hdr = {};
759         int r, version;
760
761         r = init_crypto(cd);
762         if (r < 0)
763                 return r;
764
765         /* This will return 0 if primary LUKS2 header is damaged */
766         version = LUKS2_hdr_version_unlocked(cd, NULL);
767
768         if ((isLUKS1(requested_type) && version == 2) ||
769             (isLUKS2(requested_type) && version == 1))
770                 return -EINVAL;
771
772         if (requested_type)
773                 version = 0;
774
775         if (isLUKS1(requested_type) || version == 1) {
776                 if (cd->type && isLUKS2(cd->type)) {
777                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
778                         return -EINVAL;
779                 }
780
781                 if (verify_pbkdf_params(cd, &cd->pbkdf)) {
782                         r = init_pbkdf_type(cd, NULL, CRYPT_LUKS1);
783                         if (r)
784                                 return r;
785                 }
786
787                 r = LUKS_read_phdr(&hdr, require_header, repair, cd);
788                 if (r)
789                         goto out;
790
791                 if (!cd->type && !(cd->type = strdup(CRYPT_LUKS1))) {
792                         r = -ENOMEM;
793                         goto out;
794                 }
795
796                 /* Set hash to the same as in the loaded header */
797                 if (!cd->pbkdf.hash || strcmp(cd->pbkdf.hash, hdr.hashSpec)) {
798                         free(CONST_CAST(void*)cd->pbkdf.hash);
799                         cd->pbkdf.hash = strdup(hdr.hashSpec);
800                         if (!cd->pbkdf.hash) {
801                                 r = -ENOMEM;
802                                 goto out;
803                         }
804                 }
805
806                 if (asprintf(&cipher_spec, "%s-%s", hdr.cipherName, hdr.cipherMode) < 0) {
807                         r = -ENOMEM;
808                         goto out;
809                 }
810
811                 free(cd->u.luks1.cipher_spec);
812                 cd->u.luks1.cipher_spec = cipher_spec;
813
814                 memcpy(&cd->u.luks1.hdr, &hdr, sizeof(hdr));
815         } else if (isLUKS2(requested_type) || version == 2 || version == 0) {
816                 if (cd->type && isLUKS1(cd->type)) {
817                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
818                         return -EINVAL;
819                 }
820
821                 /*
822                  * Current LUKS2 repair just overrides blkid probes
823                  * and perform auto-recovery if possible. This is safe
824                  * unless future LUKS2 repair code do something more
825                  * sophisticated. In such case we would need to check
826                  * for LUKS2 requirements and decide if it's safe to
827                  * perform repair.
828                  */
829                 r =  _crypt_load_luks2(cd, cd->type != NULL, repair);
830         } else {
831                 if (version > 2)
832                         log_err(cd, _("Unsupported LUKS version %d."), version);
833                 r = -EINVAL;
834         }
835 out:
836         crypt_safe_memzero(&hdr, sizeof(hdr));
837
838         return r;
839 }
840
841 static int _crypt_load_tcrypt(struct crypt_device *cd, struct crypt_params_tcrypt *params)
842 {
843         int r;
844
845         if (!params)
846                 return -EINVAL;
847
848         r = init_crypto(cd);
849         if (r < 0)
850                 return r;
851
852         memcpy(&cd->u.tcrypt.params, params, sizeof(*params));
853
854         r = TCRYPT_read_phdr(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
855
856         cd->u.tcrypt.params.passphrase = NULL;
857         cd->u.tcrypt.params.passphrase_size = 0;
858         cd->u.tcrypt.params.keyfiles = NULL;
859         cd->u.tcrypt.params.keyfiles_count = 0;
860         cd->u.tcrypt.params.veracrypt_pim = 0;
861
862         if (r < 0)
863                 return r;
864
865         if (!cd->type && !(cd->type = strdup(CRYPT_TCRYPT)))
866                 return -ENOMEM;
867
868         return r;
869 }
870
871 static int _crypt_load_verity(struct crypt_device *cd, struct crypt_params_verity *params)
872 {
873         int r;
874         size_t sb_offset = 0;
875
876         r = init_crypto(cd);
877         if (r < 0)
878                 return r;
879
880         if (params && params->flags & CRYPT_VERITY_NO_HEADER)
881                 return -EINVAL;
882
883         if (params)
884                 sb_offset = params->hash_area_offset;
885
886         r = VERITY_read_sb(cd, sb_offset, &cd->u.verity.uuid, &cd->u.verity.hdr);
887         if (r < 0)
888                 return r;
889
890         //FIXME: use crypt_free
891         if (!cd->type && !(cd->type = strdup(CRYPT_VERITY))) {
892                 free(CONST_CAST(void*)cd->u.verity.hdr.hash_name);
893                 free(CONST_CAST(void*)cd->u.verity.hdr.salt);
894                 free(cd->u.verity.uuid);
895                 crypt_safe_memzero(&cd->u.verity.hdr, sizeof(cd->u.verity.hdr));
896                 return -ENOMEM;
897         }
898
899         if (params)
900                 cd->u.verity.hdr.flags = params->flags;
901
902         /* Hash availability checked in sb load */
903         cd->u.verity.root_hash_size = crypt_hash_size(cd->u.verity.hdr.hash_name);
904         if (cd->u.verity.root_hash_size > 4096)
905                 return -EINVAL;
906
907         if (params && params->data_device &&
908             (r = crypt_set_data_device(cd, params->data_device)) < 0)
909                 return r;
910
911         if (params && params->fec_device) {
912                 r = device_alloc(cd, &cd->u.verity.fec_device, params->fec_device);
913                 if (r < 0)
914                         return r;
915                 cd->u.verity.hdr.fec_area_offset = params->fec_area_offset;
916                 cd->u.verity.hdr.fec_roots = params->fec_roots;
917         }
918
919         return r;
920 }
921
922 static int _crypt_load_integrity(struct crypt_device *cd,
923                                  struct crypt_params_integrity *params)
924 {
925         int r;
926
927         r = init_crypto(cd);
928         if (r < 0)
929                 return r;
930
931         r = INTEGRITY_read_sb(cd, &cd->u.integrity.params, &cd->u.integrity.sb_flags);
932         if (r < 0)
933                 return r;
934
935         // FIXME: add checks for fields in integrity sb vs params
936
937         if (params) {
938                 cd->u.integrity.params.journal_watermark = params->journal_watermark;
939                 cd->u.integrity.params.journal_commit_time = params->journal_commit_time;
940                 cd->u.integrity.params.buffer_sectors = params->buffer_sectors;
941                 // FIXME: check ENOMEM
942                 if (params->integrity)
943                         cd->u.integrity.params.integrity = strdup(params->integrity);
944                 cd->u.integrity.params.integrity_key_size = params->integrity_key_size;
945                 if (params->journal_integrity)
946                         cd->u.integrity.params.journal_integrity = strdup(params->journal_integrity);
947                 if (params->journal_crypt)
948                         cd->u.integrity.params.journal_crypt = strdup(params->journal_crypt);
949
950                 if (params->journal_crypt_key) {
951                         cd->u.integrity.journal_crypt_key =
952                                 crypt_alloc_volume_key(params->journal_crypt_key_size,
953                                                        params->journal_crypt_key);
954                         if (!cd->u.integrity.journal_crypt_key)
955                                 return -ENOMEM;
956                 }
957                 if (params->journal_integrity_key) {
958                         cd->u.integrity.journal_mac_key =
959                                 crypt_alloc_volume_key(params->journal_integrity_key_size,
960                                                        params->journal_integrity_key);
961                         if (!cd->u.integrity.journal_mac_key)
962                                 return -ENOMEM;
963                 }
964         }
965
966         if (!cd->type && !(cd->type = strdup(CRYPT_INTEGRITY))) {
967                 free(CONST_CAST(void*)cd->u.integrity.params.integrity);
968                 return -ENOMEM;
969         }
970
971         return 0;
972 }
973
974 static int _crypt_load_bitlk(struct crypt_device *cd,
975                              struct bitlk_metadata *params)
976 {
977         int r;
978
979         r = init_crypto(cd);
980         if (r < 0)
981                 return r;
982
983         r = BITLK_read_sb(cd, &cd->u.bitlk.params);
984         if (r < 0)
985                 return r;
986
987         if (asprintf(&cd->u.bitlk.cipher_spec, "%s-%s",
988                      cd->u.bitlk.params.cipher, cd->u.bitlk.params.cipher_mode) < 0) {
989                 cd->u.bitlk.cipher_spec = NULL;
990                 return -ENOMEM;
991         }
992
993         if (!cd->type && !(cd->type = strdup(CRYPT_BITLK)))
994                 return -ENOMEM;
995
996         return 0;
997 }
998
999 int crypt_load(struct crypt_device *cd,
1000                const char *requested_type,
1001                void *params)
1002 {
1003         int r;
1004
1005         if (!cd)
1006                 return -EINVAL;
1007
1008         log_dbg(cd, "Trying to load %s crypt type from device %s.",
1009                 requested_type ?: "any", mdata_device_path(cd) ?: "(none)");
1010
1011         if (!crypt_metadata_device(cd))
1012                 return -EINVAL;
1013
1014         crypt_reset_null_type(cd);
1015         cd->data_offset = 0;
1016         cd->metadata_size = 0;
1017         cd->keyslots_size = 0;
1018
1019         if (!requested_type || isLUKS1(requested_type) || isLUKS2(requested_type)) {
1020                 if (cd->type && !isLUKS1(cd->type) && !isLUKS2(cd->type)) {
1021                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1022                         return -EINVAL;
1023                 }
1024
1025                 r = _crypt_load_luks(cd, requested_type, 1, 0);
1026         } else if (isVERITY(requested_type)) {
1027                 if (cd->type && !isVERITY(cd->type)) {
1028                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1029                         return -EINVAL;
1030                 }
1031                 r = _crypt_load_verity(cd, params);
1032         } else if (isTCRYPT(requested_type)) {
1033                 if (cd->type && !isTCRYPT(cd->type)) {
1034                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1035                         return -EINVAL;
1036                 }
1037                 r = _crypt_load_tcrypt(cd, params);
1038         } else if (isINTEGRITY(requested_type)) {
1039                 if (cd->type && !isINTEGRITY(cd->type)) {
1040                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1041                         return -EINVAL;
1042                 }
1043                 r = _crypt_load_integrity(cd, params);
1044         } else if (isBITLK(requested_type)) {
1045                 if (cd->type && !isBITLK(cd->type)) {
1046                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1047                         return -EINVAL;
1048                 }
1049                 r = _crypt_load_bitlk(cd, params);
1050         } else
1051                 return -EINVAL;
1052
1053         return r;
1054 }
1055
1056 /*
1057  * crypt_init() helpers
1058  */
1059 static int _init_by_name_crypt_none(struct crypt_device *cd)
1060 {
1061         int r;
1062         char _mode[MAX_CIPHER_LEN];
1063         struct crypt_dm_active_device dmd;
1064         struct dm_target *tgt = &dmd.segment;
1065
1066         if (cd->type || !cd->u.none.active_name)
1067                 return -EINVAL;
1068
1069         r = dm_query_device(cd, cd->u.none.active_name,
1070                         DM_ACTIVE_CRYPT_CIPHER |
1071                         DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
1072         if (r < 0)
1073                 return r;
1074         if (!single_segment(&dmd) || tgt->type != DM_CRYPT)
1075                 r = -EINVAL;
1076         if (r >= 0)
1077                 r = crypt_parse_name_and_mode(tgt->u.crypt.cipher,
1078                                               cd->u.none.cipher, NULL,
1079                                               _mode);
1080
1081         if (!r) {
1082                 r = snprintf(cd->u.none.cipher_spec, sizeof(cd->u.none.cipher_spec),
1083                          "%s-%s", cd->u.none.cipher, _mode);
1084                 if (r < 0 || (size_t)r >= sizeof(cd->u.none.cipher_spec))
1085                         r = -EINVAL;
1086                 else {
1087                         cd->u.none.cipher_mode = cd->u.none.cipher_spec + strlen(cd->u.none.cipher) + 1;
1088                         cd->u.none.key_size = tgt->u.crypt.vk->keylength;
1089                         r = 0;
1090                 }
1091         }
1092
1093         dm_targets_free(cd, &dmd);
1094         return r;
1095 }
1096
1097 static const char *LUKS_UUID(struct crypt_device *cd)
1098 {
1099         if (!cd)
1100                 return NULL;
1101         else if (isLUKS1(cd->type))
1102                 return cd->u.luks1.hdr.uuid;
1103         else if (isLUKS2(cd->type))
1104                 return cd->u.luks2.hdr.uuid;
1105
1106         return NULL;
1107 }
1108
1109 static void crypt_free_type(struct crypt_device *cd)
1110 {
1111         if (isPLAIN(cd->type)) {
1112                 free(CONST_CAST(void*)cd->u.plain.hdr.hash);
1113                 free(cd->u.plain.cipher);
1114                 free(cd->u.plain.cipher_spec);
1115         } else if (isLUKS2(cd->type)) {
1116                 LUKS2_reencrypt_free(cd, cd->u.luks2.rh);
1117                 LUKS2_hdr_free(cd, &cd->u.luks2.hdr);
1118                 free(cd->u.luks2.keyslot_cipher);
1119         } else if (isLUKS1(cd->type)) {
1120                 free(cd->u.luks1.cipher_spec);
1121         } else if (isLOOPAES(cd->type)) {
1122                 free(CONST_CAST(void*)cd->u.loopaes.hdr.hash);
1123                 free(cd->u.loopaes.cipher);
1124                 free(cd->u.loopaes.cipher_spec);
1125         } else if (isVERITY(cd->type)) {
1126                 free(CONST_CAST(void*)cd->u.verity.hdr.hash_name);
1127                 free(CONST_CAST(void*)cd->u.verity.hdr.data_device);
1128                 free(CONST_CAST(void*)cd->u.verity.hdr.hash_device);
1129                 free(CONST_CAST(void*)cd->u.verity.hdr.fec_device);
1130                 free(CONST_CAST(void*)cd->u.verity.hdr.salt);
1131                 free(CONST_CAST(void*)cd->u.verity.root_hash);
1132                 free(cd->u.verity.uuid);
1133                 device_free(cd, cd->u.verity.fec_device);
1134         } else if (isINTEGRITY(cd->type)) {
1135                 free(CONST_CAST(void*)cd->u.integrity.params.integrity);
1136                 free(CONST_CAST(void*)cd->u.integrity.params.journal_integrity);
1137                 free(CONST_CAST(void*)cd->u.integrity.params.journal_crypt);
1138                 crypt_free_volume_key(cd->u.integrity.journal_crypt_key);
1139                 crypt_free_volume_key(cd->u.integrity.journal_mac_key);
1140         } else if (isBITLK(cd->type)) {
1141                 free(cd->u.bitlk.cipher_spec);
1142                 BITLK_bitlk_metadata_free(&cd->u.bitlk.params);
1143         } else if (!cd->type) {
1144                 free(cd->u.none.active_name);
1145                 cd->u.none.active_name = NULL;
1146         }
1147
1148         crypt_set_null_type(cd);
1149 }
1150
1151 static int _init_by_name_crypt(struct crypt_device *cd, const char *name)
1152 {
1153         bool found = false;
1154         char **dep, *cipher_spec = NULL, cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN], deps_uuid_prefix[40], *deps[MAX_DM_DEPS+1] = {};
1155         const char *dev, *namei;
1156         int key_nums, r;
1157         struct crypt_dm_active_device dmd, dmdi = {}, dmdep = {};
1158         struct dm_target *tgt = &dmd.segment, *tgti = &dmdi.segment;
1159
1160         r = dm_query_device(cd, name,
1161                         DM_ACTIVE_DEVICE |
1162                         DM_ACTIVE_UUID |
1163                         DM_ACTIVE_CRYPT_CIPHER |
1164                         DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
1165         if (r < 0)
1166                 return r;
1167
1168         if (tgt->type != DM_CRYPT && tgt->type != DM_LINEAR) {
1169                 log_dbg(cd, "Unsupported device table detected in %s.", name);
1170                 r = -EINVAL;
1171                 goto out;
1172         }
1173
1174         r = -EINVAL;
1175
1176         if (dmd.uuid) {
1177                 r = snprintf(deps_uuid_prefix, sizeof(deps_uuid_prefix), CRYPT_SUBDEV "-%.32s", dmd.uuid + 6);
1178                 if (r < 0 || (size_t)r != (sizeof(deps_uuid_prefix) - 1))
1179                         r = -EINVAL;
1180         }
1181
1182         if (r >= 0) {
1183                 r = dm_device_deps(cd, name, deps_uuid_prefix, deps, ARRAY_SIZE(deps));
1184                 if (r)
1185                         goto out;
1186         }
1187
1188         r = crypt_parse_name_and_mode(tgt->type == DM_LINEAR ? "null" : tgt->u.crypt.cipher, cipher,
1189                                       &key_nums, cipher_mode);
1190         if (r < 0) {
1191                 log_dbg(cd, "Cannot parse cipher and mode from active device.");
1192                 goto out;
1193         }
1194
1195         dep = deps;
1196
1197         if (tgt->type == DM_CRYPT && tgt->u.crypt.integrity && (namei = device_dm_name(tgt->data_device))) {
1198                 r = dm_query_device(cd, namei, DM_ACTIVE_DEVICE, &dmdi);
1199                 if (r < 0)
1200                         goto out;
1201                 if (!single_segment(&dmdi) || tgti->type != DM_INTEGRITY) {
1202                         log_dbg(cd, "Unsupported device table detected in %s.", namei);
1203                         r = -EINVAL;
1204                         goto out;
1205                 }
1206                 if (!cd->metadata_device) {
1207                         device_free(cd, cd->device);
1208                         MOVE_REF(cd->device, tgti->data_device);
1209                 }
1210         }
1211
1212         /* do not try to lookup LUKS2 header in detached header mode */
1213         if (dmd.uuid && !cd->metadata_device && !found) {
1214                 while (*dep && !found) {
1215                         r = dm_query_device(cd, *dep, DM_ACTIVE_DEVICE, &dmdep);
1216                         if (r < 0)
1217                                 goto out;
1218
1219                         tgt = &dmdep.segment;
1220
1221                         while (tgt && !found) {
1222                                 dev = device_path(tgt->data_device);
1223                                 if (!dev) {
1224                                         tgt = tgt->next;
1225                                         continue;
1226                                 }
1227                                 if (!strstr(dev, dm_get_dir()) ||
1228                                     !crypt_string_in(dev + strlen(dm_get_dir()) + 1, deps, ARRAY_SIZE(deps))) {
1229                                         device_free(cd, cd->device);
1230                                         MOVE_REF(cd->device, tgt->data_device);
1231                                         found = true;
1232                                 }
1233                                 tgt = tgt->next;
1234                         }
1235                         dep++;
1236                         dm_targets_free(cd, &dmdep);
1237                 }
1238         }
1239
1240         if (asprintf(&cipher_spec, "%s-%s", cipher, cipher_mode) < 0) {
1241                 cipher_spec = NULL;
1242                 r = -ENOMEM;
1243                 goto out;
1244         }
1245
1246         tgt = &dmd.segment;
1247         r = 0;
1248
1249         if (isPLAIN(cd->type) && single_segment(&dmd) && tgt->type == DM_CRYPT) {
1250                 cd->u.plain.hdr.hash = NULL; /* no way to get this */
1251                 cd->u.plain.hdr.offset = tgt->u.crypt.offset;
1252                 cd->u.plain.hdr.skip = tgt->u.crypt.iv_offset;
1253                 cd->u.plain.hdr.sector_size = tgt->u.crypt.sector_size;
1254                 cd->u.plain.key_size = tgt->u.crypt.vk->keylength;
1255                 cd->u.plain.cipher = strdup(cipher);
1256                 MOVE_REF(cd->u.plain.cipher_spec, cipher_spec);
1257                 cd->u.plain.cipher_mode = cd->u.plain.cipher_spec + strlen(cipher) + 1;
1258         } else if (isLOOPAES(cd->type) && single_segment(&dmd) && tgt->type == DM_CRYPT) {
1259                 cd->u.loopaes.hdr.offset = tgt->u.crypt.offset;
1260                 cd->u.loopaes.cipher = strdup(cipher);
1261                 MOVE_REF(cd->u.loopaes.cipher_spec, cipher_spec);
1262                 cd->u.loopaes.cipher_mode = cd->u.loopaes.cipher_spec + strlen(cipher) + 1;
1263                 /* version 3 uses last key for IV */
1264                 if (tgt->u.crypt.vk->keylength % key_nums)
1265                         key_nums++;
1266                 cd->u.loopaes.key_size = tgt->u.crypt.vk->keylength / key_nums;
1267         } else if (isLUKS1(cd->type) || isLUKS2(cd->type)) {
1268                 if (crypt_metadata_device(cd)) {
1269                         r = _crypt_load_luks(cd, cd->type, 0, 0);
1270                         if (r < 0) {
1271                                 log_dbg(cd, "LUKS device header does not match active device.");
1272                                 crypt_set_null_type(cd);
1273                                 device_close(cd, cd->metadata_device);
1274                                 device_close(cd, cd->device);
1275                                 r = 0;
1276                                 goto out;
1277                         }
1278                         /* check whether UUIDs match each other */
1279                         r = crypt_uuid_cmp(dmd.uuid, LUKS_UUID(cd));
1280                         if (r < 0) {
1281                                 log_dbg(cd, "LUKS device header uuid: %s mismatches DM returned uuid %s",
1282                                         LUKS_UUID(cd), dmd.uuid);
1283                                 crypt_free_type(cd);
1284                                 r = 0;
1285                                 goto out;
1286                         }
1287                 } else {
1288                         log_dbg(cd, "LUKS device header not available.");
1289                         crypt_set_null_type(cd);
1290                         r = 0;
1291                 }
1292         } else if (isTCRYPT(cd->type) && single_segment(&dmd) && tgt->type == DM_CRYPT) {
1293                 r = TCRYPT_init_by_name(cd, name, dmd.uuid, tgt, &cd->device,
1294                                         &cd->u.tcrypt.params, &cd->u.tcrypt.hdr);
1295         } else if (isBITLK(cd->type)) {
1296                 r = _crypt_load_bitlk(cd, NULL);
1297                 if (r < 0) {
1298                         log_dbg(cd, "BITLK device header not available.");
1299                         crypt_set_null_type(cd);
1300                         r = 0;
1301                 }
1302         }
1303 out:
1304         dm_targets_free(cd, &dmd);
1305         dm_targets_free(cd, &dmdi);
1306         dm_targets_free(cd, &dmdep);
1307         free(CONST_CAST(void*)dmd.uuid);
1308         free(cipher_spec);
1309         dep = deps;
1310         while (*dep)
1311                 free(*dep++);
1312         return r;
1313 }
1314
1315 static int _init_by_name_verity(struct crypt_device *cd, const char *name)
1316 {
1317         struct crypt_dm_active_device dmd;
1318         struct dm_target *tgt = &dmd.segment;
1319         int r;
1320
1321         r = dm_query_device(cd, name,
1322                                 DM_ACTIVE_DEVICE |
1323                                 DM_ACTIVE_VERITY_HASH_DEVICE |
1324                                 DM_ACTIVE_VERITY_ROOT_HASH |
1325                                 DM_ACTIVE_VERITY_PARAMS, &dmd);
1326         if (r < 0)
1327                 return r;
1328         if (!single_segment(&dmd) || tgt->type != DM_VERITY) {
1329                 log_dbg(cd, "Unsupported device table detected in %s.", name);
1330                 r = -EINVAL;
1331                 goto out;
1332         }
1333         if (r > 0)
1334                 r = 0;
1335
1336         if (isVERITY(cd->type)) {
1337                 cd->u.verity.uuid = NULL; // FIXME
1338                 cd->u.verity.hdr.flags = CRYPT_VERITY_NO_HEADER; //FIXME
1339                 cd->u.verity.hdr.data_size = tgt->u.verity.vp->data_size;
1340                 cd->u.verity.root_hash_size = tgt->u.verity.root_hash_size;
1341                 MOVE_REF(cd->u.verity.hdr.hash_name, tgt->u.verity.vp->hash_name);
1342                 cd->u.verity.hdr.data_device = NULL;
1343                 cd->u.verity.hdr.hash_device = NULL;
1344                 cd->u.verity.hdr.data_block_size = tgt->u.verity.vp->data_block_size;
1345                 cd->u.verity.hdr.hash_block_size = tgt->u.verity.vp->hash_block_size;
1346                 cd->u.verity.hdr.hash_area_offset = tgt->u.verity.hash_offset;
1347                 cd->u.verity.hdr.fec_area_offset = tgt->u.verity.fec_offset;
1348                 cd->u.verity.hdr.hash_type = tgt->u.verity.vp->hash_type;
1349                 cd->u.verity.hdr.flags = tgt->u.verity.vp->flags;
1350                 cd->u.verity.hdr.salt_size = tgt->u.verity.vp->salt_size;
1351                 MOVE_REF(cd->u.verity.hdr.salt, tgt->u.verity.vp->salt);
1352                 MOVE_REF(cd->u.verity.hdr.fec_device, tgt->u.verity.vp->fec_device);
1353                 cd->u.verity.hdr.fec_roots = tgt->u.verity.vp->fec_roots;
1354                 MOVE_REF(cd->u.verity.fec_device, tgt->u.verity.fec_device);
1355                 MOVE_REF(cd->metadata_device, tgt->u.verity.hash_device);
1356                 MOVE_REF(cd->u.verity.root_hash, tgt->u.verity.root_hash);
1357         }
1358 out:
1359         dm_targets_free(cd, &dmd);
1360         return r;
1361 }
1362
1363 static int _init_by_name_integrity(struct crypt_device *cd, const char *name)
1364 {
1365         struct crypt_dm_active_device dmd;
1366         struct dm_target *tgt = &dmd.segment;
1367         int r;
1368
1369         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE |
1370                                       DM_ACTIVE_CRYPT_KEY |
1371                                       DM_ACTIVE_CRYPT_KEYSIZE |
1372                                       DM_ACTIVE_INTEGRITY_PARAMS, &dmd);
1373         if (r < 0)
1374                 return r;
1375         if (!single_segment(&dmd) || tgt->type != DM_INTEGRITY) {
1376                 log_dbg(cd, "Unsupported device table detected in %s.", name);
1377                 r = -EINVAL;
1378                 goto out;
1379         }
1380         if (r > 0)
1381                 r = 0;
1382
1383         if (isINTEGRITY(cd->type)) {
1384                 cd->u.integrity.params.tag_size = tgt->u.integrity.tag_size;
1385                 cd->u.integrity.params.sector_size = tgt->u.integrity.sector_size;
1386                 cd->u.integrity.params.journal_size = tgt->u.integrity.journal_size;
1387                 cd->u.integrity.params.journal_watermark = tgt->u.integrity.journal_watermark;
1388                 cd->u.integrity.params.journal_commit_time = tgt->u.integrity.journal_commit_time;
1389                 cd->u.integrity.params.interleave_sectors = tgt->u.integrity.interleave_sectors;
1390                 cd->u.integrity.params.buffer_sectors = tgt->u.integrity.buffer_sectors;
1391                 MOVE_REF(cd->u.integrity.params.integrity, tgt->u.integrity.integrity);
1392                 MOVE_REF(cd->u.integrity.params.journal_integrity, tgt->u.integrity.journal_integrity);
1393                 MOVE_REF(cd->u.integrity.params.journal_crypt, tgt->u.integrity.journal_crypt);
1394
1395                 if (tgt->u.integrity.vk)
1396                         cd->u.integrity.params.integrity_key_size = tgt->u.integrity.vk->keylength;
1397                 if (tgt->u.integrity.journal_integrity_key)
1398                         cd->u.integrity.params.journal_integrity_key_size = tgt->u.integrity.journal_integrity_key->keylength;
1399                 if (tgt->u.integrity.journal_crypt_key)
1400                         cd->u.integrity.params.integrity_key_size = tgt->u.integrity.journal_crypt_key->keylength;
1401                 MOVE_REF(cd->metadata_device, tgt->u.integrity.meta_device);
1402         }
1403 out:
1404         dm_targets_free(cd, &dmd);
1405         return r;
1406 }
1407
1408 int crypt_init_by_name_and_header(struct crypt_device **cd,
1409                                   const char *name,
1410                                   const char *header_device)
1411 {
1412         crypt_status_info ci;
1413         struct crypt_dm_active_device dmd;
1414         struct dm_target *tgt = &dmd.segment;
1415         int r;
1416
1417         if (!cd || !name)
1418                 return -EINVAL;
1419
1420         log_dbg(NULL, "Allocating crypt device context by device %s.", name);
1421
1422         ci = crypt_status(NULL, name);
1423         if (ci == CRYPT_INVALID)
1424                 return -ENODEV;
1425
1426         if (ci < CRYPT_ACTIVE) {
1427                 log_err(NULL, _("Device %s is not active."), name);
1428                 return -ENODEV;
1429         }
1430
1431         r = dm_query_device(NULL, name, DM_ACTIVE_DEVICE | DM_ACTIVE_UUID, &dmd);
1432         if (r < 0)
1433                 return r;
1434
1435         *cd = NULL;
1436
1437         if (header_device) {
1438                 r = crypt_init(cd, header_device);
1439         } else {
1440                 r = crypt_init(cd, device_path(tgt->data_device));
1441
1442                 /* Underlying device disappeared but mapping still active */
1443                 if (!tgt->data_device || r == -ENOTBLK)
1444                         log_verbose(NULL, _("Underlying device for crypt device %s disappeared."),
1445                                     name);
1446
1447                 /* Underlying device is not readable but crypt mapping exists */
1448                 if (r == -ENOTBLK)
1449                         r = crypt_init(cd, NULL);
1450         }
1451
1452         if (r < 0)
1453                 goto out;
1454
1455         if (dmd.uuid) {
1456                 if (!strncmp(CRYPT_PLAIN, dmd.uuid, sizeof(CRYPT_PLAIN)-1))
1457                         (*cd)->type = strdup(CRYPT_PLAIN);
1458                 else if (!strncmp(CRYPT_LOOPAES, dmd.uuid, sizeof(CRYPT_LOOPAES)-1))
1459                         (*cd)->type = strdup(CRYPT_LOOPAES);
1460                 else if (!strncmp(CRYPT_LUKS1, dmd.uuid, sizeof(CRYPT_LUKS1)-1))
1461                         (*cd)->type = strdup(CRYPT_LUKS1);
1462                 else if (!strncmp(CRYPT_LUKS2, dmd.uuid, sizeof(CRYPT_LUKS2)-1))
1463                         (*cd)->type = strdup(CRYPT_LUKS2);
1464                 else if (!strncmp(CRYPT_VERITY, dmd.uuid, sizeof(CRYPT_VERITY)-1))
1465                         (*cd)->type = strdup(CRYPT_VERITY);
1466                 else if (!strncmp(CRYPT_TCRYPT, dmd.uuid, sizeof(CRYPT_TCRYPT)-1))
1467                         (*cd)->type = strdup(CRYPT_TCRYPT);
1468                 else if (!strncmp(CRYPT_INTEGRITY, dmd.uuid, sizeof(CRYPT_INTEGRITY)-1))
1469                         (*cd)->type = strdup(CRYPT_INTEGRITY);
1470                 else if (!strncmp(CRYPT_BITLK, dmd.uuid, sizeof(CRYPT_BITLK)-1))
1471                         (*cd)->type = strdup(CRYPT_BITLK);
1472                 else
1473                         log_dbg(NULL, "Unknown UUID set, some parameters are not set.");
1474         } else
1475                 log_dbg(NULL, "Active device has no UUID set, some parameters are not set.");
1476
1477         if (header_device) {
1478                 r = crypt_set_data_device(*cd, device_path(tgt->data_device));
1479                 if (r < 0)
1480                         goto out;
1481         }
1482
1483         /* Try to initialize basic parameters from active device */
1484
1485         if (tgt->type == DM_CRYPT || tgt->type == DM_LINEAR)
1486                 r = _init_by_name_crypt(*cd, name);
1487         else if (tgt->type == DM_VERITY)
1488                 r = _init_by_name_verity(*cd, name);
1489         else if (tgt->type == DM_INTEGRITY)
1490                 r = _init_by_name_integrity(*cd, name);
1491 out:
1492         if (r < 0) {
1493                 crypt_free(*cd);
1494                 *cd = NULL;
1495         } else if (!(*cd)->type) {
1496                 /* For anonymous device (no header found) remember initialized name */
1497                 (*cd)->u.none.active_name = strdup(name);
1498         }
1499
1500         free(CONST_CAST(void*)dmd.uuid);
1501         dm_targets_free(NULL, &dmd);
1502         return r;
1503 }
1504
1505 int crypt_init_by_name(struct crypt_device **cd, const char *name)
1506 {
1507         return crypt_init_by_name_and_header(cd, name, NULL);
1508 }
1509
1510 /*
1511  * crypt_format() helpers
1512  */
1513 static int _crypt_format_plain(struct crypt_device *cd,
1514                                const char *cipher,
1515                                const char *cipher_mode,
1516                                const char *uuid,
1517                                size_t volume_key_size,
1518                                struct crypt_params_plain *params)
1519 {
1520         unsigned int sector_size = params ? params->sector_size : SECTOR_SIZE;
1521         uint64_t dev_size;
1522
1523         if (!cipher || !cipher_mode) {
1524                 log_err(cd, _("Invalid plain crypt parameters."));
1525                 return -EINVAL;
1526         }
1527
1528         if (volume_key_size > 1024) {
1529                 log_err(cd, _("Invalid key size."));
1530                 return -EINVAL;
1531         }
1532
1533         if (uuid) {
1534                 log_err(cd, _("UUID is not supported for this crypt type."));
1535                 return -EINVAL;
1536         }
1537
1538         if (cd->metadata_device) {
1539                 log_err(cd, _("Detached metadata device is not supported for this crypt type."));
1540                 return -EINVAL;
1541         }
1542
1543         /* For compatibility with old params structure */
1544         if (!sector_size)
1545                 sector_size = SECTOR_SIZE;
1546
1547         if (sector_size < SECTOR_SIZE || sector_size > MAX_SECTOR_SIZE ||
1548             NOTPOW2(sector_size)) {
1549                 log_err(cd, _("Unsupported encryption sector size."));
1550                 return -EINVAL;
1551         }
1552
1553         if (sector_size > SECTOR_SIZE && !device_size(cd->device, &dev_size)) {
1554                 if (params && params->offset)
1555                         dev_size -= (params->offset * SECTOR_SIZE);
1556                 if (dev_size % sector_size) {
1557                         log_err(cd, _("Device size is not aligned to requested sector size."));
1558                         return -EINVAL;
1559                 }
1560         }
1561
1562         if (!(cd->type = strdup(CRYPT_PLAIN)))
1563                 return -ENOMEM;
1564
1565         cd->u.plain.key_size = volume_key_size;
1566         cd->volume_key = crypt_alloc_volume_key(volume_key_size, NULL);
1567         if (!cd->volume_key)
1568                 return -ENOMEM;
1569
1570         if (asprintf(&cd->u.plain.cipher_spec, "%s-%s", cipher, cipher_mode) < 0) {
1571                 cd->u.plain.cipher_spec = NULL;
1572                 return -ENOMEM;
1573         }
1574         cd->u.plain.cipher = strdup(cipher);
1575         cd->u.plain.cipher_mode = cd->u.plain.cipher_spec + strlen(cipher) + 1;
1576
1577         if (params && params->hash)
1578                 cd->u.plain.hdr.hash = strdup(params->hash);
1579
1580         cd->u.plain.hdr.offset = params ? params->offset : 0;
1581         cd->u.plain.hdr.skip = params ? params->skip : 0;
1582         cd->u.plain.hdr.size = params ? params->size : 0;
1583         cd->u.plain.hdr.sector_size = sector_size;
1584
1585         if (!cd->u.plain.cipher)
1586                 return -ENOMEM;
1587
1588         return 0;
1589 }
1590
1591 static int _crypt_format_luks1(struct crypt_device *cd,
1592                                const char *cipher,
1593                                const char *cipher_mode,
1594                                const char *uuid,
1595                                const char *volume_key,
1596                                size_t volume_key_size,
1597                                struct crypt_params_luks1 *params)
1598 {
1599         int r;
1600         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
1601         unsigned long alignment_offset = 0;
1602         uint64_t dev_size;
1603
1604         if (!cipher || !cipher_mode)
1605                 return -EINVAL;
1606
1607         if (!crypt_metadata_device(cd)) {
1608                 log_err(cd, _("Can't format LUKS without device."));
1609                 return -EINVAL;
1610         }
1611
1612         if (params && cd->data_offset && params->data_alignment &&
1613            (cd->data_offset % params->data_alignment)) {
1614                 log_err(cd, _("Requested data alignment is not compatible with data offset."));
1615                 return -EINVAL;
1616         }
1617
1618         if (!(cd->type = strdup(CRYPT_LUKS1)))
1619                 return -ENOMEM;
1620
1621         if (volume_key)
1622                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
1623                                                       volume_key);
1624         else
1625                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
1626
1627         if (!cd->volume_key)
1628                 return -ENOMEM;
1629
1630         if (verify_pbkdf_params(cd, &cd->pbkdf)) {
1631                 r = init_pbkdf_type(cd, NULL, CRYPT_LUKS1);
1632                 if (r)
1633                         return r;
1634         }
1635
1636         if (params && params->hash && strcmp(params->hash, cd->pbkdf.hash)) {
1637                 free(CONST_CAST(void*)cd->pbkdf.hash);
1638                 cd->pbkdf.hash = strdup(params->hash);
1639                 if (!cd->pbkdf.hash)
1640                         return -ENOMEM;
1641         }
1642
1643         if (params && params->data_device) {
1644                 if (!cd->metadata_device)
1645                         cd->metadata_device = cd->device;
1646                 else
1647                         device_free(cd, cd->device);
1648                 cd->device = NULL;
1649                 if (device_alloc(cd, &cd->device, params->data_device) < 0)
1650                         return -ENOMEM;
1651         }
1652
1653         if (params && cd->metadata_device) {
1654                 /* For detached header the alignment is used directly as data offset */
1655                 if (!cd->data_offset)
1656                         cd->data_offset = params->data_alignment;
1657                 required_alignment = params->data_alignment * SECTOR_SIZE;
1658         } else if (params && params->data_alignment) {
1659                 required_alignment = params->data_alignment * SECTOR_SIZE;
1660         } else
1661                 device_topology_alignment(cd, cd->device,
1662                                        &required_alignment,
1663                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
1664
1665         r = LUKS_check_cipher(cd, volume_key_size, cipher, cipher_mode);
1666         if (r < 0)
1667                 return r;
1668
1669         r = LUKS_generate_phdr(&cd->u.luks1.hdr, cd->volume_key, cipher, cipher_mode,
1670                                cd->pbkdf.hash, uuid,
1671                                cd->data_offset * SECTOR_SIZE,
1672                                alignment_offset, required_alignment, cd);
1673         if (r < 0)
1674                 return r;
1675
1676         r = device_check_access(cd, crypt_metadata_device(cd), DEV_EXCL);
1677         if (r < 0)
1678                 return r;
1679
1680         if (!device_size(crypt_data_device(cd), &dev_size) &&
1681             dev_size < (crypt_get_data_offset(cd) * SECTOR_SIZE))
1682                 log_std(cd, _("WARNING: Data offset is outside of currently available data device.\n"));
1683
1684         if (asprintf(&cd->u.luks1.cipher_spec, "%s-%s", cipher, cipher_mode) < 0) {
1685                 cd->u.luks1.cipher_spec = NULL;
1686                 return -ENOMEM;
1687         }
1688
1689         r = LUKS_wipe_header_areas(&cd->u.luks1.hdr, cd);
1690         if (r < 0) {
1691                 free(cd->u.luks1.cipher_spec);
1692                 log_err(cd, _("Cannot wipe header on device %s."),
1693                         mdata_device_path(cd));
1694                 return r;
1695         }
1696
1697         r = LUKS_write_phdr(&cd->u.luks1.hdr, cd);
1698         if (r)
1699                 free(cd->u.luks1.cipher_spec);
1700
1701         return r;
1702 }
1703
1704 static int _crypt_format_luks2(struct crypt_device *cd,
1705                                const char *cipher,
1706                                const char *cipher_mode,
1707                                const char *uuid,
1708                                const char *volume_key,
1709                                size_t volume_key_size,
1710                                struct crypt_params_luks2 *params)
1711 {
1712         int r, integrity_key_size = 0;
1713         unsigned long required_alignment = DEFAULT_DISK_ALIGNMENT;
1714         unsigned long alignment_offset = 0;
1715         unsigned int sector_size = params ? params->sector_size : SECTOR_SIZE;
1716         const char *integrity = params ? params->integrity : NULL;
1717         uint64_t dev_size;
1718         uint32_t dmc_flags;
1719
1720         cd->u.luks2.hdr.jobj = NULL;
1721         cd->u.luks2.keyslot_cipher = NULL;
1722
1723         if (!cipher || !cipher_mode)
1724                 return -EINVAL;
1725
1726         if (!crypt_metadata_device(cd)) {
1727                 log_err(cd, _("Can't format LUKS without device."));
1728                 return -EINVAL;
1729         }
1730
1731         if (params && cd->data_offset && params->data_alignment &&
1732            (cd->data_offset % params->data_alignment)) {
1733                 log_err(cd, _("Requested data alignment is not compatible with data offset."));
1734                 return -EINVAL;
1735         }
1736
1737         if (sector_size < SECTOR_SIZE || sector_size > MAX_SECTOR_SIZE ||
1738             NOTPOW2(sector_size)) {
1739                 log_err(cd, _("Unsupported encryption sector size."));
1740                 return -EINVAL;
1741         }
1742         if (sector_size != SECTOR_SIZE && !dm_flags(cd, DM_CRYPT, &dmc_flags) &&
1743             !(dmc_flags & DM_SECTOR_SIZE_SUPPORTED))
1744                 log_std(cd, _("WARNING: The device activation will fail, dm-crypt is missing "
1745                               "support for requested encryption sector size.\n"));
1746
1747         if (integrity) {
1748                 if (params->integrity_params) {
1749                         /* Standalone dm-integrity must not be used */
1750                         if (params->integrity_params->integrity ||
1751                             params->integrity_params->integrity_key_size)
1752                                 return -EINVAL;
1753                         /* FIXME: journal encryption and MAC is here not yet supported */
1754                         if (params->integrity_params->journal_crypt ||
1755                         params->integrity_params->journal_integrity)
1756                                 return -ENOTSUP;
1757                 }
1758                 if (!INTEGRITY_tag_size(cd, integrity, cipher, cipher_mode)) {
1759                         if (!strcmp(integrity, "none"))
1760                                 integrity = NULL;
1761                         else
1762                                 return -EINVAL;
1763                 }
1764                 integrity_key_size = INTEGRITY_key_size(cd, integrity);
1765                 if ((integrity_key_size < 0) || (integrity_key_size >= (int)volume_key_size)) {
1766                         log_err(cd, _("Volume key is too small for encryption with integrity extensions."));
1767                         return -EINVAL;
1768                 }
1769         }
1770
1771         r = device_check_access(cd, crypt_metadata_device(cd), DEV_EXCL);
1772         if (r < 0)
1773                 return r;
1774
1775         if (!(cd->type = strdup(CRYPT_LUKS2)))
1776                 return -ENOMEM;
1777
1778         if (volume_key)
1779                 cd->volume_key = crypt_alloc_volume_key(volume_key_size,
1780                                                       volume_key);
1781         else
1782                 cd->volume_key = crypt_generate_volume_key(cd, volume_key_size);
1783
1784         if (!cd->volume_key)
1785                 return -ENOMEM;
1786
1787         if (params && params->pbkdf)
1788                 r = crypt_set_pbkdf_type(cd, params->pbkdf);
1789         else if (verify_pbkdf_params(cd, &cd->pbkdf))
1790                 r = init_pbkdf_type(cd, NULL, CRYPT_LUKS2);
1791
1792         if (r < 0)
1793                 return r;
1794
1795         if (params && params->data_device) {
1796                 if (!cd->metadata_device)
1797                         cd->metadata_device = cd->device;
1798                 else
1799                         device_free(cd, cd->device);
1800                 cd->device = NULL;
1801                 if (device_alloc(cd, &cd->device, params->data_device) < 0)
1802                         return -ENOMEM;
1803         }
1804
1805         if (params && cd->metadata_device) {
1806                 /* For detached header the alignment is used directly as data offset */
1807                 if (!cd->data_offset)
1808                         cd->data_offset = params->data_alignment;
1809                 required_alignment = params->data_alignment * SECTOR_SIZE;
1810         } else if (params && params->data_alignment) {
1811                 required_alignment = params->data_alignment * SECTOR_SIZE;
1812         } else
1813                 device_topology_alignment(cd, cd->device,
1814                                        &required_alignment,
1815                                        &alignment_offset, DEFAULT_DISK_ALIGNMENT);
1816
1817         /* FIXME: allow this later also for normal ciphers (check AF_ALG availability. */
1818         if (integrity && !integrity_key_size) {
1819                 r = crypt_cipher_check_kernel(cipher, cipher_mode, integrity, volume_key_size);
1820                 if (r < 0) {
1821                         log_err(cd, _("Cipher %s-%s (key size %zd bits) is not available."),
1822                                 cipher, cipher_mode, volume_key_size * 8);
1823                         goto out;
1824                 }
1825         }
1826
1827         if ((!integrity || integrity_key_size) && !crypt_cipher_wrapped_key(cipher, cipher_mode) &&
1828             !INTEGRITY_tag_size(cd, NULL, cipher, cipher_mode)) {
1829                 r = LUKS_check_cipher(cd, volume_key_size - integrity_key_size,
1830                                       cipher, cipher_mode);
1831                 if (r < 0)
1832                         goto out;
1833         }
1834
1835         r = LUKS2_generate_hdr(cd, &cd->u.luks2.hdr, cd->volume_key,
1836                                cipher, cipher_mode,
1837                                integrity, uuid,
1838                                sector_size,
1839                                cd->data_offset * SECTOR_SIZE,
1840                                alignment_offset,
1841                                required_alignment,
1842                                cd->metadata_size, cd->keyslots_size);
1843         if (r < 0)
1844                 goto out;
1845
1846         r = device_size(crypt_data_device(cd), &dev_size);
1847         if (r < 0)
1848                 goto out;
1849
1850         if (dev_size < (crypt_get_data_offset(cd) * SECTOR_SIZE))
1851                 log_std(cd, _("WARNING: Data offset is outside of currently available data device.\n"));
1852
1853         if (cd->metadata_size && (cd->metadata_size != LUKS2_metadata_size(&cd->u.luks2.hdr)))
1854                 log_std(cd, _("WARNING: LUKS2 metadata size changed to %" PRIu64 " bytes.\n"),
1855                         LUKS2_metadata_size(&cd->u.luks2.hdr));
1856
1857         if (cd->keyslots_size && (cd->keyslots_size != LUKS2_keyslots_size(&cd->u.luks2.hdr)))
1858                 log_std(cd, _("WARNING: LUKS2 keyslots area size changed to %" PRIu64 " bytes.\n"),
1859                         LUKS2_keyslots_size(&cd->u.luks2.hdr));
1860
1861         if (!integrity && sector_size > SECTOR_SIZE) {
1862                 dev_size -= (crypt_get_data_offset(cd) * SECTOR_SIZE);
1863                 if (dev_size % sector_size) {
1864                         log_err(cd, _("Device size is not aligned to requested sector size."));
1865                         r = -EINVAL;
1866                         goto out;
1867                 }
1868         }
1869
1870         if (params && (params->label || params->subsystem)) {
1871                 r = LUKS2_hdr_labels(cd, &cd->u.luks2.hdr,
1872                                      params->label, params->subsystem, 0);
1873                 if (r < 0)
1874                         goto out;
1875         }
1876
1877         r = LUKS2_wipe_header_areas(cd, &cd->u.luks2.hdr, cd->metadata_device != NULL);
1878         if (r < 0) {
1879                 log_err(cd, _("Cannot wipe header on device %s."),
1880                         mdata_device_path(cd));
1881                 if (dev_size < LUKS2_hdr_and_areas_size(&cd->u.luks2.hdr))
1882                         log_err(cd, _("Device %s is too small."), device_path(crypt_metadata_device(cd)));
1883                 goto out;
1884         }
1885
1886         /* Wipe integrity superblock and create integrity superblock */
1887         if (crypt_get_integrity_tag_size(cd)) {
1888                 r = crypt_wipe_device(cd, crypt_data_device(cd), CRYPT_WIPE_ZERO,
1889                                       crypt_get_data_offset(cd) * SECTOR_SIZE,
1890                                       8 * SECTOR_SIZE, 8 * SECTOR_SIZE, NULL, NULL);
1891                 if (r < 0) {
1892                         if (r == -EBUSY)
1893                                 log_err(cd, _("Cannot format device %s in use."),
1894                                         data_device_path(cd));
1895                         else if (r == -EACCES) {
1896                                 log_err(cd, _("Cannot format device %s, permission denied."),
1897                                         data_device_path(cd));
1898                                 r = -EINVAL;
1899                         } else
1900                                 log_err(cd, _("Cannot wipe header on device %s."),
1901                                         data_device_path(cd));
1902
1903                         goto out;
1904                 }
1905
1906                 r = INTEGRITY_format(cd, params ? params->integrity_params : NULL, NULL, NULL);
1907                 if (r)
1908                         log_err(cd, _("Cannot format integrity for device %s."),
1909                                 data_device_path(cd));
1910         }
1911
1912         if (r < 0)
1913                 goto out;
1914
1915         /* override sequence id check with format */
1916         r = LUKS2_hdr_write_force(cd, &cd->u.luks2.hdr);
1917         if (r < 0) {
1918                 if (r == -EBUSY)
1919                         log_err(cd, _("Cannot format device %s in use."),
1920                                 mdata_device_path(cd));
1921                 else if (r == -EACCES) {
1922                         log_err(cd, _("Cannot format device %s, permission denied."),
1923                                 mdata_device_path(cd));
1924                         r = -EINVAL;
1925                 } else
1926                         log_err(cd, _("Cannot format device %s."),
1927                                 mdata_device_path(cd));
1928         }
1929
1930 out:
1931         if (r)
1932                 LUKS2_hdr_free(cd, &cd->u.luks2.hdr);
1933
1934         return r;
1935 }
1936
1937 static int _crypt_format_loopaes(struct crypt_device *cd,
1938                                  const char *cipher,
1939                                  const char *uuid,
1940                                  size_t volume_key_size,
1941                                  struct crypt_params_loopaes *params)
1942 {
1943         if (!crypt_metadata_device(cd)) {
1944                 log_err(cd, _("Can't format LOOPAES without device."));
1945                 return -EINVAL;
1946         }
1947
1948         if (volume_key_size > 1024) {
1949                 log_err(cd, _("Invalid key size."));
1950                 return -EINVAL;
1951         }
1952
1953         if (uuid) {
1954                 log_err(cd, _("UUID is not supported for this crypt type."));
1955                 return -EINVAL;
1956         }
1957
1958         if (cd->metadata_device) {
1959                 log_err(cd, _("Detached metadata device is not supported for this crypt type."));
1960                 return -EINVAL;
1961         }
1962
1963         if (!(cd->type = strdup(CRYPT_LOOPAES)))
1964                 return -ENOMEM;
1965
1966         cd->u.loopaes.key_size = volume_key_size;
1967
1968         cd->u.loopaes.cipher = strdup(cipher ?: DEFAULT_LOOPAES_CIPHER);
1969
1970         if (params && params->hash)
1971                 cd->u.loopaes.hdr.hash = strdup(params->hash);
1972
1973         cd->u.loopaes.hdr.offset = params ? params->offset : 0;
1974         cd->u.loopaes.hdr.skip = params ? params->skip : 0;
1975
1976         return 0;
1977 }
1978
1979 static int _crypt_format_verity(struct crypt_device *cd,
1980                                  const char *uuid,
1981                                  struct crypt_params_verity *params)
1982 {
1983         int r = 0, hash_size;
1984         uint64_t data_device_size, hash_blocks_size;
1985         struct device *fec_device = NULL;
1986         char *fec_device_path = NULL, *hash_name = NULL, *root_hash = NULL, *salt = NULL;
1987
1988         if (!crypt_metadata_device(cd)) {
1989                 log_err(cd, _("Can't format VERITY without device."));
1990                 return -EINVAL;
1991         }
1992
1993         if (!params)
1994                 return -EINVAL;
1995
1996         if (!params->data_device && !cd->metadata_device)
1997                 return -EINVAL;
1998
1999         if (params->hash_type > VERITY_MAX_HASH_TYPE) {
2000                 log_err(cd, _("Unsupported VERITY hash type %d."), params->hash_type);
2001                 return -EINVAL;
2002         }
2003
2004         if (VERITY_BLOCK_SIZE_OK(params->data_block_size) ||
2005             VERITY_BLOCK_SIZE_OK(params->hash_block_size)) {
2006                 log_err(cd, _("Unsupported VERITY block size."));
2007                 return -EINVAL;
2008         }
2009
2010         if (MISALIGNED_512(params->hash_area_offset)) {
2011                 log_err(cd, _("Unsupported VERITY hash offset."));
2012                 return -EINVAL;
2013         }
2014
2015         if (MISALIGNED_512(params->fec_area_offset)) {
2016                 log_err(cd, _("Unsupported VERITY FEC offset."));
2017                 return -EINVAL;
2018         }
2019
2020         if (!(cd->type = strdup(CRYPT_VERITY)))
2021                 return -ENOMEM;
2022
2023         if (params->data_device) {
2024                 r = crypt_set_data_device(cd, params->data_device);
2025                 if (r)
2026                         return r;
2027         }
2028
2029         if (!params->data_size) {
2030                 r = device_size(cd->device, &data_device_size);
2031                 if (r < 0)
2032                         return r;
2033
2034                 cd->u.verity.hdr.data_size = data_device_size / params->data_block_size;
2035         } else
2036                 cd->u.verity.hdr.data_size = params->data_size;
2037
2038         if (device_is_identical(crypt_metadata_device(cd), crypt_data_device(cd)) > 0 &&
2039            (cd->u.verity.hdr.data_size * params->data_block_size) > params->hash_area_offset) {
2040                 log_err(cd, _("Data area overlaps with hash area."));
2041                 return -EINVAL;
2042         }
2043
2044         hash_size = crypt_hash_size(params->hash_name);
2045         if (hash_size <= 0) {
2046                 log_err(cd, _("Hash algorithm %s not supported."),
2047                         params->hash_name);
2048                 return -EINVAL;
2049         }
2050         cd->u.verity.root_hash_size = hash_size;
2051
2052         if (params->fec_device) {
2053                 fec_device_path = strdup(params->fec_device);
2054                 if (!fec_device_path)
2055                         return -ENOMEM;
2056                 r = device_alloc(cd, &fec_device, params->fec_device);
2057                 if (r < 0) {
2058                         r = -ENOMEM;
2059                         goto err;
2060                 }
2061
2062                 hash_blocks_size = VERITY_hash_blocks(cd, params) * params->hash_block_size;
2063                 if (device_is_identical(crypt_metadata_device(cd), fec_device) > 0 &&
2064                     (params->hash_area_offset + hash_blocks_size) > params->fec_area_offset) {
2065                         log_err(cd, _("Hash area overlaps with FEC area."));
2066                         r = -EINVAL;
2067                         goto err;
2068                 }
2069
2070                 if (device_is_identical(crypt_data_device(cd), fec_device) > 0 &&
2071                     (cd->u.verity.hdr.data_size * params->data_block_size) > params->fec_area_offset) {
2072                         log_err(cd, _("Data area overlaps with FEC area."));
2073                         r = -EINVAL;
2074                         goto err;
2075                 }
2076         }
2077
2078         root_hash = malloc(cd->u.verity.root_hash_size);
2079         hash_name = strdup(params->hash_name);
2080         salt = malloc(params->salt_size);
2081
2082         if (!root_hash || !hash_name || !salt) {
2083                 r = -ENOMEM;
2084                 goto err;
2085         }
2086
2087         cd->u.verity.hdr.flags = params->flags;
2088         cd->u.verity.root_hash = root_hash;
2089         cd->u.verity.hdr.hash_name = hash_name;
2090         cd->u.verity.hdr.data_device = NULL;
2091         cd->u.verity.fec_device = fec_device;
2092         cd->u.verity.hdr.fec_device = fec_device_path;
2093         cd->u.verity.hdr.fec_roots = params->fec_roots;
2094         cd->u.verity.hdr.data_block_size = params->data_block_size;
2095         cd->u.verity.hdr.hash_block_size = params->hash_block_size;
2096         cd->u.verity.hdr.hash_area_offset = params->hash_area_offset;
2097         cd->u.verity.hdr.fec_area_offset = params->fec_area_offset;
2098         cd->u.verity.hdr.hash_type = params->hash_type;
2099         cd->u.verity.hdr.flags = params->flags;
2100         cd->u.verity.hdr.salt_size = params->salt_size;
2101         cd->u.verity.hdr.salt = salt;
2102
2103         if (params->salt)
2104                 memcpy(salt, params->salt, params->salt_size);
2105         else
2106                 r = crypt_random_get(cd, salt, params->salt_size, CRYPT_RND_SALT);
2107         if (r)
2108                 goto err;
2109
2110         if (params->flags & CRYPT_VERITY_CREATE_HASH) {
2111                 r = VERITY_create(cd, &cd->u.verity.hdr,
2112                                   cd->u.verity.root_hash, cd->u.verity.root_hash_size);
2113                 if (!r && params->fec_device)
2114                         r = VERITY_FEC_process(cd, &cd->u.verity.hdr, cd->u.verity.fec_device, 0, NULL);
2115                 if (r)
2116                         goto err;
2117         }
2118
2119         if (!(params->flags & CRYPT_VERITY_NO_HEADER)) {
2120                 if (uuid) {
2121                         if (!(cd->u.verity.uuid = strdup(uuid)))
2122                                 r = -ENOMEM;
2123                 } else
2124                         r = VERITY_UUID_generate(cd, &cd->u.verity.uuid);
2125
2126                 if (!r)
2127                         r = VERITY_write_sb(cd, cd->u.verity.hdr.hash_area_offset,
2128                                             cd->u.verity.uuid,
2129                                             &cd->u.verity.hdr);
2130         }
2131
2132 err:
2133         if (r) {
2134                 device_free(cd, fec_device);
2135                 free(root_hash);
2136                 free(hash_name);
2137                 free(fec_device_path);
2138                 free(salt);
2139         }
2140
2141         return r;
2142 }
2143
2144 static int _crypt_format_integrity(struct crypt_device *cd,
2145                                    const char *uuid,
2146                                    struct crypt_params_integrity *params)
2147 {
2148         int r;
2149         uint32_t integrity_tag_size;
2150         char *integrity = NULL, *journal_integrity = NULL, *journal_crypt = NULL;
2151         struct volume_key *journal_crypt_key = NULL, *journal_mac_key = NULL;
2152
2153         if (!params)
2154                 return -EINVAL;
2155
2156         if (uuid) {
2157                 log_err(cd, _("UUID is not supported for this crypt type."));
2158                 return -EINVAL;
2159         }
2160
2161         r = device_check_access(cd, crypt_metadata_device(cd), DEV_EXCL);
2162         if (r < 0)
2163                 return r;
2164
2165         /* Wipe first 8 sectors - fs magic numbers etc. */
2166         r = crypt_wipe_device(cd, crypt_metadata_device(cd), CRYPT_WIPE_ZERO, 0,
2167                               8 * SECTOR_SIZE, 8 * SECTOR_SIZE, NULL, NULL);
2168         if (r < 0) {
2169                 log_err(cd, _("Cannot wipe header on device %s."),
2170                         mdata_device_path(cd));
2171                 return r;
2172         }
2173
2174         if (!(cd->type = strdup(CRYPT_INTEGRITY)))
2175                 return -ENOMEM;
2176
2177         if (params->journal_crypt_key) {
2178                 journal_crypt_key = crypt_alloc_volume_key(params->journal_crypt_key_size,
2179                                                            params->journal_crypt_key);
2180                 if (!journal_crypt_key)
2181                         return -ENOMEM;
2182         }
2183
2184         if (params->journal_integrity_key) {
2185                 journal_mac_key = crypt_alloc_volume_key(params->journal_integrity_key_size,
2186                                                          params->journal_integrity_key);
2187                 if (!journal_mac_key) {
2188                         r = -ENOMEM;
2189                         goto err;
2190                 }
2191         }
2192
2193         if (params->integrity && !(integrity = strdup(params->integrity))) {
2194                 r = -ENOMEM;
2195                 goto err;
2196         }
2197         if (params->journal_integrity && !(journal_integrity = strdup(params->journal_integrity))) {
2198                 r = -ENOMEM;
2199                 goto err;
2200         }
2201         if (params->journal_crypt && !(journal_crypt = strdup(params->journal_crypt))) {
2202                 r = -ENOMEM;
2203                 goto err;
2204         }
2205
2206         integrity_tag_size = INTEGRITY_hash_tag_size(integrity);
2207         if (integrity_tag_size > 0 && params->tag_size && integrity_tag_size != params->tag_size)
2208                 log_std(cd, _("WARNING: Requested tag size %d bytes differs from %s size output (%d bytes).\n"),
2209                         params->tag_size, integrity, integrity_tag_size);
2210
2211         if (params->tag_size)
2212                 integrity_tag_size = params->tag_size;
2213
2214         cd->u.integrity.journal_crypt_key = journal_crypt_key;
2215         cd->u.integrity.journal_mac_key = journal_mac_key;
2216         cd->u.integrity.params.journal_size = params->journal_size;
2217         cd->u.integrity.params.journal_watermark = params->journal_watermark;
2218         cd->u.integrity.params.journal_commit_time = params->journal_commit_time;
2219         cd->u.integrity.params.interleave_sectors = params->interleave_sectors;
2220         cd->u.integrity.params.buffer_sectors = params->buffer_sectors;
2221         cd->u.integrity.params.sector_size = params->sector_size;
2222         cd->u.integrity.params.tag_size = integrity_tag_size;
2223         cd->u.integrity.params.integrity = integrity;
2224         cd->u.integrity.params.journal_integrity = journal_integrity;
2225         cd->u.integrity.params.journal_crypt = journal_crypt;
2226
2227         r = INTEGRITY_format(cd, params, cd->u.integrity.journal_crypt_key, cd->u.integrity.journal_mac_key);
2228         if (r)
2229                 log_err(cd, _("Cannot format integrity for device %s."),
2230                         mdata_device_path(cd));
2231 err:
2232         if (r) {
2233                 crypt_free_volume_key(journal_crypt_key);
2234                 crypt_free_volume_key(journal_mac_key);
2235                 free(integrity);
2236                 free(journal_integrity);
2237                 free(journal_crypt);
2238         }
2239
2240         return r;
2241 }
2242
2243 int crypt_format(struct crypt_device *cd,
2244         const char *type,
2245         const char *cipher,
2246         const char *cipher_mode,
2247         const char *uuid,
2248         const char *volume_key,
2249         size_t volume_key_size,
2250         void *params)
2251 {
2252         int r;
2253
2254         if (!cd || !type)
2255                 return -EINVAL;
2256
2257         if (cd->type) {
2258                 log_dbg(cd, "Context already formatted as %s.", cd->type);
2259                 return -EINVAL;
2260         }
2261
2262         log_dbg(cd, "Formatting device %s as type %s.", mdata_device_path(cd) ?: "(none)", type);
2263
2264         crypt_reset_null_type(cd);
2265
2266         r = init_crypto(cd);
2267         if (r < 0)
2268                 return r;
2269
2270         if (isPLAIN(type))
2271                 r = _crypt_format_plain(cd, cipher, cipher_mode,
2272                                         uuid, volume_key_size, params);
2273         else if (isLUKS1(type))
2274                 r = _crypt_format_luks1(cd, cipher, cipher_mode,
2275                                         uuid, volume_key, volume_key_size, params);
2276         else if (isLUKS2(type))
2277                 r = _crypt_format_luks2(cd, cipher, cipher_mode,
2278                                         uuid, volume_key, volume_key_size, params);
2279         else if (isLOOPAES(type))
2280                 r = _crypt_format_loopaes(cd, cipher, uuid, volume_key_size, params);
2281         else if (isVERITY(type))
2282                 r = _crypt_format_verity(cd, uuid, params);
2283         else if (isINTEGRITY(type))
2284                 r = _crypt_format_integrity(cd, uuid, params);
2285         else {
2286                 log_err(cd, _("Unknown crypt device type %s requested."), type);
2287                 r = -EINVAL;
2288         }
2289
2290         if (r < 0) {
2291                 crypt_set_null_type(cd);
2292                 crypt_free_volume_key(cd->volume_key);
2293                 cd->volume_key = NULL;
2294         }
2295
2296         return r;
2297 }
2298
2299 int crypt_repair(struct crypt_device *cd,
2300                  const char *requested_type,
2301                  void *params __attribute__((unused)))
2302 {
2303         int r;
2304
2305         if (!cd)
2306                 return -EINVAL;
2307
2308         log_dbg(cd, "Trying to repair %s crypt type from device %s.",
2309                 requested_type ?: "any", mdata_device_path(cd) ?: "(none)");
2310
2311         if (!crypt_metadata_device(cd))
2312                 return -EINVAL;
2313
2314         if (requested_type && !isLUKS(requested_type))
2315                 return -EINVAL;
2316
2317         /* Load with repair */
2318         r = _crypt_load_luks(cd, requested_type, 1, 1);
2319         if (r < 0)
2320                 return r;
2321
2322         /* cd->type and header must be set in context */
2323         r = crypt_check_data_device_size(cd);
2324         if (r < 0)
2325                 crypt_set_null_type(cd);
2326
2327         return r;
2328 }
2329
2330 /* compare volume keys */
2331 static int _compare_volume_keys(struct volume_key *svk, unsigned skeyring_only, struct volume_key *tvk, unsigned tkeyring_only)
2332 {
2333         if (!svk && !tvk)
2334                 return 0;
2335         else if (!svk || !tvk)
2336                 return 1;
2337
2338         if (svk->keylength != tvk->keylength)
2339                 return 1;
2340
2341         if (!skeyring_only && !tkeyring_only)
2342                 return memcmp(svk->key, tvk->key, svk->keylength);
2343
2344         if (svk->key_description && tvk->key_description)
2345                 return strcmp(svk->key_description, tvk->key_description);
2346
2347         return 0;
2348 }
2349
2350 static int _compare_device_types(struct crypt_device *cd,
2351                                const struct crypt_dm_active_device *src,
2352                                const struct crypt_dm_active_device *tgt)
2353 {
2354         if (!tgt->uuid) {
2355                 log_dbg(cd, "Missing device uuid in target device.");
2356                 return -EINVAL;
2357         }
2358
2359         if (isLUKS2(cd->type) && !strncmp("INTEGRITY-", tgt->uuid, strlen("INTEGRITY-"))) {
2360                 if (crypt_uuid_cmp(tgt->uuid, src->uuid)) {
2361                         log_dbg(cd, "LUKS UUID mismatch.");
2362                         return -EINVAL;
2363                 }
2364         } else if (isLUKS(cd->type)) {
2365                 if (!src->uuid || strncmp(cd->type, tgt->uuid, strlen(cd->type)) ||
2366                     crypt_uuid_cmp(tgt->uuid, src->uuid)) {
2367                         log_dbg(cd, "LUKS UUID mismatch.");
2368                         return -EINVAL;
2369                 }
2370         } else if (isPLAIN(cd->type) || isLOOPAES(cd->type)) {
2371                 if (strncmp(cd->type, tgt->uuid, strlen(cd->type))) {
2372                         log_dbg(cd, "Unexpected uuid prefix %s in target device.", tgt->uuid);
2373                         return -EINVAL;
2374                 }
2375         } else {
2376                 log_dbg(cd, "Unsupported device type %s for reload.", cd->type ?: "<empty>");
2377                 return -ENOTSUP;
2378         }
2379
2380         return 0;
2381 }
2382
2383 static int _compare_crypt_devices(struct crypt_device *cd,
2384                                const struct dm_target *src,
2385                                const struct dm_target *tgt)
2386 {
2387         /* for crypt devices keys are mandatory */
2388         if (!src->u.crypt.vk || !tgt->u.crypt.vk)
2389                 return -EINVAL;
2390
2391         /* CIPHER checks */
2392         if (!src->u.crypt.cipher || !tgt->u.crypt.cipher)
2393                 return -EINVAL;
2394         if (strcmp(src->u.crypt.cipher, tgt->u.crypt.cipher)) {
2395                 log_dbg(cd, "Cipher specs do not match.");
2396                 return -EINVAL;
2397         }
2398
2399         if (tgt->u.crypt.vk->keylength == 0 && crypt_is_cipher_null(tgt->u.crypt.cipher))
2400                 log_dbg(cd, "Existing device uses cipher null. Skipping key comparison.");
2401         else if (_compare_volume_keys(src->u.crypt.vk, 0, tgt->u.crypt.vk, tgt->u.crypt.vk->key_description != NULL)) {
2402                 log_dbg(cd, "Keys in context and target device do not match.");
2403                 return -EINVAL;
2404         }
2405
2406         if (crypt_strcmp(src->u.crypt.integrity, tgt->u.crypt.integrity)) {
2407                 log_dbg(cd, "Integrity parameters do not match.");
2408                 return -EINVAL;
2409         }
2410
2411         if (src->u.crypt.offset      != tgt->u.crypt.offset ||
2412             src->u.crypt.sector_size != tgt->u.crypt.sector_size ||
2413             src->u.crypt.iv_offset   != tgt->u.crypt.iv_offset ||
2414             src->u.crypt.tag_size    != tgt->u.crypt.tag_size) {
2415                 log_dbg(cd, "Integer parameters do not match.");
2416                 return -EINVAL;
2417         }
2418
2419         if (device_is_identical(src->data_device, tgt->data_device) <= 0) {
2420                 log_dbg(cd, "Data devices do not match.");
2421                 return -EINVAL;
2422         }
2423
2424         return 0;
2425 }
2426
2427 static int _compare_integrity_devices(struct crypt_device *cd,
2428                                const struct dm_target *src,
2429                                const struct dm_target *tgt)
2430 {
2431         /*
2432          * some parameters may be implicit (and set in dm-integrity ctor)
2433          *
2434          *      journal_size
2435          *      journal_watermark
2436          *      journal_commit_time
2437          *      buffer_sectors
2438          *      interleave_sectors
2439          */
2440
2441         /* check remaining integer values that makes sense */
2442         if (src->u.integrity.tag_size     != tgt->u.integrity.tag_size ||
2443             src->u.integrity.offset       != tgt->u.integrity.offset   ||
2444             src->u.integrity.sector_size  != tgt->u.integrity.sector_size) {
2445                 log_dbg(cd, "Integer parameters do not match.");
2446                 return -EINVAL;
2447         }
2448
2449         if (crypt_strcmp(src->u.integrity.integrity,         tgt->u.integrity.integrity) ||
2450             crypt_strcmp(src->u.integrity.journal_integrity, tgt->u.integrity.journal_integrity) ||
2451             crypt_strcmp(src->u.integrity.journal_crypt,     tgt->u.integrity.journal_crypt)) {
2452                 log_dbg(cd, "Journal parameters do not match.");
2453                 return -EINVAL;
2454         }
2455
2456         /* unfortunately dm-integrity doesn't support keyring */
2457         if (_compare_volume_keys(src->u.integrity.vk, 0, tgt->u.integrity.vk, 0) ||
2458             _compare_volume_keys(src->u.integrity.journal_integrity_key, 0, tgt->u.integrity.journal_integrity_key, 0) ||
2459             _compare_volume_keys(src->u.integrity.journal_crypt_key, 0, tgt->u.integrity.journal_crypt_key, 0)) {
2460                 log_dbg(cd, "Journal keys do not match.");
2461                 return -EINVAL;
2462         }
2463
2464         /* unsupported underneath dm-crypt with auth. encryption */
2465         if (src->u.integrity.meta_device || tgt->u.integrity.meta_device)
2466                 return -ENOTSUP;
2467
2468         if (src->size != tgt->size) {
2469                 log_dbg(cd, "Device size parameters do not match.");
2470                 return -EINVAL;
2471         }
2472
2473         if (device_is_identical(src->data_device, tgt->data_device) <= 0) {
2474                 log_dbg(cd, "Data devices do not match.");
2475                 return -EINVAL;
2476         }
2477
2478         return 0;
2479 }
2480
2481 int crypt_compare_dm_devices(struct crypt_device *cd,
2482                                const struct crypt_dm_active_device *src,
2483                                const struct crypt_dm_active_device *tgt)
2484 {
2485         int r;
2486         const struct dm_target *s, *t;
2487
2488         if (!src || !tgt)
2489                 return -EINVAL;
2490
2491         r = _compare_device_types(cd, src, tgt);
2492         if (r)
2493                 return r;
2494
2495         s = &src->segment;
2496         t = &tgt->segment;
2497
2498         while (s || t) {
2499                 if (!s || !t) {
2500                         log_dbg(cd, "segments count mismatch.");
2501                         return -EINVAL;
2502                 }
2503                 if (s->type != t->type) {
2504                         log_dbg(cd, "segment type mismatch.");
2505                         r = -EINVAL;
2506                         break;
2507                 }
2508
2509                 switch (s->type) {
2510                 case DM_CRYPT:
2511                         r = _compare_crypt_devices(cd, s, t);
2512                         break;
2513                 case DM_INTEGRITY:
2514                         r = _compare_integrity_devices(cd, s, t);
2515                         break;
2516                 case DM_LINEAR:
2517                         r = (s->u.linear.offset == t->u.linear.offset) ? 0 : -EINVAL;
2518                         break;
2519                 default:
2520                         r = -ENOTSUP;
2521                 }
2522
2523                 if (r)
2524                         break;
2525
2526                 s = s->next;
2527                 t = t->next;
2528         }
2529
2530         return r;
2531 }
2532
2533 static int _reload_device(struct crypt_device *cd, const char *name,
2534                           struct crypt_dm_active_device *sdmd)
2535 {
2536         int r;
2537         struct crypt_dm_active_device tdmd;
2538         struct dm_target *src, *tgt = &tdmd.segment;
2539
2540         if (!cd || !cd->type || !name || !(sdmd->flags & CRYPT_ACTIVATE_REFRESH))
2541                 return -EINVAL;
2542
2543         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
2544                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
2545                                   DM_ACTIVE_CRYPT_KEY, &tdmd);
2546         if (r < 0) {
2547                 log_err(cd, _("Device %s is not active."), name);
2548                 return -EINVAL;
2549         }
2550
2551         if (!single_segment(&tdmd) || tgt->type != DM_CRYPT || tgt->u.crypt.tag_size) {
2552                 r = -ENOTSUP;
2553                 log_err(cd, _("Unsupported parameters on device %s."), name);
2554                 goto out;
2555         }
2556
2557         r = crypt_compare_dm_devices(cd, sdmd, &tdmd);
2558         if (r) {
2559                 log_err(cd, _("Mismatching parameters on device %s."), name);
2560                 goto out;
2561         }
2562
2563         src = &sdmd->segment;
2564
2565         /* Changing read only flag for active device makes no sense */
2566         if (tdmd.flags & CRYPT_ACTIVATE_READONLY)
2567                 sdmd->flags |= CRYPT_ACTIVATE_READONLY;
2568         else
2569                 sdmd->flags &= ~CRYPT_ACTIVATE_READONLY;
2570
2571         if (sdmd->flags & CRYPT_ACTIVATE_KEYRING_KEY) {
2572                 r = crypt_volume_key_set_description(tgt->u.crypt.vk, src->u.crypt.vk->key_description);
2573                 if (r)
2574                         goto out;
2575         } else {
2576                 crypt_free_volume_key(tgt->u.crypt.vk);
2577                 tgt->u.crypt.vk = crypt_alloc_volume_key(src->u.crypt.vk->keylength, src->u.crypt.vk->key);
2578                 if (!tgt->u.crypt.vk) {
2579                         r = -ENOMEM;
2580                         goto out;
2581                 }
2582         }
2583
2584         r = device_block_adjust(cd, src->data_device, DEV_OK,
2585                                 src->u.crypt.offset, &sdmd->size, NULL);
2586         if (r)
2587                 goto out;
2588
2589         tdmd.flags = sdmd->flags;
2590         tgt->size = tdmd.size = sdmd->size;
2591
2592         r = dm_reload_device(cd, name, &tdmd, 0, 1);
2593 out:
2594         dm_targets_free(cd, &tdmd);
2595         free(CONST_CAST(void*)tdmd.uuid);
2596
2597         return r;
2598 }
2599
2600 static int _reload_device_with_integrity(struct crypt_device *cd,
2601         const char *name,
2602         const char *iname,
2603         const char *ipath,
2604         struct crypt_dm_active_device *sdmd,
2605         struct crypt_dm_active_device *sdmdi)
2606 {
2607         int r;
2608         struct crypt_dm_active_device tdmd, tdmdi = {};
2609         struct dm_target *src, *srci, *tgt = &tdmd.segment, *tgti = &tdmdi.segment;
2610         struct device *data_device = NULL;
2611
2612         if (!cd || !cd->type || !name || !iname || !(sdmd->flags & CRYPT_ACTIVATE_REFRESH))
2613                 return -EINVAL;
2614
2615         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
2616                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
2617                                   DM_ACTIVE_CRYPT_KEY, &tdmd);
2618         if (r < 0) {
2619                 log_err(cd, _("Device %s is not active."), name);
2620                 return -EINVAL;
2621         }
2622
2623         if (!single_segment(&tdmd) || tgt->type != DM_CRYPT || !tgt->u.crypt.tag_size) {
2624                 r = -ENOTSUP;
2625                 log_err(cd, _("Unsupported parameters on device %s."), name);
2626                 goto out;
2627         }
2628
2629         r = dm_query_device(cd, iname, DM_ACTIVE_DEVICE | DM_ACTIVE_UUID, &tdmdi);
2630         if (r < 0) {
2631                 log_err(cd, _("Device %s is not active."), iname);
2632                 r = -EINVAL;
2633                 goto out;
2634         }
2635
2636         if (!single_segment(&tdmdi) || tgti->type != DM_INTEGRITY) {
2637                 r = -ENOTSUP;
2638                 log_err(cd, _("Unsupported parameters on device %s."), iname);
2639                 goto out;
2640         }
2641
2642         r = crypt_compare_dm_devices(cd, sdmdi, &tdmdi);
2643         if (r) {
2644                 log_err(cd, _("Mismatching parameters on device %s."), iname);
2645                 goto out;
2646         }
2647
2648         src = &sdmd->segment;
2649         srci = &sdmdi->segment;
2650
2651         r = device_alloc(cd, &data_device, ipath);
2652         if (r < 0)
2653                 goto out;
2654
2655         r = device_block_adjust(cd, srci->data_device, DEV_OK,
2656                                 srci->u.integrity.offset, &sdmdi->size, NULL);
2657         if (r)
2658                 goto out;
2659
2660         src->data_device = data_device;
2661
2662         r = crypt_compare_dm_devices(cd, sdmd, &tdmd);
2663         if (r) {
2664                 log_err(cd, _("Crypt devices mismatch."));
2665                 goto out;
2666         }
2667
2668         /* Changing read only flag for active device makes no sense */
2669         if (tdmd.flags & CRYPT_ACTIVATE_READONLY)
2670                 sdmd->flags |= CRYPT_ACTIVATE_READONLY;
2671         else
2672                 sdmd->flags &= ~CRYPT_ACTIVATE_READONLY;
2673
2674         if (tdmdi.flags & CRYPT_ACTIVATE_READONLY)
2675                 sdmdi->flags |= CRYPT_ACTIVATE_READONLY;
2676         else
2677                 sdmdi->flags &= ~CRYPT_ACTIVATE_READONLY;
2678
2679         if (sdmd->flags & CRYPT_ACTIVATE_KEYRING_KEY) {
2680                 r = crypt_volume_key_set_description(tgt->u.crypt.vk, src->u.crypt.vk->key_description);
2681                 if (r)
2682                         goto out;
2683         } else {
2684                 crypt_free_volume_key(tgt->u.crypt.vk);
2685                 tgt->u.crypt.vk = crypt_alloc_volume_key(src->u.crypt.vk->keylength, src->u.crypt.vk->key);
2686                 if (!tgt->u.crypt.vk) {
2687                         r = -ENOMEM;
2688                         goto out;
2689                 }
2690         }
2691
2692         r = device_block_adjust(cd, src->data_device, DEV_OK,
2693                                 src->u.crypt.offset, &sdmd->size, NULL);
2694         if (r)
2695                 goto out;
2696
2697         tdmd.flags = sdmd->flags;
2698         tdmd.size = sdmd->size;
2699
2700         if ((r = dm_reload_device(cd, iname, sdmdi, 0, 0))) {
2701                 log_err(cd, _("Failed to reload device %s."), iname);
2702                 goto out;
2703         }
2704
2705         if ((r = dm_reload_device(cd, name, &tdmd, 0, 0))) {
2706                 log_err(cd, _("Failed to reload device %s."), name);
2707                 goto err_clear;
2708         }
2709
2710         if ((r = dm_suspend_device(cd, name, 0))) {
2711                 log_err(cd, _("Failed to suspend device %s."), name);
2712                 goto err_clear;
2713         }
2714
2715         if ((r = dm_suspend_device(cd, iname, 0))) {
2716                 log_err(cd, _("Failed to suspend device %s."), iname);
2717                 goto err_clear;
2718         }
2719
2720         if ((r = dm_resume_device(cd, iname, act2dmflags(sdmdi->flags)))) {
2721                 log_err(cd, _("Failed to resume device %s."), iname);
2722                 goto err_clear;
2723         }
2724
2725         r = dm_resume_device(cd, name, act2dmflags(tdmd.flags));
2726         if (!r)
2727                 goto out;
2728
2729         /*
2730          * This is worst case scenario. We have active underlying dm-integrity device with
2731          * new table but dm-crypt resume failed for some reason. Tear everything down and
2732          * burn it for good.
2733          */
2734
2735         log_err(cd, _("Fatal error while reloading device %s (on top of device %s)."), name, iname);
2736
2737         if (dm_error_device(cd, name))
2738                 log_err(cd, _("Failed to switch device %s to dm-error."), name);
2739         if (dm_error_device(cd, iname))
2740                 log_err(cd, _("Failed to switch device %s to dm-error."), iname);
2741         goto out;
2742
2743 err_clear:
2744         dm_clear_device(cd, name);
2745         dm_clear_device(cd, iname);
2746
2747         if (dm_status_suspended(cd, name) > 0)
2748                 dm_resume_device(cd, name, 0);
2749         if (dm_status_suspended(cd, iname) > 0)
2750                 dm_resume_device(cd, iname, 0);
2751 out:
2752         dm_targets_free(cd, &tdmd);
2753         dm_targets_free(cd, &tdmdi);
2754         free(CONST_CAST(void*)tdmdi.uuid);
2755         free(CONST_CAST(void*)tdmd.uuid);
2756         device_free(cd, data_device);
2757
2758         return r;
2759 }
2760
2761 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
2762 {
2763         struct crypt_dm_active_device dmdq, dmd = {};
2764         struct dm_target *tgt = &dmdq.segment;
2765         int r;
2766
2767         /*
2768          * FIXME: Also with LUKS2 we must not allow resize when there's
2769          *        explicit size stored in metadata (length != "dynamic")
2770          */
2771
2772         /* Device context type must be initialized */
2773         if (!cd || !cd->type || !name)
2774                 return -EINVAL;
2775
2776         if (isTCRYPT(cd->type) || isBITLK(cd->type)) {
2777                 log_err(cd, _("This operation is not supported for this device type."));
2778                 return -ENOTSUP;
2779         }
2780
2781         log_dbg(cd, "Resizing device %s to %" PRIu64 " sectors.", name, new_size);
2782
2783         r = dm_query_device(cd, name, DM_ACTIVE_CRYPT_KEYSIZE | DM_ACTIVE_CRYPT_KEY, &dmdq);
2784         if (r < 0) {
2785                 log_err(cd, _("Device %s is not active."), name);
2786                 return -EINVAL;
2787         }
2788         if (!single_segment(&dmdq) || tgt->type != DM_CRYPT) {
2789                 log_dbg(cd, "Unsupported device table detected in %s.", name);
2790                 r = -EINVAL;
2791                 goto out;
2792         }
2793
2794         if ((dmdq.flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_key_in_keyring(cd)) {
2795                 r = -EPERM;
2796                 goto out;
2797         }
2798
2799         if (crypt_key_in_keyring(cd)) {
2800                 if (!isLUKS2(cd->type)) {
2801                         r = -EINVAL;
2802                         goto out;
2803                 }
2804                 r = LUKS2_key_description_by_segment(cd, &cd->u.luks2.hdr,
2805                                         tgt->u.crypt.vk, CRYPT_DEFAULT_SEGMENT);
2806                 if (r)
2807                         goto out;
2808
2809                 dmdq.flags |= CRYPT_ACTIVATE_KEYRING_KEY;
2810         }
2811
2812         if (crypt_loop_device(crypt_get_device_name(cd))) {
2813                 log_dbg(cd, "Trying to resize underlying loop device %s.",
2814                         crypt_get_device_name(cd));
2815                 /* Here we always use default size not new_size */
2816                 if (crypt_loop_resize(crypt_get_device_name(cd)))
2817                         log_err(cd, _("Cannot resize loop device."));
2818         }
2819
2820         r = device_block_adjust(cd, crypt_data_device(cd), DEV_OK,
2821                                 crypt_get_data_offset(cd), &new_size, &dmdq.flags);
2822         if (r)
2823                 goto out;
2824
2825         if (MISALIGNED(new_size, tgt->u.crypt.sector_size >> SECTOR_SHIFT)) {
2826                 log_err(cd, _("Device size is not aligned to requested sector size."));
2827                 r = -EINVAL;
2828                 goto out;
2829         }
2830
2831         if (MISALIGNED(new_size, device_block_size(cd, crypt_data_device(cd)) >> SECTOR_SHIFT)) {
2832                 log_err(cd, _("Device size is not aligned to device logical block size."));
2833                 r = -EINVAL;
2834                 goto out;
2835         }
2836
2837         dmd.uuid = crypt_get_uuid(cd);
2838         dmd.size = new_size;
2839         dmd.flags = dmdq.flags | CRYPT_ACTIVATE_REFRESH;
2840         r = dm_crypt_target_set(&dmd.segment, 0, new_size, crypt_data_device(cd),
2841                         tgt->u.crypt.vk, crypt_get_cipher_spec(cd),
2842                         crypt_get_iv_offset(cd), crypt_get_data_offset(cd),
2843                         crypt_get_integrity(cd), crypt_get_integrity_tag_size(cd),
2844                         crypt_get_sector_size(cd));
2845         if (r < 0)
2846                 goto out;
2847
2848         if (new_size == dmdq.size) {
2849                 log_dbg(cd, "Device has already requested size %" PRIu64
2850                         " sectors.", dmdq.size);
2851                 r = 0;
2852         } else {
2853                 if (isTCRYPT(cd->type))
2854                         r = -ENOTSUP;
2855                 else if (isLUKS2(cd->type))
2856                         r = LUKS2_unmet_requirements(cd, &cd->u.luks2.hdr, 0, 0);
2857                 if (!r)
2858                         r = _reload_device(cd, name, &dmd);
2859         }
2860 out:
2861         dm_targets_free(cd, &dmd);
2862         dm_targets_free(cd, &dmdq);
2863
2864         return r;
2865 }
2866
2867 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
2868 {
2869         const char *active_uuid;
2870         int r;
2871
2872         log_dbg(cd, "%s device uuid.", uuid ? "Setting new" : "Refreshing");
2873
2874         if ((r = onlyLUKS(cd)))
2875                 return r;
2876
2877         active_uuid = crypt_get_uuid(cd);
2878
2879         if (uuid && active_uuid && !strncmp(uuid, active_uuid, UUID_STRING_L)) {
2880                 log_dbg(cd, "UUID is the same as requested (%s) for device %s.",
2881                         uuid, mdata_device_path(cd));
2882                 return 0;
2883         }
2884
2885         if (uuid)
2886                 log_dbg(cd, "Requested new UUID change to %s for %s.", uuid, mdata_device_path(cd));
2887         else
2888                 log_dbg(cd, "Requested new UUID refresh for %s.", mdata_device_path(cd));
2889
2890         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
2891                 return -EPERM;
2892
2893         if (isLUKS1(cd->type))
2894                 return LUKS_hdr_uuid_set(&cd->u.luks1.hdr, uuid, cd);
2895         else
2896                 return LUKS2_hdr_uuid(cd, &cd->u.luks2.hdr, uuid);
2897 }
2898
2899 int crypt_set_label(struct crypt_device *cd, const char *label, const char *subsystem)
2900 {
2901         int r;
2902
2903         log_dbg(cd, "Setting new labels.");
2904
2905         if ((r = onlyLUKS2(cd)))
2906                 return r;
2907
2908         return LUKS2_hdr_labels(cd, &cd->u.luks2.hdr, label, subsystem, 1);
2909 }
2910
2911 int crypt_header_backup(struct crypt_device *cd,
2912                         const char *requested_type,
2913                         const char *backup_file)
2914 {
2915         int r;
2916
2917         if (requested_type && !isLUKS(requested_type))
2918                 return -EINVAL;
2919
2920         if (!backup_file)
2921                 return -EINVAL;
2922
2923         /* Load with repair */
2924         r = _crypt_load_luks(cd, requested_type, 1, 0);
2925         if (r < 0)
2926                 return r;
2927
2928         log_dbg(cd, "Requested header backup of device %s (%s) to "
2929                 "file %s.", mdata_device_path(cd), requested_type ?: "any type", backup_file);
2930
2931         if (isLUKS1(cd->type) && (!requested_type || isLUKS1(requested_type)))
2932                 r = LUKS_hdr_backup(backup_file, cd);
2933         else if (isLUKS2(cd->type) && (!requested_type || isLUKS2(requested_type)))
2934                 r = LUKS2_hdr_backup(cd, &cd->u.luks2.hdr, backup_file);
2935         else
2936                 r = -EINVAL;
2937
2938         return r;
2939 }
2940
2941 int crypt_header_restore(struct crypt_device *cd,
2942                          const char *requested_type,
2943                          const char *backup_file)
2944 {
2945         struct luks_phdr hdr1;
2946         struct luks2_hdr hdr2;
2947         int r, version;
2948
2949         if (requested_type && !isLUKS(requested_type))
2950                 return -EINVAL;
2951
2952         if (!cd || (cd->type && !isLUKS(cd->type)) || !backup_file)
2953                 return -EINVAL;
2954
2955         r = init_crypto(cd);
2956         if (r < 0)
2957                 return r;
2958
2959         log_dbg(cd, "Requested header restore to device %s (%s) from "
2960                 "file %s.", mdata_device_path(cd), requested_type ?: "any type", backup_file);
2961
2962         version = LUKS2_hdr_version_unlocked(cd, backup_file);
2963         if (!version ||
2964            (requested_type && version == 1 && !isLUKS1(requested_type)) ||
2965            (requested_type && version == 2 && !isLUKS2(requested_type))) {
2966                 log_err(cd, _("Header backup file does not contain compatible LUKS header."));
2967                 return -EINVAL;
2968         }
2969
2970         memset(&hdr2, 0, sizeof(hdr2));
2971
2972         if (!cd->type) {
2973                 if (version == 1)
2974                         r = LUKS_hdr_restore(backup_file, &hdr1, cd);
2975                 else
2976                         r = LUKS2_hdr_restore(cd, &hdr2, backup_file);
2977
2978                 crypt_safe_memzero(&hdr1, sizeof(hdr1));
2979                 crypt_safe_memzero(&hdr2, sizeof(hdr2));
2980         } else if (isLUKS2(cd->type) && (!requested_type || isLUKS2(requested_type))) {
2981                 r = LUKS2_hdr_restore(cd, &cd->u.luks2.hdr, backup_file);
2982                 if (r)
2983                         _luks2_reload(cd);
2984         } else if (isLUKS1(cd->type) && (!requested_type || isLUKS1(requested_type)))
2985                 r = LUKS_hdr_restore(backup_file, &cd->u.luks1.hdr, cd);
2986         else
2987                 r = -EINVAL;
2988
2989         if (!r)
2990                 r = _crypt_load_luks(cd, version == 1 ? CRYPT_LUKS1 : CRYPT_LUKS2, 1, 1);
2991
2992         return r;
2993 }
2994
2995 void crypt_free(struct crypt_device *cd)
2996 {
2997         if (!cd)
2998                 return;
2999
3000         log_dbg(cd, "Releasing crypt device %s context.", mdata_device_path(cd));
3001
3002         dm_backend_exit(cd);
3003         crypt_free_volume_key(cd->volume_key);
3004
3005         crypt_free_type(cd);
3006
3007         device_free(cd, cd->device);
3008         device_free(cd, cd->metadata_device);
3009
3010         free(CONST_CAST(void*)cd->pbkdf.type);
3011         free(CONST_CAST(void*)cd->pbkdf.hash);
3012
3013         /* Some structures can contain keys (TCRYPT), wipe it */
3014         crypt_safe_memzero(cd, sizeof(*cd));
3015         free(cd);
3016 }
3017
3018 static char *crypt_get_device_key_description(struct crypt_device *cd, const char *name)
3019 {
3020         char *desc = NULL;
3021         struct crypt_dm_active_device dmd;
3022         struct dm_target *tgt = &dmd.segment;
3023
3024         if (dm_query_device(cd, name, DM_ACTIVE_CRYPT_KEY | DM_ACTIVE_CRYPT_KEYSIZE, &dmd) < 0)
3025                 return NULL;
3026
3027         if (single_segment(&dmd) && tgt->type == DM_CRYPT &&
3028             (dmd.flags & CRYPT_ACTIVATE_KEYRING_KEY) && tgt->u.crypt.vk->key_description)
3029                 desc = strdup(tgt->u.crypt.vk->key_description);
3030
3031         dm_targets_free(cd, &dmd);
3032
3033         return desc;
3034 }
3035
3036 int crypt_suspend(struct crypt_device *cd,
3037                   const char *name)
3038 {
3039         char *key_desc;
3040         crypt_status_info ci;
3041         int r;
3042         uint32_t dmflags = DM_SUSPEND_WIPE_KEY;
3043
3044         /* FIXME: check context uuid matches the dm-crypt device uuid (onlyLUKS branching) */
3045
3046         if (!cd || !name)
3047                 return -EINVAL;
3048
3049         log_dbg(cd, "Suspending volume %s.", name);
3050
3051         if (cd->type)
3052                 r = onlyLUKS(cd);
3053         else {
3054                 r = crypt_uuid_type_cmp(cd, CRYPT_LUKS1);
3055                 if (r < 0)
3056                         r = crypt_uuid_type_cmp(cd, CRYPT_LUKS2);
3057                 if (r < 0)
3058                         log_err(cd, _("This operation is supported only for LUKS device."));
3059         }
3060
3061         if (r < 0)
3062                 return r;
3063
3064         ci = crypt_status(NULL, name);
3065         if (ci < CRYPT_ACTIVE) {
3066                 log_err(cd, _("Volume %s is not active."), name);
3067                 return -EINVAL;
3068         }
3069
3070         dm_backend_init(cd);
3071
3072         r = dm_status_suspended(cd, name);
3073         if (r < 0)
3074                 goto out;
3075
3076         if (r) {
3077                 log_err(cd, _("Volume %s is already suspended."), name);
3078                 r = -EINVAL;
3079                 goto out;
3080         }
3081
3082         key_desc = crypt_get_device_key_description(cd, name);
3083
3084         /* we can't simply wipe wrapped keys */
3085         if (crypt_cipher_wrapped_key(crypt_get_cipher(cd), crypt_get_cipher_mode(cd)))
3086                 dmflags &= ~DM_SUSPEND_WIPE_KEY;
3087
3088         r = dm_suspend_device(cd, name, dmflags);
3089         if (r == -ENOTSUP)
3090                 log_err(cd, _("Suspend is not supported for device %s."), name);
3091         else if (r)
3092                 log_err(cd, _("Error during suspending device %s."), name);
3093         else
3094                 crypt_drop_keyring_key_by_description(cd, key_desc, LOGON_KEY);
3095         free(key_desc);
3096 out:
3097         dm_backend_exit(cd);
3098         return r;
3099 }
3100
3101 /* key must be properly verified */
3102 static int resume_by_volume_key(struct crypt_device *cd,
3103                 struct volume_key *vk,
3104                 const char *name)
3105 {
3106         int digest, r;
3107         struct volume_key *zerokey = NULL;
3108
3109         if (crypt_is_cipher_null(crypt_get_cipher_spec(cd))) {
3110                 zerokey = crypt_alloc_volume_key(0, NULL);
3111                 if (!zerokey)
3112                         return -ENOMEM;
3113                 vk = zerokey;
3114         } else if (crypt_use_keyring_for_vk(cd)) {
3115                 /* LUKS2 path only */
3116                 digest = LUKS2_digest_by_segment(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
3117                 if (digest < 0)
3118                         return -EINVAL;
3119                 r = LUKS2_volume_key_load_in_keyring_by_digest(cd,
3120                                         &cd->u.luks2.hdr, vk, digest);
3121                 if (r < 0)
3122                         return r;
3123         }
3124
3125         r = dm_resume_and_reinstate_key(cd, name, vk);
3126
3127         if (r == -ENOTSUP)
3128                 log_err(cd, _("Resume is not supported for device %s."), name);
3129         else if (r)
3130                 log_err(cd, _("Error during resuming device %s."), name);
3131
3132         if (r < 0)
3133                 crypt_drop_keyring_key(cd, vk);
3134
3135         crypt_free_volume_key(zerokey);
3136
3137         return r;
3138 }
3139
3140 int crypt_resume_by_passphrase(struct crypt_device *cd,
3141                                const char *name,
3142                                int keyslot,
3143                                const char *passphrase,
3144                                size_t passphrase_size)
3145 {
3146         struct volume_key *vk = NULL;
3147         int r;
3148
3149         /* FIXME: check context uuid matches the dm-crypt device uuid */
3150
3151         if (!passphrase || !name)
3152                 return -EINVAL;
3153
3154         log_dbg(cd, "Resuming volume %s.", name);
3155
3156         if ((r = onlyLUKS(cd)))
3157                 return r;
3158
3159         r = dm_status_suspended(cd, name);
3160         if (r < 0)
3161                 return r;
3162
3163         if (!r) {
3164                 log_err(cd, _("Volume %s is not suspended."), name);
3165                 return -EINVAL;
3166         }
3167
3168         if (isLUKS1(cd->type))
3169                 r = LUKS_open_key_with_hdr(keyslot, passphrase, passphrase_size,
3170                                            &cd->u.luks1.hdr, &vk, cd);
3171         else
3172                 r = LUKS2_keyslot_open(cd, keyslot, CRYPT_DEFAULT_SEGMENT, passphrase, passphrase_size, &vk);
3173
3174         if  (r < 0)
3175                 return r;
3176
3177         keyslot = r;
3178
3179         r = resume_by_volume_key(cd, vk, name);
3180
3181         crypt_free_volume_key(vk);
3182         return r < 0 ? r : keyslot;
3183 }
3184
3185 int crypt_resume_by_keyfile_device_offset(struct crypt_device *cd,
3186                                           const char *name,
3187                                           int keyslot,
3188                                           const char *keyfile,
3189                                           size_t keyfile_size,
3190                                           uint64_t keyfile_offset)
3191 {
3192         struct volume_key *vk = NULL;
3193         char *passphrase_read = NULL;
3194         size_t passphrase_size_read;
3195         int r;
3196
3197         /* FIXME: check context uuid matches the dm-crypt device uuid */
3198
3199         if (!name || !keyfile)
3200                 return -EINVAL;
3201
3202         log_dbg(cd, "Resuming volume %s.", name);
3203
3204         if ((r = onlyLUKS(cd)))
3205                 return r;
3206
3207         r = dm_status_suspended(cd, name);
3208         if (r < 0)
3209                 return r;
3210
3211         if (!r) {
3212                 log_err(cd, _("Volume %s is not suspended."), name);
3213                 return -EINVAL;
3214         }
3215
3216         r = crypt_keyfile_device_read(cd, keyfile,
3217                                       &passphrase_read, &passphrase_size_read,
3218                                       keyfile_offset, keyfile_size, 0);
3219         if (r < 0)
3220                 return r;
3221
3222         if (isLUKS1(cd->type))
3223                 r = LUKS_open_key_with_hdr(keyslot, passphrase_read, passphrase_size_read,
3224                                            &cd->u.luks1.hdr, &vk, cd);
3225         else
3226                 r = LUKS2_keyslot_open(cd, keyslot, CRYPT_DEFAULT_SEGMENT, passphrase_read, passphrase_size_read, &vk);
3227
3228         crypt_safe_free(passphrase_read);
3229         if (r < 0)
3230                 return r;
3231
3232         keyslot = r;
3233
3234         r = resume_by_volume_key(cd, vk, name);
3235
3236         crypt_free_volume_key(vk);
3237         return r < 0 ? r : keyslot;
3238 }
3239
3240 int crypt_resume_by_keyfile(struct crypt_device *cd,
3241                             const char *name,
3242                             int keyslot,
3243                             const char *keyfile,
3244                             size_t keyfile_size)
3245 {
3246         return crypt_resume_by_keyfile_device_offset(cd, name, keyslot,
3247                                               keyfile, keyfile_size, 0);
3248 }
3249
3250 int crypt_resume_by_keyfile_offset(struct crypt_device *cd,
3251                                    const char *name,
3252                                    int keyslot,
3253                                    const char *keyfile,
3254                                    size_t keyfile_size,
3255                                    size_t keyfile_offset)
3256 {
3257         return crypt_resume_by_keyfile_device_offset(cd, name, keyslot,
3258                                       keyfile, keyfile_size, keyfile_offset);
3259 }
3260
3261 int crypt_resume_by_volume_key(struct crypt_device *cd,
3262         const char *name,
3263         const char *volume_key,
3264         size_t volume_key_size)
3265 {
3266         struct volume_key *vk = NULL;
3267         int r;
3268
3269         if (!name || !volume_key)
3270                 return -EINVAL;
3271
3272         log_dbg(cd, "Resuming volume %s by volume key.", name);
3273
3274         if ((r = onlyLUKS(cd)))
3275                 return r;
3276
3277         r = dm_status_suspended(cd, name);
3278         if (r < 0)
3279                 return r;
3280
3281         if (!r) {
3282                 log_err(cd, _("Volume %s is not suspended."), name);
3283                 return -EINVAL;
3284         }
3285
3286         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
3287         if (!vk)
3288                 return -ENOMEM;
3289
3290         if (isLUKS1(cd->type))
3291                 r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
3292         else if (isLUKS2(cd->type))
3293                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
3294         else
3295                 r = -EINVAL;
3296         if (r == -EPERM || r == -ENOENT)
3297                 log_err(cd, _("Volume key does not match the volume."));
3298
3299         if (r >= 0)
3300                 r = resume_by_volume_key(cd, vk, name);
3301
3302         crypt_free_volume_key(vk);
3303         return r;
3304 }
3305
3306 /*
3307  * Keyslot manipulation
3308  */
3309 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
3310         int keyslot, // -1 any
3311         const char *passphrase,
3312         size_t passphrase_size,
3313         const char *new_passphrase,
3314         size_t new_passphrase_size)
3315 {
3316         int digest, r, active_slots;
3317         struct luks2_keyslot_params params;
3318         struct volume_key *vk = NULL;
3319
3320         log_dbg(cd, "Adding new keyslot, existing passphrase %sprovided,"
3321                 "new passphrase %sprovided.",
3322                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
3323
3324         if ((r = onlyLUKS(cd)))
3325                 return r;
3326
3327         if (!passphrase || !new_passphrase)
3328                 return -EINVAL;
3329
3330         r = keyslot_verify_or_find_empty(cd, &keyslot);
3331         if (r)
3332                 return r;
3333
3334         if (isLUKS1(cd->type))
3335                 active_slots = LUKS_keyslot_active_count(&cd->u.luks1.hdr);
3336         else
3337                 active_slots = LUKS2_keyslot_active_count(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
3338         if (active_slots == 0) {
3339                 /* No slots used, try to use pre-generated key in header */
3340                 if (cd->volume_key) {
3341                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
3342                         r = vk ? 0 : -ENOMEM;
3343                 } else {
3344                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided."));
3345                         return -EINVAL;
3346                 }
3347         } else if (active_slots < 0)
3348                 return -EINVAL;
3349         else {
3350                 /* Passphrase provided, use it to unlock existing keyslot */
3351                 if (isLUKS1(cd->type))
3352                         r = LUKS_open_key_with_hdr(CRYPT_ANY_SLOT, passphrase,
3353                                                    passphrase_size, &cd->u.luks1.hdr, &vk, cd);
3354                 else
3355                         r = LUKS2_keyslot_open(cd, CRYPT_ANY_SLOT, CRYPT_DEFAULT_SEGMENT, passphrase,
3356                                                 passphrase_size, &vk);
3357         }
3358
3359         if (r < 0)
3360                 goto out;
3361
3362         if (isLUKS1(cd->type))
3363                 r = LUKS_set_key(keyslot, CONST_CAST(char*)new_passphrase,
3364                                  new_passphrase_size, &cd->u.luks1.hdr, vk, cd);
3365         else {
3366                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
3367                 digest = r;
3368
3369                 if (r >= 0)
3370                         r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
3371
3372                 if (r >= 0)
3373                         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot, digest, 1, 0);
3374
3375                 if (r >= 0)
3376                         r = LUKS2_keyslot_store(cd,  &cd->u.luks2.hdr, keyslot,
3377                                                 CONST_CAST(char*)new_passphrase,
3378                                                 new_passphrase_size, vk, &params);
3379         }
3380
3381         if (r < 0)
3382                 goto out;
3383
3384         r = 0;
3385 out:
3386         crypt_free_volume_key(vk);
3387         if (r < 0) {
3388                 _luks2_reload(cd);
3389                 return r;
3390         }
3391         return keyslot;
3392 }
3393
3394 int crypt_keyslot_change_by_passphrase(struct crypt_device *cd,
3395         int keyslot_old,
3396         int keyslot_new,
3397         const char *passphrase,
3398         size_t passphrase_size,
3399         const char *new_passphrase,
3400         size_t new_passphrase_size)
3401 {
3402         int digest = -1, r;
3403         struct luks2_keyslot_params params;
3404         struct volume_key *vk = NULL;
3405
3406         if (!passphrase || !new_passphrase)
3407                 return -EINVAL;
3408
3409         log_dbg(cd, "Changing passphrase from old keyslot %d to new %d.",
3410                 keyslot_old, keyslot_new);
3411
3412         if ((r = onlyLUKS(cd)))
3413                 return r;
3414
3415         if (isLUKS1(cd->type))
3416                 r = LUKS_open_key_with_hdr(keyslot_old, passphrase, passphrase_size,
3417                                            &cd->u.luks1.hdr, &vk, cd);
3418         else if (isLUKS2(cd->type)) {
3419                 r = LUKS2_keyslot_open(cd, keyslot_old, CRYPT_ANY_SEGMENT, passphrase, passphrase_size, &vk);
3420                 /* will fail for keyslots w/o digest. fix if supported in a future */
3421                 if (r >= 0) {
3422                         digest = LUKS2_digest_by_keyslot(&cd->u.luks2.hdr, r);
3423                         if (digest < 0)
3424                                 r = -EINVAL;
3425                 }
3426         } else
3427                 r = -EINVAL;
3428         if (r < 0)
3429                 goto out;
3430
3431         if (keyslot_old != CRYPT_ANY_SLOT && keyslot_old != r) {
3432                 log_dbg(cd, "Keyslot mismatch.");
3433                 goto out;
3434         }
3435         keyslot_old = r;
3436
3437         if (keyslot_new == CRYPT_ANY_SLOT) {
3438                 if (isLUKS1(cd->type))
3439                         keyslot_new = LUKS_keyslot_find_empty(&cd->u.luks1.hdr);
3440                 else if (isLUKS2(cd->type))
3441                         keyslot_new = LUKS2_keyslot_find_empty(&cd->u.luks2.hdr);
3442                 if (keyslot_new < 0)
3443                         keyslot_new = keyslot_old;
3444         }
3445         log_dbg(cd, "Key change, old slot %d, new slot %d.", keyslot_old, keyslot_new);
3446
3447         if (isLUKS1(cd->type)) {
3448                 if (keyslot_old == keyslot_new) {
3449                         log_dbg(cd, "Key slot %d is going to be overwritten.", keyslot_old);
3450                         (void)crypt_keyslot_destroy(cd, keyslot_old);
3451                 }
3452                 r = LUKS_set_key(keyslot_new, new_passphrase, new_passphrase_size,
3453                                  &cd->u.luks1.hdr, vk, cd);
3454         } else if (isLUKS2(cd->type)) {
3455                 r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
3456                 if (r)
3457                         goto out;
3458
3459                 if (keyslot_old != keyslot_new) {
3460                         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot_new, digest, 1, 0);
3461                         if (r < 0)
3462                                 goto out;
3463                         r = LUKS2_token_assignment_copy(cd, &cd->u.luks2.hdr, keyslot_old, keyslot_new, 0);
3464                         if (r < 0)
3465                                 goto out;
3466                 } else {
3467                         log_dbg(cd, "Key slot %d is going to be overwritten.", keyslot_old);
3468                         /* FIXME: improve return code so that we can detect area is damaged */
3469                         r = LUKS2_keyslot_wipe(cd, &cd->u.luks2.hdr, keyslot_old, 1);
3470                         if (r) {
3471                                 /* (void)crypt_keyslot_destroy(cd, keyslot_old); */
3472                                 r = -EINVAL;
3473                                 goto out;
3474                         }
3475                 }
3476
3477                 r = LUKS2_keyslot_store(cd,  &cd->u.luks2.hdr,
3478                                         keyslot_new, new_passphrase,
3479                                         new_passphrase_size, vk, &params);
3480         } else
3481                 r = -EINVAL;
3482
3483         if (r >= 0 && keyslot_old != keyslot_new)
3484                 r = crypt_keyslot_destroy(cd, keyslot_old);
3485
3486         if (r < 0)
3487                 log_err(cd, _("Failed to swap new key slot."));
3488 out:
3489         crypt_free_volume_key(vk);
3490         if (r < 0) {
3491                 _luks2_reload(cd);
3492                 return r;
3493         }
3494         return keyslot_new;
3495 }
3496
3497 int crypt_keyslot_add_by_keyfile_device_offset(struct crypt_device *cd,
3498         int keyslot,
3499         const char *keyfile,
3500         size_t keyfile_size,
3501         uint64_t keyfile_offset,
3502         const char *new_keyfile,
3503         size_t new_keyfile_size,
3504         uint64_t new_keyfile_offset)
3505 {
3506         int digest, r, active_slots;
3507         size_t passwordLen, new_passwordLen;
3508         struct luks2_keyslot_params params;
3509         char *password = NULL, *new_password = NULL;
3510         struct volume_key *vk = NULL;
3511
3512         if (!keyfile || !new_keyfile)
3513                 return -EINVAL;
3514
3515         log_dbg(cd, "Adding new keyslot, existing keyfile %s, new keyfile %s.",
3516                 keyfile, new_keyfile);
3517
3518         if ((r = onlyLUKS(cd)))
3519                 return r;
3520
3521         r = keyslot_verify_or_find_empty(cd, &keyslot);
3522         if (r)
3523                 return r;
3524
3525         if (isLUKS1(cd->type))
3526                 active_slots = LUKS_keyslot_active_count(&cd->u.luks1.hdr);
3527         else
3528                 active_slots = LUKS2_keyslot_active_count(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
3529         if (active_slots == 0) {
3530                 /* No slots used, try to use pre-generated key in header */
3531                 if (cd->volume_key) {
3532                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
3533                         r = vk ? 0 : -ENOMEM;
3534                 } else {
3535                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided."));
3536                         return -EINVAL;
3537                 }
3538         } else {
3539                 r = crypt_keyfile_device_read(cd, keyfile,
3540                                        &password, &passwordLen,
3541                                        keyfile_offset, keyfile_size, 0);
3542                 if (r < 0)
3543                         goto out;
3544
3545                 if (isLUKS1(cd->type))
3546                         r = LUKS_open_key_with_hdr(CRYPT_ANY_SLOT, password, passwordLen,
3547                                                    &cd->u.luks1.hdr, &vk, cd);
3548                 else
3549                         r = LUKS2_keyslot_open(cd, CRYPT_ANY_SLOT, CRYPT_DEFAULT_SEGMENT, password, passwordLen, &vk);
3550         }
3551
3552         if (r < 0)
3553                 goto out;
3554
3555         r = crypt_keyfile_device_read(cd, new_keyfile,
3556                                &new_password, &new_passwordLen,
3557                                new_keyfile_offset, new_keyfile_size, 0);
3558         if (r < 0)
3559                 goto out;
3560
3561         if (isLUKS1(cd->type))
3562                 r = LUKS_set_key(keyslot, new_password, new_passwordLen,
3563                                  &cd->u.luks1.hdr, vk, cd);
3564         else {
3565                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
3566                 digest = r;
3567
3568                 if (r >= 0)
3569                         r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
3570
3571                 if (r >= 0)
3572                         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot, digest, 1, 0);
3573
3574                 if (r >= 0)
3575                         r = LUKS2_keyslot_store(cd,  &cd->u.luks2.hdr, keyslot,
3576                                                 new_password, new_passwordLen, vk, &params);
3577         }
3578 out:
3579         crypt_safe_free(password);
3580         crypt_safe_free(new_password);
3581         crypt_free_volume_key(vk);
3582         if (r < 0) {
3583                 _luks2_reload(cd);
3584                 return r;
3585         }
3586         return keyslot;
3587 }
3588
3589 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
3590         int keyslot,
3591         const char *keyfile,
3592         size_t keyfile_size,
3593         const char *new_keyfile,
3594         size_t new_keyfile_size)
3595 {
3596         return crypt_keyslot_add_by_keyfile_device_offset(cd, keyslot,
3597                                 keyfile, keyfile_size, 0,
3598                                 new_keyfile, new_keyfile_size, 0);
3599 }
3600
3601 int crypt_keyslot_add_by_keyfile_offset(struct crypt_device *cd,
3602         int keyslot,
3603         const char *keyfile,
3604         size_t keyfile_size,
3605         size_t keyfile_offset,
3606         const char *new_keyfile,
3607         size_t new_keyfile_size,
3608         size_t new_keyfile_offset)
3609 {
3610         return crypt_keyslot_add_by_keyfile_device_offset(cd, keyslot,
3611                                 keyfile, keyfile_size, keyfile_offset,
3612                                 new_keyfile, new_keyfile_size, new_keyfile_offset);
3613 }
3614
3615 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
3616         int keyslot,
3617         const char *volume_key,
3618         size_t volume_key_size,
3619         const char *passphrase,
3620         size_t passphrase_size)
3621 {
3622         struct volume_key *vk = NULL;
3623         int r;
3624
3625         if (!passphrase)
3626                 return -EINVAL;
3627
3628         log_dbg(cd, "Adding new keyslot %d using volume key.", keyslot);
3629
3630         if ((r = onlyLUKS(cd)))
3631                 return r;
3632
3633         if (isLUKS2(cd->type))
3634                 return crypt_keyslot_add_by_key(cd, keyslot,
3635                                 volume_key, volume_key_size, passphrase,
3636                                 passphrase_size, 0);
3637
3638         r = keyslot_verify_or_find_empty(cd, &keyslot);
3639         if (r < 0)
3640                 return r;
3641
3642         if (volume_key)
3643                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
3644         else if (cd->volume_key)
3645                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
3646
3647         if (!vk)
3648                 return -ENOMEM;
3649
3650         r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
3651         if (r < 0)
3652                 log_err(cd, _("Volume key does not match the volume."));
3653         else
3654                 r = LUKS_set_key(keyslot, passphrase, passphrase_size,
3655                         &cd->u.luks1.hdr, vk, cd);
3656
3657         crypt_free_volume_key(vk);
3658         return (r < 0) ? r : keyslot;
3659 }
3660
3661 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
3662 {
3663         crypt_keyslot_info ki;
3664         int r;
3665
3666         log_dbg(cd, "Destroying keyslot %d.", keyslot);
3667
3668         if ((r = _onlyLUKS(cd, CRYPT_CD_UNRESTRICTED)))
3669                 return r;
3670
3671         ki = crypt_keyslot_status(cd, keyslot);
3672         if (ki == CRYPT_SLOT_INVALID) {
3673                 log_err(cd, _("Key slot %d is invalid."), keyslot);
3674                 return -EINVAL;
3675         }
3676
3677         if (isLUKS1(cd->type)) {
3678                 if (ki == CRYPT_SLOT_INACTIVE) {
3679                         log_err(cd, _("Keyslot %d is not active."), keyslot);
3680                         return -EINVAL;
3681                 }
3682                 return LUKS_del_key(keyslot, &cd->u.luks1.hdr, cd);
3683         }
3684
3685         return LUKS2_keyslot_wipe(cd, &cd->u.luks2.hdr, keyslot, 0);
3686 }
3687
3688 static int _check_header_data_overlap(struct crypt_device *cd, const char *name)
3689 {
3690         if (!name || !isLUKS(cd->type))
3691                 return 0;
3692
3693         if (device_is_identical(crypt_data_device(cd), crypt_metadata_device(cd)) <= 0)
3694                 return 0;
3695
3696         /* FIXME: check real header size */
3697         if (crypt_get_data_offset(cd) == 0) {
3698                 log_err(cd, _("Device header overlaps with data area."));
3699                 return -EINVAL;
3700         }
3701
3702         return 0;
3703 }
3704
3705 static int check_devices(struct crypt_device *cd, const char *name, const char *iname, uint32_t *flags)
3706 {
3707         int r;
3708
3709         if (!flags || !name)
3710                 return -EINVAL;
3711
3712         if (iname) {
3713                 r = dm_status_device(cd, iname);
3714                 if (r >= 0 && !(*flags & CRYPT_ACTIVATE_REFRESH))
3715                         return -EBUSY;
3716                 if (r < 0 && r != -ENODEV)
3717                         return r;
3718                 if (r == -ENODEV)
3719                         *flags &= ~CRYPT_ACTIVATE_REFRESH;
3720         }
3721
3722         r = dm_status_device(cd, name);
3723         if (r >= 0 && !(*flags & CRYPT_ACTIVATE_REFRESH))
3724                 return -EBUSY;
3725         if (r < 0 && r != -ENODEV)
3726                 return r;
3727         if (r == -ENODEV)
3728                 *flags &= ~CRYPT_ACTIVATE_REFRESH;
3729
3730         return 0;
3731 }
3732
3733 static int _create_device_with_integrity(struct crypt_device *cd,
3734         const char *type, const char *name, const char *iname,
3735         const char *ipath, struct crypt_dm_active_device *dmd,
3736         struct crypt_dm_active_device *dmdi)
3737 {
3738         int r;
3739         enum devcheck device_check;
3740         struct dm_target *tgt;
3741         struct device *device = NULL;
3742
3743         if (!single_segment(dmd))
3744                 return -EINVAL;
3745
3746         tgt = &dmd->segment;
3747         if (tgt->type != DM_CRYPT)
3748                 return -EINVAL;
3749
3750         device_check = dmd->flags & CRYPT_ACTIVATE_SHARED ? DEV_OK : DEV_EXCL;
3751
3752         r = INTEGRITY_activate_dmd_device(cd, iname, CRYPT_INTEGRITY, dmdi, 0);
3753         if (r)
3754                 return r;
3755
3756         r = device_alloc(cd, &device, ipath);
3757         if (r < 0)
3758                 goto out;
3759         tgt->data_device = device;
3760
3761         r = device_block_adjust(cd, tgt->data_device, device_check,
3762                                 tgt->u.crypt.offset, &dmd->size, &dmd->flags);
3763
3764         if (!r)
3765                 r = dm_create_device(cd, name, type, dmd);
3766 out:
3767         if (r < 0)
3768                 dm_remove_device(cd, iname, 0);
3769
3770         device_free(cd, device);
3771         return r;
3772 }
3773
3774 static int kernel_keyring_support(void)
3775 {
3776         static unsigned _checked = 0;
3777
3778         if (!_checked) {
3779                 _kernel_keyring_supported = keyring_check();
3780                 _checked = 1;
3781         }
3782
3783         return _kernel_keyring_supported;
3784 }
3785
3786 static int dmcrypt_keyring_bug(void)
3787 {
3788         uint64_t kversion;
3789
3790         if (kernel_version(&kversion))
3791                 return 1;
3792         return kversion < version(4,15,0,0);
3793 }
3794
3795 int create_or_reload_device(struct crypt_device *cd, const char *name,
3796                      const char *type, struct crypt_dm_active_device *dmd)
3797 {
3798         int r;
3799         enum devcheck device_check;
3800         struct dm_target *tgt;
3801
3802         if (!type || !name || !single_segment(dmd))
3803                 return -EINVAL;
3804
3805         tgt = &dmd->segment;
3806         if (tgt->type != DM_CRYPT)
3807                 return -EINVAL;
3808
3809         /* drop CRYPT_ACTIVATE_REFRESH flag if any device is inactive */
3810         r = check_devices(cd, name, NULL, &dmd->flags);
3811         if (r)
3812                 return r;
3813
3814         if (dmd->flags & CRYPT_ACTIVATE_REFRESH)
3815                 r = _reload_device(cd, name, dmd);
3816         else {
3817                 device_check = dmd->flags & CRYPT_ACTIVATE_SHARED ? DEV_OK : DEV_EXCL;
3818
3819                 r = device_block_adjust(cd, tgt->data_device, device_check,
3820                                         tgt->u.crypt.offset, &dmd->size, &dmd->flags);
3821                 if (!r) {
3822                         tgt->size = dmd->size;
3823                         r = dm_create_device(cd, name, type, dmd);
3824                 }
3825         }
3826
3827         return r;
3828 }
3829
3830 int create_or_reload_device_with_integrity(struct crypt_device *cd, const char *name,
3831                      const char *type, struct crypt_dm_active_device *dmd,
3832                      struct crypt_dm_active_device *dmdi)
3833 {
3834         int r;
3835         const char *iname = NULL;
3836         char *ipath = NULL;
3837
3838         if (!type || !name || !dmd || !dmdi)
3839                 return -EINVAL;
3840
3841         if (asprintf(&ipath, "%s/%s_dif", dm_get_dir(), name) < 0)
3842                 return -ENOMEM;
3843         iname = ipath + strlen(dm_get_dir()) + 1;
3844
3845         /* drop CRYPT_ACTIVATE_REFRESH flag if any device is inactive */
3846         r = check_devices(cd, name, iname, &dmd->flags);
3847         if (r)
3848                 goto out;
3849
3850         if (dmd->flags & CRYPT_ACTIVATE_REFRESH)
3851                 r = _reload_device_with_integrity(cd, name, iname, ipath, dmd, dmdi);
3852         else
3853                 r = _create_device_with_integrity(cd, type, name, iname, ipath, dmd, dmdi);
3854 out:
3855         free(ipath);
3856
3857         return r;
3858 }
3859
3860 /* See fixmes in _open_and_activate_luks2 */
3861 int update_reencryption_flag(struct crypt_device *cd, int enable, bool commit);
3862
3863 /* TODO: This function should 1:1 with pre-reencryption code */
3864 static int _open_and_activate(struct crypt_device *cd,
3865         int keyslot,
3866         const char *name,
3867         const char *passphrase,
3868         size_t passphrase_size,
3869         uint32_t flags)
3870 {
3871         bool use_keyring;
3872         int r;
3873         struct volume_key *vk = NULL;
3874
3875         r = LUKS2_keyslot_open(cd, keyslot,
3876                                (flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) ?
3877                                CRYPT_ANY_SEGMENT : CRYPT_DEFAULT_SEGMENT,
3878                                passphrase, passphrase_size, &vk);
3879         if (r < 0)
3880                 return r;
3881         keyslot = r;
3882
3883         if (!crypt_use_keyring_for_vk(cd))
3884                 use_keyring = false;
3885         else
3886                 use_keyring = ((name && !crypt_is_cipher_null(crypt_get_cipher(cd))) ||
3887                                (flags & CRYPT_ACTIVATE_KEYRING_KEY));
3888
3889         if (use_keyring) {
3890                 r = LUKS2_volume_key_load_in_keyring_by_keyslot(cd,
3891                                 &cd->u.luks2.hdr, vk, keyslot);
3892                 if (r < 0)
3893                         goto out;
3894                 flags |= CRYPT_ACTIVATE_KEYRING_KEY;
3895         }
3896
3897         if (name)
3898                 r = LUKS2_activate(cd, name, vk, flags);
3899 out:
3900         if (r < 0)
3901                 crypt_drop_keyring_key(cd, vk);
3902         crypt_free_volume_key(vk);
3903
3904         return r < 0 ? r : keyslot;
3905 }
3906
3907 #if USE_LUKS2_REENCRYPTION
3908 static int load_all_keys(struct crypt_device *cd, struct luks2_hdr *hdr, struct volume_key *vks)
3909 {
3910         int r;
3911         struct volume_key *vk = vks;
3912
3913         while (vk) {
3914                 r = LUKS2_volume_key_load_in_keyring_by_digest(cd, hdr, vk, crypt_volume_key_get_id(vk));
3915                 if (r < 0)
3916                         return r;
3917                 vk = crypt_volume_key_next(vk);
3918         }
3919
3920         return 0;
3921 }
3922
3923 static int _open_all_keys(struct crypt_device *cd,
3924         struct luks2_hdr *hdr,
3925         int keyslot,
3926         const char *passphrase,
3927         size_t passphrase_size,
3928         uint32_t flags,
3929         struct volume_key **vks)
3930 {
3931         int r, segment;
3932         struct volume_key *_vks = NULL;
3933         crypt_reencrypt_info ri = LUKS2_reencrypt_status(hdr);
3934
3935         segment = (flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) ? CRYPT_ANY_SEGMENT : CRYPT_DEFAULT_SEGMENT;
3936
3937         switch (ri) {
3938         case CRYPT_REENCRYPT_NONE:
3939                 r = LUKS2_keyslot_open(cd, keyslot, segment, passphrase, passphrase_size, &_vks);
3940                 break;
3941         case CRYPT_REENCRYPT_CLEAN:
3942         case CRYPT_REENCRYPT_CRASH:
3943                 if (segment == CRYPT_ANY_SEGMENT)
3944                         r = LUKS2_keyslot_open(cd, keyslot, segment, passphrase,
3945                                                passphrase_size, &_vks);
3946                 else
3947                         r = LUKS2_keyslot_open_all_segments(cd, keyslot,
3948                                         keyslot, passphrase, passphrase_size,
3949                                         &_vks);
3950                 break;
3951         default:
3952                 r = -EINVAL;
3953         }
3954
3955         if (keyslot == CRYPT_ANY_SLOT)
3956                 keyslot = r;
3957
3958         if (r >= 0 && (flags & CRYPT_ACTIVATE_KEYRING_KEY))
3959                 r = load_all_keys(cd, hdr, _vks);
3960
3961         if (r >= 0 && vks)
3962                 MOVE_REF(*vks, _vks);
3963
3964         if (r < 0)
3965                 crypt_drop_keyring_key(cd, _vks);
3966         crypt_free_volume_key(_vks);
3967
3968         return r < 0 ? r : keyslot;
3969 }
3970
3971 static int _open_and_activate_reencrypt_device(struct crypt_device *cd,
3972         struct luks2_hdr *hdr,
3973         int keyslot,
3974         const char *name,
3975         const char *passphrase,
3976         size_t passphrase_size,
3977         uint32_t flags)
3978 {
3979         bool dynamic_size;
3980         crypt_reencrypt_info ri;
3981         uint64_t minimal_size, device_size;
3982         struct volume_key *vks = NULL;
3983         int r = 0;
3984         struct crypt_lock_handle *reencrypt_lock = NULL;
3985
3986         if (crypt_use_keyring_for_vk(cd))
3987                 flags |= CRYPT_ACTIVATE_KEYRING_KEY;
3988
3989         r = LUKS2_reencrypt_lock(cd, &reencrypt_lock);
3990         if (r) {
3991                 if (r == -EBUSY)
3992                         log_err(cd, _("Reencryption in-progress. Cannot activate device."));
3993                 else
3994                         log_err(cd, _("Failed to get reencryption lock."));
3995                 return r;
3996         }
3997
3998         if ((r = crypt_load(cd, CRYPT_LUKS2, NULL)))
3999                 goto err;
4000
4001         ri = LUKS2_reencrypt_status(hdr);
4002
4003         if (ri == CRYPT_REENCRYPT_CRASH) {
4004                 r = LUKS2_reencrypt_locked_recovery_by_passphrase(cd, keyslot,
4005                                 keyslot, passphrase, passphrase_size, flags, &vks);
4006                 if (r < 0) {
4007                         log_err(cd, _("LUKS2 reencryption recovery failed."));
4008                         goto err;
4009                 }
4010                 keyslot = r;
4011
4012                 ri = LUKS2_reencrypt_status(hdr);
4013         }
4014
4015         /* recovery finished reencryption or it's already finished */
4016         if (ri == CRYPT_REENCRYPT_NONE) {
4017                 crypt_drop_keyring_key(cd, vks);
4018                 crypt_free_volume_key(vks);
4019                 LUKS2_reencrypt_unlock(cd, reencrypt_lock);
4020                 return _open_and_activate(cd, keyslot, name, passphrase, passphrase_size, flags);
4021         }
4022
4023         if (ri > CRYPT_REENCRYPT_CLEAN) {
4024                 r = -EINVAL;
4025                 goto err;
4026         }
4027
4028         if (LUKS2_get_data_size(hdr, &minimal_size, &dynamic_size))
4029                 goto err;
4030
4031         if (!vks) {
4032                 r = _open_all_keys(cd, hdr, keyslot, passphrase, passphrase_size, flags, &vks);
4033                 if (r >= 0)
4034                         keyslot = r;
4035         }
4036
4037         if (r >= 0) {
4038                 r = LUKS2_reencrypt_digest_verify(cd, hdr, vks);
4039                 if (r < 0)
4040                         goto err;
4041         }
4042
4043         log_dbg(cd, "Entering clean reencryption state mode.");
4044
4045         if (r >= 0)
4046                 r = LUKS2_reencrypt_check_device_size(cd, hdr, minimal_size, &device_size, true, dynamic_size);
4047
4048         if (r >= 0)
4049                 r = LUKS2_activate_multi(cd, name, vks, device_size >> SECTOR_SHIFT, flags);
4050 err:
4051         LUKS2_reencrypt_unlock(cd, reencrypt_lock);
4052         if (r < 0)
4053                 crypt_drop_keyring_key(cd, vks);
4054         crypt_free_volume_key(vks);
4055
4056         return r < 0 ? r : keyslot;
4057 }
4058
4059 /*
4060  * Activation/deactivation of a device
4061  */
4062 static int _open_and_activate_luks2(struct crypt_device *cd,
4063         int keyslot,
4064         const char *name,
4065         const char *passphrase,
4066         size_t passphrase_size,
4067         uint32_t flags)
4068 {
4069         crypt_reencrypt_info ri;
4070         int r, rv;
4071         struct luks2_hdr *hdr = &cd->u.luks2.hdr;
4072         struct volume_key *vks = NULL;
4073
4074         ri = LUKS2_reencrypt_status(hdr);
4075         if (ri == CRYPT_REENCRYPT_INVALID)
4076                 return -EINVAL;
4077
4078         if (ri > CRYPT_REENCRYPT_NONE) {
4079                 if (name)
4080                         r = _open_and_activate_reencrypt_device(cd, hdr, keyslot, name, passphrase,
4081                                         passphrase_size, flags);
4082                 else {
4083                         r = _open_all_keys(cd, hdr, keyslot, passphrase,
4084                                            passphrase_size, flags, &vks);
4085                         if (r < 0)
4086                                 return r;
4087
4088                         rv = LUKS2_reencrypt_digest_verify(cd, hdr, vks);
4089                         crypt_free_volume_key(vks);
4090                         if (rv < 0)
4091                                 return rv;
4092                 }
4093         } else
4094                 r = _open_and_activate(cd, keyslot, name, passphrase,
4095                                 passphrase_size, flags);
4096
4097         return r;
4098 }
4099 #else
4100 static int _open_and_activate_luks2(struct crypt_device *cd,
4101         int keyslot,
4102         const char *name,
4103         const char *passphrase,
4104         size_t passphrase_size,
4105         uint32_t flags)
4106 {
4107         crypt_reencrypt_info ri;
4108
4109         ri = LUKS2_reencrypt_status(&cd->u.luks2.hdr);
4110         if (ri == CRYPT_REENCRYPT_INVALID)
4111                 return -EINVAL;
4112
4113         if (ri > CRYPT_REENCRYPT_NONE) {
4114                 log_err(cd, _("This operation is not supported for this device type."));
4115                 return -ENOTSUP;
4116         }
4117
4118         return _open_and_activate(cd, keyslot, name, passphrase, passphrase_size, flags);
4119 }
4120 #endif
4121
4122 static int _activate_by_passphrase(struct crypt_device *cd,
4123         const char *name,
4124         int keyslot,
4125         const char *passphrase,
4126         size_t passphrase_size,
4127         uint32_t flags)
4128 {
4129         int r;
4130         struct volume_key *vk = NULL;
4131
4132         if ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd))
4133                 return -EINVAL;
4134
4135         if ((flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) && name)
4136                 return -EINVAL;
4137
4138         r = _check_header_data_overlap(cd, name);
4139         if (r < 0)
4140                 return r;
4141
4142         if (flags & CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF)
4143                 cd->memory_hard_pbkdf_lock_enabled = true;
4144
4145         /* plain, use hashed passphrase */
4146         if (isPLAIN(cd->type)) {
4147                 r = -EINVAL;
4148                 if (!name)
4149                         goto out;
4150
4151                 r = process_key(cd, cd->u.plain.hdr.hash,
4152                                 cd->u.plain.key_size,
4153                                 passphrase, passphrase_size, &vk);
4154                 if (r < 0)
4155                         goto out;
4156
4157                 r = PLAIN_activate(cd, name, vk, cd->u.plain.hdr.size, flags);
4158                 keyslot = 0;
4159         } else if (isLUKS1(cd->type)) {
4160                 r = LUKS_open_key_with_hdr(keyslot, passphrase,
4161                                            passphrase_size, &cd->u.luks1.hdr, &vk, cd);
4162                 if (r >= 0) {
4163                         keyslot = r;
4164                         if (name)
4165                                 r = LUKS1_activate(cd, name, vk, flags);
4166                 }
4167         } else if (isLUKS2(cd->type)) {
4168                 r = _open_and_activate_luks2(cd, keyslot, name, passphrase, passphrase_size, flags);
4169                 keyslot = r;
4170         } else if (isBITLK(cd->type)) {
4171                 r = BITLK_activate(cd, name, passphrase, passphrase_size,
4172                                    &cd->u.bitlk.params, flags);
4173                 keyslot = 0;
4174         } else {
4175                 log_err(cd, _("Device type is not properly initialized."));
4176                 r = -EINVAL;
4177         }
4178 out:
4179         if (r < 0)
4180                 crypt_drop_keyring_key(cd, vk);
4181         crypt_free_volume_key(vk);
4182
4183         cd->memory_hard_pbkdf_lock_enabled = false;
4184
4185         return r < 0 ? r : keyslot;
4186 }
4187
4188 static int _activate_loopaes(struct crypt_device *cd,
4189         const char *name,
4190         char *buffer,
4191         size_t buffer_size,
4192         uint32_t flags)
4193 {
4194         int r;
4195         unsigned int key_count = 0;
4196         struct volume_key *vk = NULL;
4197
4198         r = LOOPAES_parse_keyfile(cd, &vk, cd->u.loopaes.hdr.hash, &key_count,
4199                                   buffer, buffer_size);
4200
4201         if (!r && name)
4202                 r = LOOPAES_activate(cd, name, cd->u.loopaes.cipher, key_count,
4203                                      vk, flags);
4204
4205         crypt_free_volume_key(vk);
4206
4207         return r;
4208 }
4209
4210 static int _activate_check_status(struct crypt_device *cd, const char *name, unsigned reload)
4211 {
4212         int r;
4213
4214         if (!name)
4215                 return 0;
4216
4217         r = dm_status_device(cd, name);
4218
4219         if (r >= 0 && reload)
4220                 return 0;
4221
4222         if (r >= 0 || r == -EEXIST) {
4223                 log_err(cd, _("Device %s already exists."), name);
4224                 return -EEXIST;
4225         }
4226
4227         if (r == -ENODEV)
4228                 return 0;
4229
4230         log_err(cd, _("Cannot use device %s, name is invalid or still in use."), name);
4231         return r;
4232 }
4233
4234 // activation/deactivation of device mapping
4235 int crypt_activate_by_passphrase(struct crypt_device *cd,
4236         const char *name,
4237         int keyslot,
4238         const char *passphrase,
4239         size_t passphrase_size,
4240         uint32_t flags)
4241 {
4242         int r;
4243
4244         if (!cd || !passphrase || (!name && (flags & CRYPT_ACTIVATE_REFRESH)))
4245                 return -EINVAL;
4246
4247         log_dbg(cd, "%s volume %s [keyslot %d] using passphrase.",
4248                 name ? "Activating" : "Checking", name ?: "passphrase",
4249                 keyslot);
4250
4251         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4252         if (r < 0)
4253                 return r;
4254
4255         return _activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
4256 }
4257
4258 int crypt_activate_by_keyfile_device_offset(struct crypt_device *cd,
4259         const char *name,
4260         int keyslot,
4261         const char *keyfile,
4262         size_t keyfile_size,
4263         uint64_t keyfile_offset,
4264         uint32_t flags)
4265 {
4266         char *passphrase_read = NULL;
4267         size_t passphrase_size_read;
4268         int r;
4269
4270         if (!cd || !keyfile ||
4271             ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd)))
4272                 return -EINVAL;
4273
4274         log_dbg(cd, "%s volume %s [keyslot %d] using keyfile %s.",
4275                 name ? "Activating" : "Checking", name ?: "passphrase", keyslot, keyfile);
4276
4277         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4278         if (r < 0)
4279                 return r;
4280
4281         r = crypt_keyfile_device_read(cd, keyfile,
4282                                 &passphrase_read, &passphrase_size_read,
4283                                 keyfile_offset, keyfile_size, 0);
4284         if (r < 0)
4285                 goto out;
4286
4287         if (isLOOPAES(cd->type))
4288                 r = _activate_loopaes(cd, name, passphrase_read, passphrase_size_read, flags);
4289         else
4290                 r = _activate_by_passphrase(cd, name, keyslot, passphrase_read, passphrase_size_read, flags);
4291
4292 out:
4293         crypt_safe_free(passphrase_read);
4294         return r;
4295 }
4296
4297 int crypt_activate_by_keyfile(struct crypt_device *cd,
4298         const char *name,
4299         int keyslot,
4300         const char *keyfile,
4301         size_t keyfile_size,
4302         uint32_t flags)
4303 {
4304         return crypt_activate_by_keyfile_device_offset(cd, name, keyslot, keyfile,
4305                                         keyfile_size, 0, flags);
4306 }
4307
4308 int crypt_activate_by_keyfile_offset(struct crypt_device *cd,
4309         const char *name,
4310         int keyslot,
4311         const char *keyfile,
4312         size_t keyfile_size,
4313         size_t keyfile_offset,
4314         uint32_t flags)
4315 {
4316         return crypt_activate_by_keyfile_device_offset(cd, name, keyslot, keyfile,
4317                                         keyfile_size, keyfile_offset, flags);
4318 }
4319 int crypt_activate_by_volume_key(struct crypt_device *cd,
4320         const char *name,
4321         const char *volume_key,
4322         size_t volume_key_size,
4323         uint32_t flags)
4324 {
4325         bool use_keyring;
4326         struct volume_key *vk = NULL;
4327         int r;
4328
4329         if (!cd ||
4330             ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd)))
4331                 return -EINVAL;
4332
4333         log_dbg(cd, "%s volume %s by volume key.", name ? "Activating" : "Checking",
4334                 name ?: "");
4335
4336         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4337         if (r < 0)
4338                 return r;
4339
4340         r = _check_header_data_overlap(cd, name);
4341         if (r < 0)
4342                 return r;
4343
4344         /* use key directly, no hash */
4345         if (isPLAIN(cd->type)) {
4346                 if (!name)
4347                         return -EINVAL;
4348
4349                 if (!volume_key || !volume_key_size || volume_key_size != cd->u.plain.key_size) {
4350                         log_err(cd, _("Incorrect volume key specified for plain device."));
4351                         return -EINVAL;
4352                 }
4353
4354                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4355                 if (!vk)
4356                         return -ENOMEM;
4357
4358                 r = PLAIN_activate(cd, name, vk, cd->u.plain.hdr.size, flags);
4359         } else if (isLUKS1(cd->type)) {
4360                 /* If key is not provided, try to use internal key */
4361                 if (!volume_key) {
4362                         if (!cd->volume_key) {
4363                                 log_err(cd, _("Volume key does not match the volume."));
4364                                 return -EINVAL;
4365                         }
4366                         volume_key_size = cd->volume_key->keylength;
4367                         volume_key = cd->volume_key->key;
4368                 }
4369
4370                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4371                 if (!vk)
4372                         return -ENOMEM;
4373                 r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
4374
4375                 if (r == -EPERM)
4376                         log_err(cd, _("Volume key does not match the volume."));
4377
4378                 if (!r && name)
4379                         r = LUKS1_activate(cd, name, vk, flags);
4380         } else if (isLUKS2(cd->type)) {
4381                 /* If key is not provided, try to use internal key */
4382                 if (!volume_key) {
4383                         if (!cd->volume_key) {
4384                                 log_err(cd, _("Volume key does not match the volume."));
4385                                 return -EINVAL;
4386                         }
4387                         volume_key_size = cd->volume_key->keylength;
4388                         volume_key = cd->volume_key->key;
4389                 }
4390
4391                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4392                 if (!vk)
4393                         return -ENOMEM;
4394
4395                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
4396                 if (r == -EPERM || r == -ENOENT)
4397                         log_err(cd, _("Volume key does not match the volume."));
4398                 if (r > 0)
4399                         r = 0;
4400
4401                 if (!crypt_use_keyring_for_vk(cd))
4402                         use_keyring = false;
4403                 else
4404                         use_keyring = (name && !crypt_is_cipher_null(crypt_get_cipher(cd))) || (flags & CRYPT_ACTIVATE_KEYRING_KEY);
4405
4406                 if (!r && use_keyring) {
4407                         r = LUKS2_key_description_by_segment(cd,
4408                                 &cd->u.luks2.hdr, vk, CRYPT_DEFAULT_SEGMENT);
4409                         if (!r)
4410                                 r = crypt_volume_key_load_in_keyring(cd, vk);
4411                         if (!r)
4412                                 flags |= CRYPT_ACTIVATE_KEYRING_KEY;
4413                 }
4414
4415                 if (!r && name)
4416                         r = LUKS2_activate(cd, name, vk, flags);
4417         } else if (isVERITY(cd->type)) {
4418                 r = crypt_activate_by_signed_key(cd, name, volume_key, volume_key_size, NULL, 0, flags);
4419         } else if (isTCRYPT(cd->type)) {
4420                 if (!name)
4421                         return 0;
4422                 r = TCRYPT_activate(cd, name, &cd->u.tcrypt.hdr,
4423                                     &cd->u.tcrypt.params, flags);
4424         } else if (isINTEGRITY(cd->type)) {
4425                 if (!name)
4426                         return 0;
4427                 if (volume_key) {
4428                         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4429                         if (!vk)
4430                                 return -ENOMEM;
4431                 }
4432                 r = INTEGRITY_activate(cd, name, &cd->u.integrity.params, vk,
4433                                        cd->u.integrity.journal_crypt_key,
4434                                        cd->u.integrity.journal_mac_key, flags,
4435                                        cd->u.integrity.sb_flags);
4436         } else {
4437                 log_err(cd, _("Device type is not properly initialized."));
4438                 r = -EINVAL;
4439         }
4440
4441         if (r < 0)
4442                 crypt_drop_keyring_key(cd, vk);
4443         crypt_free_volume_key(vk);
4444
4445         return r;
4446 }
4447
4448 int crypt_activate_by_signed_key(struct crypt_device *cd,
4449         const char *name,
4450         const char *volume_key,
4451         size_t volume_key_size,
4452         const char *signature,
4453         size_t signature_size,
4454         uint32_t flags)
4455 {
4456         char description[512];
4457         int r;
4458
4459         if (!cd || !isVERITY(cd->type))
4460                 return -EINVAL;
4461
4462         if (!volume_key || !volume_key_size || (!name && signature)) {
4463                 log_err(cd, _("Incorrect root hash specified for verity device."));
4464                 return -EINVAL;
4465         }
4466
4467         log_dbg(cd, "%s volume %s by %skey.", name ? "Activating" : "Checking", name ?: "", signature ? "signed " : "");
4468
4469         if (cd->u.verity.hdr.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE && !signature) {
4470                 log_err(cd, _("Root hash signature required."));
4471                 return -EINVAL;
4472         }
4473
4474         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4475         if (r < 0)
4476                 return r;
4477
4478         if (signature && !kernel_keyring_support()) {
4479                 log_err(cd, _("Kernel keyring missing: required for passing signature to kernel."));
4480                 return -EINVAL;
4481         }
4482
4483         /* volume_key == root hash */
4484         free(CONST_CAST(void*)cd->u.verity.root_hash);
4485         cd->u.verity.root_hash = NULL;
4486
4487         if (signature) {
4488                 r = snprintf(description, sizeof(description)-1, "cryptsetup:%s%s%s",
4489                              crypt_get_uuid(cd) ?: "", crypt_get_uuid(cd) ? "-" : "", name);
4490                 if (r < 0)
4491                         return -EINVAL;
4492
4493                 log_dbg(cd, "Adding signature into keyring %s", description);
4494                 r = keyring_add_key_in_thread_keyring(USER_KEY, description, signature, signature_size);
4495                 if (r) {
4496                         log_err(cd, _("Failed to load key in kernel keyring."));
4497                         return r;
4498                 }
4499         }
4500
4501         r = VERITY_activate(cd, name, volume_key, volume_key_size,
4502                             signature ? description : NULL,
4503                             cd->u.verity.fec_device,
4504                             &cd->u.verity.hdr, flags | CRYPT_ACTIVATE_READONLY);
4505
4506         if (!r) {
4507                 cd->u.verity.root_hash_size = volume_key_size;
4508                 cd->u.verity.root_hash = malloc(volume_key_size);
4509                 if (cd->u.verity.root_hash)
4510                         memcpy(CONST_CAST(void*)cd->u.verity.root_hash, volume_key, volume_key_size);
4511         }
4512
4513         if (signature)
4514                 crypt_drop_keyring_key_by_description(cd, description, USER_KEY);
4515
4516         return r;
4517 }
4518
4519 int crypt_deactivate_by_name(struct crypt_device *cd, const char *name, uint32_t flags)
4520 {
4521         struct crypt_device *fake_cd = NULL;
4522         struct luks2_hdr *hdr2 = NULL;
4523         struct crypt_dm_active_device dmd = {};
4524         int r;
4525         uint32_t get_flags = DM_ACTIVE_DEVICE | DM_ACTIVE_UUID | DM_ACTIVE_HOLDERS;
4526
4527         if (!name)
4528                 return -EINVAL;
4529
4530         log_dbg(cd, "Deactivating volume %s.", name);
4531
4532         if (!cd) {
4533                 r = crypt_init_by_name(&fake_cd, name);
4534                 if (r < 0)
4535                         return r;
4536                 cd = fake_cd;
4537         }
4538
4539         /* skip holders detection and early abort when some flags raised */
4540         if (flags & (CRYPT_DEACTIVATE_FORCE | CRYPT_DEACTIVATE_DEFERRED))
4541                 get_flags &= ~DM_ACTIVE_HOLDERS;
4542
4543         switch (crypt_status(cd, name)) {
4544                 case CRYPT_ACTIVE:
4545                 case CRYPT_BUSY:
4546                         r = dm_query_device(cd, name, get_flags, &dmd);
4547                         if (r >= 0) {
4548                                 if (dmd.holders) {
4549                                         log_err(cd, _("Device %s is still in use."), name);
4550                                         r = -EBUSY;
4551                                         break;
4552                                 }
4553                         }
4554
4555                         if (isLUKS2(cd->type))
4556                                 hdr2 = crypt_get_hdr(cd, CRYPT_LUKS2);
4557
4558                         if ((dmd.uuid && !strncmp(CRYPT_LUKS2, dmd.uuid, sizeof(CRYPT_LUKS2)-1)) || hdr2)
4559                                 r = LUKS2_deactivate(cd, name, hdr2, &dmd, flags);
4560                         else if (isTCRYPT(cd->type))
4561                                 r = TCRYPT_deactivate(cd, name, flags);
4562                         else
4563                                 r = dm_remove_device(cd, name, flags);
4564                         if (r < 0 && crypt_status(cd, name) == CRYPT_BUSY) {
4565                                 log_err(cd, _("Device %s is still in use."), name);
4566                                 r = -EBUSY;
4567                         }
4568                         break;
4569                 case CRYPT_INACTIVE:
4570                         log_err(cd, _("Device %s is not active."), name);
4571                         r = -ENODEV;
4572                         break;
4573                 default:
4574                         log_err(cd, _("Invalid device %s."), name);
4575                         r = -EINVAL;
4576         }
4577
4578         dm_targets_free(cd, &dmd);
4579         free(CONST_CAST(void*)dmd.uuid);
4580         crypt_free(fake_cd);
4581
4582         return r;
4583 }
4584
4585 int crypt_deactivate(struct crypt_device *cd, const char *name)
4586 {
4587         return crypt_deactivate_by_name(cd, name, 0);
4588 }
4589
4590 int crypt_get_active_device(struct crypt_device *cd, const char *name,
4591                             struct crypt_active_device *cad)
4592 {
4593         int r;
4594         struct crypt_dm_active_device dmd, dmdi = {};
4595         const char *namei = NULL;
4596         struct dm_target *tgt = &dmd.segment;
4597         uint64_t min_offset = UINT64_MAX;
4598
4599         if (!cd || !name || !cad)
4600                 return -EINVAL;
4601
4602         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE, &dmd);
4603         if (r < 0)
4604                 return r;
4605
4606         /* For LUKS2 with integrity we need flags from underlying dm-integrity */
4607         if (isLUKS2(cd->type) && crypt_get_integrity_tag_size(cd) && single_segment(&dmd)) {
4608                 namei = device_dm_name(tgt->data_device);
4609                 if (namei && dm_query_device(cd, namei, 0, &dmdi) >= 0)
4610                         dmd.flags |= dmdi.flags;
4611         }
4612
4613         if (cd && isTCRYPT(cd->type)) {
4614                 cad->offset     = TCRYPT_get_data_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
4615                 cad->iv_offset  = TCRYPT_get_iv_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
4616         } else {
4617                 while (tgt) {
4618                         if (tgt->type == DM_CRYPT && (min_offset > tgt->u.crypt.offset)) {
4619                                 min_offset = tgt->u.crypt.offset;
4620                                 cad->iv_offset = tgt->u.crypt.iv_offset;
4621                         } else if (tgt->type == DM_INTEGRITY && (min_offset > tgt->u.integrity.offset)) {
4622                                 min_offset = tgt->u.integrity.offset;
4623                                 cad->iv_offset = 0;
4624                         } else if (tgt->type == DM_LINEAR && (min_offset > tgt->u.linear.offset)) {
4625                                 min_offset = tgt->u.linear.offset;
4626                                 cad->iv_offset = 0;
4627                         }
4628                         tgt = tgt->next;
4629                 }
4630         }
4631
4632         if (min_offset != UINT64_MAX)
4633                 cad->offset = min_offset;
4634
4635         cad->size       = dmd.size;
4636         cad->flags      = dmd.flags;
4637
4638         r = 0;
4639         dm_targets_free(cd, &dmd);
4640         dm_targets_free(cd, &dmdi);
4641
4642         return r;
4643 }
4644
4645 uint64_t crypt_get_active_integrity_failures(struct crypt_device *cd, const char *name)
4646 {
4647         struct crypt_dm_active_device dmd;
4648         uint64_t failures = 0;
4649
4650         if (!name)
4651                 return 0;
4652
4653         /* FIXME: LUKS2 / dm-crypt does not provide this count. */
4654         if (dm_query_device(cd, name, 0, &dmd) < 0)
4655                 return 0;
4656
4657         if (single_segment(&dmd) && dmd.segment.type == DM_INTEGRITY)
4658                 (void)dm_status_integrity_failures(cd, name, &failures);
4659
4660         dm_targets_free(cd, &dmd);
4661
4662         return failures;
4663 }
4664
4665 /*
4666  * Volume key handling
4667  */
4668 int crypt_volume_key_get(struct crypt_device *cd,
4669         int keyslot,
4670         char *volume_key,
4671         size_t *volume_key_size,
4672         const char *passphrase,
4673         size_t passphrase_size)
4674 {
4675         struct volume_key *vk = NULL;
4676         int key_len, r = -EINVAL;
4677
4678         if (!cd || !volume_key || !volume_key_size || (!isTCRYPT(cd->type) && !isVERITY(cd->type) && !passphrase))
4679                 return -EINVAL;
4680
4681         if (isLUKS2(cd->type) && keyslot != CRYPT_ANY_SLOT)
4682                 key_len = LUKS2_get_keyslot_stored_key_size(&cd->u.luks2.hdr, keyslot);
4683         else
4684                 key_len = crypt_get_volume_key_size(cd);
4685
4686         if (key_len < 0)
4687                 return -EINVAL;
4688
4689         if (key_len > (int)*volume_key_size) {
4690                 log_err(cd, _("Volume key buffer too small."));
4691                 return -ENOMEM;
4692         }
4693
4694         if (isPLAIN(cd->type) && cd->u.plain.hdr.hash) {
4695                 r = process_key(cd, cd->u.plain.hdr.hash, key_len,
4696                                 passphrase, passphrase_size, &vk);
4697                 if (r < 0)
4698                         log_err(cd, _("Cannot retrieve volume key for plain device."));
4699         } else if (isLUKS1(cd->type)) {
4700                 r = LUKS_open_key_with_hdr(keyslot, passphrase,
4701                                         passphrase_size, &cd->u.luks1.hdr, &vk, cd);
4702         } else if (isLUKS2(cd->type)) {
4703                 r = LUKS2_keyslot_open(cd, keyslot,
4704                                 keyslot == CRYPT_ANY_SLOT ? CRYPT_DEFAULT_SEGMENT : CRYPT_ANY_SEGMENT,
4705                                 passphrase, passphrase_size, &vk);
4706         } else if (isTCRYPT(cd->type)) {
4707                 r = TCRYPT_get_volume_key(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params, &vk);
4708         } else if (isVERITY(cd->type)) {
4709                 /* volume_key == root hash */
4710                 if (cd->u.verity.root_hash) {
4711                         memcpy(volume_key, cd->u.verity.root_hash, cd->u.verity.root_hash_size);
4712                         *volume_key_size = cd->u.verity.root_hash_size;
4713                         r = 0;
4714                 } else
4715                         log_err(cd, _("Cannot retrieve root hash for verity device."));
4716         } else
4717                 log_err(cd, _("This operation is not supported for %s crypt device."), cd->type ?: "(none)");
4718
4719         if (r >= 0 && vk) {
4720                 memcpy(volume_key, vk->key, vk->keylength);
4721                 *volume_key_size = vk->keylength;
4722         }
4723
4724         crypt_free_volume_key(vk);
4725         return r;
4726 }
4727
4728 int crypt_volume_key_verify(struct crypt_device *cd,
4729         const char *volume_key,
4730         size_t volume_key_size)
4731 {
4732         struct volume_key *vk;
4733         int r;
4734
4735         if ((r = _onlyLUKS(cd, CRYPT_CD_UNRESTRICTED)))
4736                 return r;
4737
4738         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4739         if (!vk)
4740                 return -ENOMEM;
4741
4742         if (isLUKS1(cd->type))
4743                 r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
4744         else if (isLUKS2(cd->type))
4745                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
4746         else
4747                 r = -EINVAL;
4748
4749
4750         if (r == -EPERM)
4751                 log_err(cd, _("Volume key does not match the volume."));
4752
4753         crypt_free_volume_key(vk);
4754
4755         return r >= 0 ? 0 : r;
4756 }
4757
4758 /*
4759  * RNG and memory locking
4760  */
4761 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
4762 {
4763         if (!cd)
4764                 return;
4765
4766         switch (rng_type) {
4767         case CRYPT_RNG_URANDOM:
4768         case CRYPT_RNG_RANDOM:
4769                 log_dbg(cd, "RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
4770                 cd->rng_type = rng_type;
4771         }
4772 }
4773
4774 int crypt_get_rng_type(struct crypt_device *cd)
4775 {
4776         if (!cd)
4777                 return -EINVAL;
4778
4779         return cd->rng_type;
4780 }
4781
4782 int crypt_memory_lock(struct crypt_device *cd, int lock)
4783 {
4784         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
4785 }
4786
4787 void crypt_set_compatibility(struct crypt_device *cd, uint32_t flags)
4788 {
4789         if (cd)
4790                 cd->compatibility = flags;
4791 }
4792
4793 uint32_t crypt_get_compatibility(struct crypt_device *cd)
4794 {
4795         if (cd)
4796                 return cd->compatibility;
4797
4798         return 0;
4799 }
4800
4801 /*
4802  * Reporting
4803  */
4804 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
4805 {
4806         int r;
4807
4808         if (!name)
4809                 return CRYPT_INVALID;
4810
4811         if (!cd)
4812                 dm_backend_init(cd);
4813
4814         r = dm_status_device(cd, name);
4815
4816         if (!cd)
4817                 dm_backend_exit(cd);
4818
4819         if (r < 0 && r != -ENODEV)
4820                 return CRYPT_INVALID;
4821
4822         if (r == 0)
4823                 return CRYPT_ACTIVE;
4824
4825         if (r > 0)
4826                 return CRYPT_BUSY;
4827
4828         return CRYPT_INACTIVE;
4829 }
4830
4831 static void hexprint(struct crypt_device *cd, const char *d, int n, const char *sep)
4832 {
4833         int i;
4834         for(i = 0; i < n; i++)
4835                 log_std(cd, "%02hhx%s", (const char)d[i], sep);
4836 }
4837
4838 static int _luks_dump(struct crypt_device *cd)
4839 {
4840         int i;
4841
4842         log_std(cd, "LUKS header information for %s\n\n", mdata_device_path(cd));
4843         log_std(cd, "Version:       \t%" PRIu16 "\n", cd->u.luks1.hdr.version);
4844         log_std(cd, "Cipher name:   \t%s\n", cd->u.luks1.hdr.cipherName);
4845         log_std(cd, "Cipher mode:   \t%s\n", cd->u.luks1.hdr.cipherMode);
4846         log_std(cd, "Hash spec:     \t%s\n", cd->u.luks1.hdr.hashSpec);
4847         log_std(cd, "Payload offset:\t%" PRIu32 "\n", cd->u.luks1.hdr.payloadOffset);
4848         log_std(cd, "MK bits:       \t%" PRIu32 "\n", cd->u.luks1.hdr.keyBytes * 8);
4849         log_std(cd, "MK digest:     \t");
4850         hexprint(cd, cd->u.luks1.hdr.mkDigest, LUKS_DIGESTSIZE, " ");
4851         log_std(cd, "\n");
4852         log_std(cd, "MK salt:       \t");
4853         hexprint(cd, cd->u.luks1.hdr.mkDigestSalt, LUKS_SALTSIZE/2, " ");
4854         log_std(cd, "\n               \t");
4855         hexprint(cd, cd->u.luks1.hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
4856         log_std(cd, "\n");
4857         log_std(cd, "MK iterations: \t%" PRIu32 "\n", cd->u.luks1.hdr.mkDigestIterations);
4858         log_std(cd, "UUID:          \t%s\n\n", cd->u.luks1.hdr.uuid);
4859         for(i = 0; i < LUKS_NUMKEYS; i++) {
4860                 if(cd->u.luks1.hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
4861                         log_std(cd, "Key Slot %d: ENABLED\n",i);
4862                         log_std(cd, "\tIterations:         \t%" PRIu32 "\n",
4863                                 cd->u.luks1.hdr.keyblock[i].passwordIterations);
4864                         log_std(cd, "\tSalt:               \t");
4865                         hexprint(cd, cd->u.luks1.hdr.keyblock[i].passwordSalt,
4866                                  LUKS_SALTSIZE/2, " ");
4867                         log_std(cd, "\n\t                      \t");
4868                         hexprint(cd, cd->u.luks1.hdr.keyblock[i].passwordSalt +
4869                                  LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
4870                         log_std(cd, "\n");
4871
4872                         log_std(cd, "\tKey material offset:\t%" PRIu32 "\n",
4873                                 cd->u.luks1.hdr.keyblock[i].keyMaterialOffset);
4874                         log_std(cd, "\tAF stripes:            \t%" PRIu32 "\n",
4875                                 cd->u.luks1.hdr.keyblock[i].stripes);
4876                 }
4877                 else
4878                         log_std(cd, "Key Slot %d: DISABLED\n", i);
4879         }
4880         return 0;
4881 }
4882
4883 static int _verity_dump(struct crypt_device *cd)
4884 {
4885         log_std(cd, "VERITY header information for %s\n", mdata_device_path(cd));
4886         log_std(cd, "UUID:            \t%s\n", cd->u.verity.uuid ?: "");
4887         log_std(cd, "Hash type:       \t%u\n", cd->u.verity.hdr.hash_type);
4888         log_std(cd, "Data blocks:     \t%" PRIu64 "\n", cd->u.verity.hdr.data_size);
4889         log_std(cd, "Data block size: \t%u\n", cd->u.verity.hdr.data_block_size);
4890         log_std(cd, "Hash block size: \t%u\n", cd->u.verity.hdr.hash_block_size);
4891         log_std(cd, "Hash algorithm:  \t%s\n", cd->u.verity.hdr.hash_name);
4892         log_std(cd, "Salt:            \t");
4893         if (cd->u.verity.hdr.salt_size)
4894                 hexprint(cd, cd->u.verity.hdr.salt, cd->u.verity.hdr.salt_size, "");
4895         else
4896                 log_std(cd, "-");
4897         log_std(cd, "\n");
4898         if (cd->u.verity.root_hash) {
4899                 log_std(cd, "Root hash:      \t");
4900                 hexprint(cd, cd->u.verity.root_hash, cd->u.verity.root_hash_size, "");
4901                 log_std(cd, "\n");
4902         }
4903         return 0;
4904 }
4905
4906 int crypt_dump(struct crypt_device *cd)
4907 {
4908         if (!cd)
4909                 return -EINVAL;
4910         if (isLUKS1(cd->type))
4911                 return _luks_dump(cd);
4912         else if (isLUKS2(cd->type))
4913                 return LUKS2_hdr_dump(cd, &cd->u.luks2.hdr);
4914         else if (isVERITY(cd->type))
4915                 return _verity_dump(cd);
4916         else if (isTCRYPT(cd->type))
4917                 return TCRYPT_dump(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
4918         else if (isINTEGRITY(cd->type))
4919                 return INTEGRITY_dump(cd, crypt_data_device(cd), 0);
4920         else if (isBITLK(cd->type))
4921                 return BITLK_dump(cd, crypt_data_device(cd), &cd->u.bitlk.params);
4922
4923         log_err(cd, _("Dump operation is not supported for this device type."));
4924         return -EINVAL;
4925 }
4926
4927 /* internal only */
4928 const char *crypt_get_cipher_spec(struct crypt_device *cd)
4929 {
4930         if (!cd)
4931                 return NULL;
4932         else if (isLUKS2(cd->type))
4933                 return LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
4934         else if (isLUKS1(cd->type))
4935                 return cd->u.luks1.cipher_spec;
4936         else if (isPLAIN(cd->type))
4937                 return cd->u.plain.cipher_spec;
4938         else if (isLOOPAES(cd->type))
4939                 return cd->u.loopaes.cipher_spec;
4940         else if (isBITLK(cd->type))
4941                 return cd->u.bitlk.cipher_spec;
4942         else if (!cd->type && !_init_by_name_crypt_none(cd))
4943                 return cd->u.none.cipher_spec;
4944
4945         return NULL;
4946 }
4947
4948 const char *crypt_get_cipher(struct crypt_device *cd)
4949 {
4950         if (!cd)
4951                 return NULL;
4952
4953         if (isPLAIN(cd->type))
4954                 return cd->u.plain.cipher;
4955
4956         if (isLUKS1(cd->type))
4957                 return cd->u.luks1.hdr.cipherName;
4958
4959         if (isLUKS2(cd->type)) {
4960                 if (crypt_parse_name_and_mode(LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT),
4961                                               cd->u.luks2.cipher, NULL, cd->u.luks2.cipher_mode))
4962                         return NULL;
4963                 return cd->u.luks2.cipher;
4964         }
4965
4966         if (isLOOPAES(cd->type))
4967                 return cd->u.loopaes.cipher;
4968
4969         if (isTCRYPT(cd->type))
4970                 return cd->u.tcrypt.params.cipher;
4971
4972         if (isBITLK(cd->type))
4973                 return cd->u.bitlk.params.cipher;
4974
4975         if (!cd->type && !_init_by_name_crypt_none(cd))
4976                 return cd->u.none.cipher;
4977
4978         return NULL;
4979 }
4980
4981 const char *crypt_get_cipher_mode(struct crypt_device *cd)
4982 {
4983         if (!cd)
4984                 return NULL;
4985
4986         if (isPLAIN(cd->type))
4987                 return cd->u.plain.cipher_mode;
4988
4989         if (isLUKS1(cd->type))
4990                 return cd->u.luks1.hdr.cipherMode;
4991
4992         if (isLUKS2(cd->type)) {
4993                 if (crypt_parse_name_and_mode(LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT),
4994                                               cd->u.luks2.cipher, NULL, cd->u.luks2.cipher_mode))
4995                         return NULL;
4996                 return cd->u.luks2.cipher_mode;
4997         }
4998
4999         if (isLOOPAES(cd->type))
5000                 return cd->u.loopaes.cipher_mode;
5001
5002         if (isTCRYPT(cd->type))
5003                 return cd->u.tcrypt.params.mode;
5004
5005         if (isBITLK(cd->type))
5006                 return cd->u.bitlk.params.cipher_mode;
5007
5008         if (!cd->type && !_init_by_name_crypt_none(cd))
5009                 return cd->u.none.cipher_mode;
5010
5011         return NULL;
5012 }
5013
5014 /* INTERNAL only */
5015 const char *crypt_get_integrity(struct crypt_device *cd)
5016 {
5017         if (!cd)
5018                 return NULL;
5019
5020         if (isINTEGRITY(cd->type))
5021                 return cd->u.integrity.params.integrity;
5022
5023         if (isLUKS2(cd->type))
5024                 return LUKS2_get_integrity(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
5025
5026         return NULL;
5027 }
5028
5029 /* INTERNAL only */
5030 int crypt_get_integrity_key_size(struct crypt_device *cd)
5031 {
5032         if (isINTEGRITY(cd->type))
5033                 return INTEGRITY_key_size(cd, crypt_get_integrity(cd));
5034
5035         if (isLUKS2(cd->type))
5036                 return INTEGRITY_key_size(cd, crypt_get_integrity(cd));
5037
5038         return 0;
5039 }
5040
5041 /* INTERNAL only */
5042 int crypt_get_integrity_tag_size(struct crypt_device *cd)
5043 {
5044         if (isINTEGRITY(cd->type))
5045                 return cd->u.integrity.params.tag_size;
5046
5047         if (isLUKS2(cd->type))
5048                 return INTEGRITY_tag_size(cd, crypt_get_integrity(cd),
5049                                           crypt_get_cipher(cd),
5050                                           crypt_get_cipher_mode(cd));
5051         return 0;
5052 }
5053
5054 int crypt_get_sector_size(struct crypt_device *cd)
5055 {
5056         if (!cd)
5057                 return SECTOR_SIZE;
5058
5059         if (isPLAIN(cd->type))
5060                 return cd->u.plain.hdr.sector_size;
5061
5062         if (isINTEGRITY(cd->type))
5063                 return cd->u.integrity.params.sector_size;
5064
5065         if (isLUKS2(cd->type))
5066                 return LUKS2_get_sector_size(&cd->u.luks2.hdr);
5067
5068         return SECTOR_SIZE;
5069 }
5070
5071 const char *crypt_get_uuid(struct crypt_device *cd)
5072 {
5073         if (!cd)
5074                 return NULL;
5075
5076         if (isLUKS1(cd->type))
5077                 return cd->u.luks1.hdr.uuid;
5078
5079         if (isLUKS2(cd->type))
5080                 return cd->u.luks2.hdr.uuid;
5081
5082         if (isVERITY(cd->type))
5083                 return cd->u.verity.uuid;
5084
5085         if (isBITLK(cd->type))
5086                 return cd->u.bitlk.params.guid;
5087
5088         return NULL;
5089 }
5090
5091 const char *crypt_get_device_name(struct crypt_device *cd)
5092 {
5093         const char *path;
5094
5095         if (!cd)
5096                 return NULL;
5097
5098         path = device_block_path(cd->device);
5099         if (!path)
5100                 path = device_path(cd->device);
5101
5102         return path;
5103 }
5104
5105 const char *crypt_get_metadata_device_name(struct crypt_device *cd)
5106 {
5107         const char *path;
5108
5109         if (!cd || !cd->metadata_device)
5110                 return NULL;
5111
5112         path = device_block_path(cd->metadata_device);
5113         if (!path)
5114                 path = device_path(cd->metadata_device);
5115
5116         return path;
5117 }
5118
5119 int crypt_get_volume_key_size(struct crypt_device *cd)
5120 {
5121         int r;
5122
5123         if (!cd)
5124                 return 0;
5125
5126         if (isPLAIN(cd->type))
5127                 return cd->u.plain.key_size;
5128
5129         if (isLUKS1(cd->type))
5130                 return cd->u.luks1.hdr.keyBytes;
5131
5132         if (isLUKS2(cd->type)) {
5133                 r = LUKS2_get_volume_key_size(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
5134                 if (r < 0 && cd->volume_key)
5135                         r = cd->volume_key->keylength;
5136                 return r < 0 ? 0 : r;
5137         }
5138
5139         if (isLOOPAES(cd->type))
5140                 return cd->u.loopaes.key_size;
5141
5142         if (isVERITY(cd->type))
5143                 return cd->u.verity.root_hash_size;
5144
5145         if (isTCRYPT(cd->type))
5146                 return cd->u.tcrypt.params.key_size;
5147
5148         if (isBITLK(cd->type))
5149                 return cd->u.bitlk.params.key_size / 8;
5150
5151         if (!cd->type && !_init_by_name_crypt_none(cd))
5152                 return cd->u.none.key_size;
5153
5154         return 0;
5155 }
5156
5157 int crypt_keyslot_get_key_size(struct crypt_device *cd, int keyslot)
5158 {
5159         if (!cd || !isLUKS(cd->type))
5160                 return -EINVAL;
5161
5162         if (keyslot < 0 || keyslot >= crypt_keyslot_max(cd->type))
5163                 return -EINVAL;
5164
5165         if (isLUKS1(cd->type))
5166                 return cd->u.luks1.hdr.keyBytes;
5167
5168         if (isLUKS2(cd->type))
5169                 return LUKS2_get_keyslot_stored_key_size(&cd->u.luks2.hdr, keyslot);
5170
5171         return -EINVAL;
5172 }
5173
5174 int crypt_keyslot_set_encryption(struct crypt_device *cd,
5175         const char *cipher,
5176         size_t key_size)
5177 {
5178         char *tmp;
5179
5180         if (!cd || !cipher || ! key_size || !isLUKS2(cd->type))
5181                 return -EINVAL;
5182
5183         if (LUKS2_keyslot_cipher_incompatible(cd, cipher))
5184                 return -EINVAL;
5185
5186         tmp = strdup(cipher);
5187         free(cd->u.luks2.keyslot_cipher);
5188         cd->u.luks2.keyslot_cipher = tmp;
5189         if (!cd->u.luks2.keyslot_cipher)
5190                 return -ENOMEM;
5191         cd->u.luks2.keyslot_key_size = key_size;
5192
5193         return 0;
5194 }
5195
5196 const char *crypt_keyslot_get_encryption(struct crypt_device *cd, int keyslot, size_t *key_size)
5197 {
5198         const char *cipher;
5199
5200         if (!cd || !isLUKS(cd->type) || !key_size)
5201                 return NULL;
5202
5203         if (isLUKS1(cd->type)) {
5204                 if (keyslot != CRYPT_ANY_SLOT &&
5205                     LUKS_keyslot_info(&cd->u.luks1.hdr, keyslot) < CRYPT_SLOT_ACTIVE)
5206                         return NULL;
5207                 *key_size = crypt_get_volume_key_size(cd);
5208                 return cd->u.luks1.cipher_spec;
5209         }
5210
5211         if (keyslot != CRYPT_ANY_SLOT)
5212                 return LUKS2_get_keyslot_cipher(&cd->u.luks2.hdr, keyslot, key_size);
5213
5214         /* Keyslot encryption was set through crypt_keyslot_set_encryption() */
5215         if (cd->u.luks2.keyslot_cipher) {
5216                 *key_size = cd->u.luks2.keyslot_key_size;
5217                 return cd->u.luks2.keyslot_cipher;
5218         }
5219
5220         /* Try to reuse volume encryption parameters */
5221         cipher =  LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
5222         if (!LUKS2_keyslot_cipher_incompatible(cd, cipher)) {
5223                 *key_size = crypt_get_volume_key_size(cd);
5224                 if (*key_size)
5225                         return cipher;
5226         }
5227
5228         /* Fallback to default LUKS2 keyslot encryption */
5229         *key_size = DEFAULT_LUKS2_KEYSLOT_KEYBITS / 8;
5230         return DEFAULT_LUKS2_KEYSLOT_CIPHER;
5231 }
5232
5233 int crypt_keyslot_get_pbkdf(struct crypt_device *cd, int keyslot, struct crypt_pbkdf_type *pbkdf)
5234 {
5235         if (!cd || !pbkdf || keyslot == CRYPT_ANY_SLOT)
5236                 return -EINVAL;
5237
5238         if (isLUKS1(cd->type))
5239                 return LUKS_keyslot_pbkdf(&cd->u.luks1.hdr, keyslot, pbkdf);
5240         else if (isLUKS2(cd->type))
5241                 return LUKS2_keyslot_pbkdf(&cd->u.luks2.hdr, keyslot, pbkdf);
5242
5243         return -EINVAL;
5244 }
5245
5246 int crypt_set_data_offset(struct crypt_device *cd, uint64_t data_offset)
5247 {
5248         if (!cd)
5249                 return -EINVAL;
5250         if (data_offset % (MAX_SECTOR_SIZE >> SECTOR_SHIFT)) {
5251                 log_err(cd, _("Data offset is not multiple of %u bytes."), MAX_SECTOR_SIZE);
5252                 return -EINVAL;
5253         }
5254
5255         cd->data_offset = data_offset;
5256         log_dbg(cd, "Data offset set to %" PRIu64 " (512-byte) sectors.", data_offset);
5257
5258         return 0;
5259 }
5260
5261 int crypt_set_metadata_size(struct crypt_device *cd,
5262         uint64_t metadata_size,
5263         uint64_t keyslots_size)
5264 {
5265         if (!cd)
5266                 return -EINVAL;
5267
5268         if (cd->type && !isLUKS2(cd->type))
5269                 return -EINVAL;
5270
5271         if (metadata_size && LUKS2_check_metadata_area_size(metadata_size))
5272                 return -EINVAL;
5273
5274         if (keyslots_size && LUKS2_check_keyslots_area_size(keyslots_size))
5275                 return -EINVAL;
5276
5277         cd->metadata_size = metadata_size;
5278         cd->keyslots_size = keyslots_size;
5279
5280         return 0;
5281 }
5282
5283 int crypt_get_metadata_size(struct crypt_device *cd,
5284         uint64_t *metadata_size,
5285         uint64_t *keyslots_size)
5286 {
5287         uint64_t msize, ksize;
5288
5289         if (!cd)
5290                 return -EINVAL;
5291
5292         if (!cd->type) {
5293                 msize = cd->metadata_size;
5294                 ksize = cd->keyslots_size;
5295         } else if (isLUKS1(cd->type)) {
5296                 msize = LUKS_ALIGN_KEYSLOTS;
5297                 ksize = LUKS_device_sectors(&cd->u.luks1.hdr) * SECTOR_SIZE - msize;
5298         } else if (isLUKS2(cd->type)) {
5299                 msize = LUKS2_metadata_size(&cd->u.luks2.hdr);
5300                 ksize = LUKS2_keyslots_size(&cd->u.luks2.hdr);
5301         } else
5302                 return -EINVAL;
5303
5304         if (metadata_size)
5305                 *metadata_size = msize;
5306         if (keyslots_size)
5307                 *keyslots_size = ksize;
5308
5309         return 0;
5310 }
5311
5312 uint64_t crypt_get_data_offset(struct crypt_device *cd)
5313 {
5314         if (!cd)
5315                 return 0;
5316
5317         if (isPLAIN(cd->type))
5318                 return cd->u.plain.hdr.offset;
5319
5320         if (isLUKS1(cd->type))
5321                 return cd->u.luks1.hdr.payloadOffset;
5322
5323         if (isLUKS2(cd->type))
5324                 return LUKS2_get_data_offset(&cd->u.luks2.hdr);
5325
5326         if (isLOOPAES(cd->type))
5327                 return cd->u.loopaes.hdr.offset;
5328
5329         if (isTCRYPT(cd->type))
5330                 return TCRYPT_get_data_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
5331
5332         if (isBITLK(cd->type))
5333                 return cd->u.bitlk.params.volume_header_size / SECTOR_SIZE;
5334
5335         return cd->data_offset;
5336 }
5337
5338 uint64_t crypt_get_iv_offset(struct crypt_device *cd)
5339 {
5340         if (!cd)
5341                 return 0;
5342
5343         if (isPLAIN(cd->type))
5344                 return cd->u.plain.hdr.skip;
5345
5346         if (isLOOPAES(cd->type))
5347                 return cd->u.loopaes.hdr.skip;
5348
5349         if (isTCRYPT(cd->type))
5350                 return TCRYPT_get_iv_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
5351
5352         return 0;
5353 }
5354
5355 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
5356 {
5357         if (_onlyLUKS(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED) < 0)
5358                 return CRYPT_SLOT_INVALID;
5359
5360         if (isLUKS1(cd->type))
5361                 return LUKS_keyslot_info(&cd->u.luks1.hdr, keyslot);
5362         else if(isLUKS2(cd->type))
5363                 return LUKS2_keyslot_info(&cd->u.luks2.hdr, keyslot);
5364
5365         return CRYPT_SLOT_INVALID;
5366 }
5367
5368 int crypt_keyslot_max(const char *type)
5369 {
5370         if (type && isLUKS1(type))
5371                 return LUKS_NUMKEYS;
5372
5373         if (type && isLUKS2(type))
5374                 return LUKS2_KEYSLOTS_MAX;
5375
5376         return -EINVAL;
5377 }
5378
5379 int crypt_keyslot_area(struct crypt_device *cd,
5380         int keyslot,
5381         uint64_t *offset,
5382         uint64_t *length)
5383 {
5384         if (_onlyLUKS(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED) || !offset || !length)
5385                 return -EINVAL;
5386
5387         if (isLUKS2(cd->type))
5388                 return LUKS2_keyslot_area(&cd->u.luks2.hdr, keyslot, offset, length);
5389
5390         return LUKS_keyslot_area(&cd->u.luks1.hdr, keyslot, offset, length);
5391 }
5392
5393 crypt_keyslot_priority crypt_keyslot_get_priority(struct crypt_device *cd, int keyslot)
5394 {
5395         if (_onlyLUKS(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED))
5396                 return CRYPT_SLOT_PRIORITY_INVALID;
5397
5398         if (keyslot < 0 || keyslot >= crypt_keyslot_max(cd->type))
5399                 return CRYPT_SLOT_PRIORITY_INVALID;
5400
5401         if (isLUKS2(cd->type))
5402                 return LUKS2_keyslot_priority_get(cd, &cd->u.luks2.hdr, keyslot);
5403
5404         return CRYPT_SLOT_PRIORITY_NORMAL;
5405 }
5406
5407 int crypt_keyslot_set_priority(struct crypt_device *cd, int keyslot, crypt_keyslot_priority priority)
5408 {
5409         int r;
5410
5411         log_dbg(cd, "Setting keyslot %d to priority %d.", keyslot, priority);
5412
5413         if (priority == CRYPT_SLOT_PRIORITY_INVALID)
5414                 return -EINVAL;
5415
5416         if (keyslot < 0 || keyslot >= crypt_keyslot_max(cd->type))
5417                 return -EINVAL;
5418
5419         if ((r = onlyLUKS2(cd)))
5420                 return r;
5421
5422         return LUKS2_keyslot_priority_set(cd, &cd->u.luks2.hdr, keyslot, priority, 1);
5423 }
5424
5425 const char *crypt_get_type(struct crypt_device *cd)
5426 {
5427         return cd ? cd->type : NULL;
5428 }
5429
5430 const char *crypt_get_default_type(void)
5431 {
5432         return DEFAULT_LUKS_FORMAT;
5433 }
5434
5435 int crypt_get_verity_info(struct crypt_device *cd,
5436         struct crypt_params_verity *vp)
5437 {
5438         if (!cd || !isVERITY(cd->type) || !vp)
5439                 return -EINVAL;
5440
5441         vp->data_device = device_path(cd->device);
5442         vp->hash_device = mdata_device_path(cd);
5443         vp->fec_device  = device_path(cd->u.verity.fec_device);
5444         vp->fec_area_offset = cd->u.verity.hdr.fec_area_offset;
5445         vp->fec_roots = cd->u.verity.hdr.fec_roots;
5446         vp->hash_name = cd->u.verity.hdr.hash_name;
5447         vp->salt = cd->u.verity.hdr.salt;
5448         vp->salt_size = cd->u.verity.hdr.salt_size;
5449         vp->data_block_size = cd->u.verity.hdr.data_block_size;
5450         vp->hash_block_size = cd->u.verity.hdr.hash_block_size;
5451         vp->data_size = cd->u.verity.hdr.data_size;
5452         vp->hash_area_offset = cd->u.verity.hdr.hash_area_offset;
5453         vp->hash_type = cd->u.verity.hdr.hash_type;
5454         vp->flags = cd->u.verity.hdr.flags & (CRYPT_VERITY_NO_HEADER | CRYPT_VERITY_ROOT_HASH_SIGNATURE);
5455         return 0;
5456 }
5457
5458 int crypt_get_integrity_info(struct crypt_device *cd,
5459         struct crypt_params_integrity *ip)
5460 {
5461         if (!cd || !ip)
5462                 return -EINVAL;
5463
5464         if (isINTEGRITY(cd->type)) {
5465                 ip->journal_size = cd->u.integrity.params.journal_size;
5466                 ip->journal_watermark = cd->u.integrity.params.journal_watermark;
5467                 ip->journal_commit_time = cd->u.integrity.params.journal_commit_time;
5468                 ip->interleave_sectors = cd->u.integrity.params.interleave_sectors;
5469                 ip->tag_size = cd->u.integrity.params.tag_size;
5470                 ip->sector_size = cd->u.integrity.params.sector_size;
5471                 ip->buffer_sectors = cd->u.integrity.params.buffer_sectors;
5472
5473                 ip->integrity = cd->u.integrity.params.integrity;
5474                 ip->integrity_key_size = crypt_get_integrity_key_size(cd);
5475
5476                 ip->journal_integrity = cd->u.integrity.params.journal_integrity;
5477                 ip->journal_integrity_key_size = cd->u.integrity.params.journal_integrity_key_size;
5478                 ip->journal_integrity_key = NULL;
5479
5480                 ip->journal_crypt = cd->u.integrity.params.journal_crypt;
5481                 ip->journal_crypt_key_size = cd->u.integrity.params.journal_crypt_key_size;
5482                 ip->journal_crypt_key = NULL;
5483                 return 0;
5484         } else if (isLUKS2(cd->type)) {
5485                 ip->journal_size = 0; // FIXME
5486                 ip->journal_watermark = 0; // FIXME
5487                 ip->journal_commit_time = 0; // FIXME
5488                 ip->interleave_sectors = 0; // FIXME
5489                 ip->sector_size = crypt_get_sector_size(cd);
5490                 ip->buffer_sectors = 0; // FIXME
5491
5492                 ip->integrity = LUKS2_get_integrity(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
5493                 ip->integrity_key_size = crypt_get_integrity_key_size(cd);
5494                 ip->tag_size = INTEGRITY_tag_size(cd, ip->integrity, crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
5495
5496                 ip->journal_integrity = NULL;
5497                 ip->journal_integrity_key_size = 0;
5498                 ip->journal_integrity_key = NULL;
5499
5500                 ip->journal_crypt = NULL;
5501                 ip->journal_crypt_key_size = 0;
5502                 ip->journal_crypt_key = NULL;
5503                 return 0;
5504         }
5505
5506         return -ENOTSUP;
5507 }
5508
5509 int crypt_convert(struct crypt_device *cd,
5510                   const char *type,
5511                   void *params)
5512 {
5513         struct luks_phdr hdr1;
5514         struct luks2_hdr hdr2;
5515         int r;
5516
5517         if (!type)
5518                 return -EINVAL;
5519
5520         log_dbg(cd, "Converting LUKS device to type %s", type);
5521
5522         if ((r = onlyLUKS(cd)))
5523                 return r;
5524
5525         if (isLUKS1(cd->type) && isLUKS2(type))
5526                 r = LUKS2_luks1_to_luks2(cd, &cd->u.luks1.hdr, &hdr2);
5527         else if (isLUKS2(cd->type) && isLUKS1(type))
5528                 r = LUKS2_luks2_to_luks1(cd, &cd->u.luks2.hdr, &hdr1);
5529         else
5530                 return -EINVAL;
5531
5532         if (r < 0) {
5533                 /* in-memory header may be invalid after failed conversion */
5534                 _luks2_reload(cd);
5535                 if (r == -EBUSY)
5536                         log_err(cd, _("Cannot convert device %s which is still in use."), mdata_device_path(cd));
5537                 return r;
5538         }
5539
5540         crypt_free_type(cd);
5541
5542         return crypt_load(cd, type, params);
5543 }
5544
5545 /* Internal access function to header pointer */
5546 void *crypt_get_hdr(struct crypt_device *cd, const char *type)
5547 {
5548         /* If requested type differs, ignore it */
5549         if (strcmp(cd->type, type))
5550                 return NULL;
5551
5552         if (isPLAIN(cd->type))
5553                 return &cd->u.plain;
5554
5555         if (isLUKS1(cd->type))
5556                 return &cd->u.luks1.hdr;
5557
5558         if (isLUKS2(cd->type))
5559                 return &cd->u.luks2.hdr;
5560
5561         if (isLOOPAES(cd->type))
5562                 return &cd->u.loopaes;
5563
5564         if (isVERITY(cd->type))
5565                 return &cd->u.verity;
5566
5567         if (isTCRYPT(cd->type))
5568                 return &cd->u.tcrypt;
5569
5570         return NULL;
5571 }
5572
5573 /* internal only */
5574 struct luks2_reencrypt *crypt_get_luks2_reencrypt(struct crypt_device *cd)
5575 {
5576         return cd->u.luks2.rh;
5577 }
5578
5579 /* internal only */
5580 void crypt_set_luks2_reencrypt(struct crypt_device *cd, struct luks2_reencrypt *rh)
5581 {
5582         cd->u.luks2.rh = rh;
5583 }
5584
5585 /*
5586  * Token handling
5587  */
5588 int crypt_activate_by_token(struct crypt_device *cd,
5589         const char *name, int token, void *usrptr, uint32_t flags)
5590 {
5591         int r;
5592
5593         log_dbg(cd, "%s volume %s using token %d.",
5594                 name ? "Activating" : "Checking", name ?: "passphrase", token);
5595
5596         if ((r = _onlyLUKS2(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED, 0)))
5597                 return r;
5598
5599         if ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd))
5600                 return -EINVAL;
5601
5602         if ((flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) && name)
5603                 return -EINVAL;
5604
5605         if (token == CRYPT_ANY_TOKEN)
5606                 return LUKS2_token_open_and_activate_any(cd, &cd->u.luks2.hdr, name, flags);
5607
5608         return LUKS2_token_open_and_activate(cd, &cd->u.luks2.hdr, token, name, flags, usrptr);
5609 }
5610
5611 int crypt_token_json_get(struct crypt_device *cd, int token, const char **json)
5612 {
5613         int r;
5614
5615         if (!json)
5616                 return -EINVAL;
5617
5618         log_dbg(cd, "Requesting JSON for token %d.", token);
5619
5620         if ((r = _onlyLUKS2(cd, CRYPT_CD_UNRESTRICTED, 0)))
5621                 return r;
5622
5623         return LUKS2_token_json_get(cd, &cd->u.luks2.hdr, token, json) ?: token;
5624 }
5625
5626 int crypt_token_json_set(struct crypt_device *cd, int token, const char *json)
5627 {
5628         int r;
5629
5630         log_dbg(cd, "Updating JSON for token %d.", token);
5631
5632         if ((r = onlyLUKS2(cd)))
5633                 return r;
5634
5635         return LUKS2_token_create(cd, &cd->u.luks2.hdr, token, json, 1);
5636 }
5637
5638 crypt_token_info crypt_token_status(struct crypt_device *cd, int token, const char **type)
5639 {
5640         if (_onlyLUKS2(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED, 0))
5641                 return CRYPT_TOKEN_INVALID;
5642
5643         return LUKS2_token_status(cd, &cd->u.luks2.hdr, token, type);
5644 }
5645
5646 int crypt_token_luks2_keyring_get(struct crypt_device *cd,
5647         int token,
5648         struct crypt_token_params_luks2_keyring *params)
5649 {
5650         crypt_token_info token_info;
5651         const char *type;
5652         int r;
5653
5654         if (!params)
5655                 return -EINVAL;
5656
5657         log_dbg(cd, "Requesting LUKS2 keyring token %d.", token);
5658
5659         if ((r = _onlyLUKS2(cd, CRYPT_CD_UNRESTRICTED, 0)))
5660                 return r;
5661
5662         token_info = LUKS2_token_status(cd, &cd->u.luks2.hdr, token, &type);
5663         switch (token_info) {
5664         case CRYPT_TOKEN_INVALID:
5665                 log_dbg(cd, "Token %d is invalid.", token);
5666                 return -EINVAL;
5667         case CRYPT_TOKEN_INACTIVE:
5668                 log_dbg(cd, "Token %d is inactive.", token);
5669                 return -EINVAL;
5670         case CRYPT_TOKEN_INTERNAL:
5671                 if (!strcmp(type, LUKS2_TOKEN_KEYRING))
5672                         break;
5673                 /* Fall through */
5674         case CRYPT_TOKEN_INTERNAL_UNKNOWN:
5675         case CRYPT_TOKEN_EXTERNAL:
5676         case CRYPT_TOKEN_EXTERNAL_UNKNOWN:
5677                 log_dbg(cd, "Token %d has unexpected type %s.", token, type);
5678                 return -EINVAL;
5679         }
5680
5681         return LUKS2_builtin_token_get(cd, &cd->u.luks2.hdr, token, LUKS2_TOKEN_KEYRING, params);
5682 }
5683
5684 int crypt_token_luks2_keyring_set(struct crypt_device *cd,
5685         int token,
5686         const struct crypt_token_params_luks2_keyring *params)
5687 {
5688         int r;
5689
5690         if (!params)
5691                 return -EINVAL;
5692
5693         log_dbg(cd, "Creating new LUKS2 keyring token (%d).", token);
5694
5695         if ((r = onlyLUKS2(cd)))
5696                 return r;
5697
5698         return LUKS2_builtin_token_create(cd, &cd->u.luks2.hdr, token, LUKS2_TOKEN_KEYRING, params, 1);
5699 }
5700
5701 int crypt_token_assign_keyslot(struct crypt_device *cd, int token, int keyslot)
5702 {
5703         int r;
5704
5705         if ((r = onlyLUKS2(cd)))
5706                 return r;
5707
5708         return LUKS2_token_assign(cd, &cd->u.luks2.hdr, keyslot, token, 1, 1);
5709 }
5710
5711 int crypt_token_unassign_keyslot(struct crypt_device *cd, int token, int keyslot)
5712 {
5713         int r;
5714
5715         if ((r = onlyLUKS2(cd)))
5716                 return r;
5717
5718         return LUKS2_token_assign(cd, &cd->u.luks2.hdr, keyslot, token, 0, 1);
5719 }
5720
5721 int crypt_token_is_assigned(struct crypt_device *cd, int token, int keyslot)
5722 {
5723         int r;
5724
5725         if ((r = _onlyLUKS2(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED, 0)))
5726                 return r;
5727
5728         return LUKS2_token_is_assigned(cd, &cd->u.luks2.hdr, keyslot, token);
5729 }
5730
5731 /* Internal only */
5732 int crypt_metadata_locking_enabled(void)
5733 {
5734         return _metadata_locking;
5735 }
5736
5737 int crypt_metadata_locking(struct crypt_device *cd, int enable)
5738 {
5739         if (enable && !_metadata_locking)
5740                 return -EPERM;
5741
5742         _metadata_locking = enable ? 1 : 0;
5743         return 0;
5744 }
5745
5746 int crypt_persistent_flags_set(struct crypt_device *cd, crypt_flags_type type, uint32_t flags)
5747 {
5748         int r;
5749
5750         if ((r = onlyLUKS2(cd)))
5751                 return r;
5752
5753         if (type == CRYPT_FLAGS_ACTIVATION)
5754                 return LUKS2_config_set_flags(cd, &cd->u.luks2.hdr, flags);
5755
5756         if (type == CRYPT_FLAGS_REQUIREMENTS)
5757                 return LUKS2_config_set_requirements(cd, &cd->u.luks2.hdr, flags, true);
5758
5759         return -EINVAL;
5760 }
5761
5762 int crypt_persistent_flags_get(struct crypt_device *cd, crypt_flags_type type, uint32_t *flags)
5763 {
5764         int r;
5765
5766         if (!flags)
5767                 return -EINVAL;
5768
5769         if ((r = _onlyLUKS2(cd, CRYPT_CD_UNRESTRICTED, 0)))
5770                 return r;
5771
5772         if (type == CRYPT_FLAGS_ACTIVATION)
5773                 return LUKS2_config_get_flags(cd, &cd->u.luks2.hdr, flags);
5774
5775         if (type == CRYPT_FLAGS_REQUIREMENTS)
5776                 return LUKS2_config_get_requirements(cd, &cd->u.luks2.hdr, flags);
5777
5778         return -EINVAL;
5779 }
5780
5781 static int update_volume_key_segment_digest(struct crypt_device *cd, struct luks2_hdr *hdr, int digest, int commit)
5782 {
5783         int r;
5784
5785         /* Remove any assignments in memory */
5786         r = LUKS2_digest_segment_assign(cd, hdr, CRYPT_DEFAULT_SEGMENT, CRYPT_ANY_DIGEST, 0, 0);
5787         if (r)
5788                 return r;
5789
5790         /* Assign it to the specific digest */
5791         return LUKS2_digest_segment_assign(cd, hdr, CRYPT_DEFAULT_SEGMENT, digest, 1, commit);
5792 }
5793
5794 static int verify_and_update_segment_digest(struct crypt_device *cd,
5795                 struct luks2_hdr *hdr, int keyslot,
5796                 const char *volume_key, size_t volume_key_size,
5797                 const char *password, size_t password_size)
5798 {
5799         int digest, r;
5800         struct volume_key *vk = NULL;
5801
5802         if (keyslot < 0 || (volume_key && !volume_key_size))
5803                 return -EINVAL;
5804
5805         if (volume_key)
5806                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
5807         else {
5808                 r = LUKS2_keyslot_open(cd, keyslot, CRYPT_ANY_SEGMENT, password, password_size, &vk);
5809                 if (r != keyslot) {
5810                         r = -EINVAL;
5811                         goto out;
5812                 }
5813         }
5814
5815         if (!vk)
5816                 return -ENOMEM;
5817
5818         /* check volume_key (param) digest matches keyslot digest */
5819         r = LUKS2_digest_verify(cd, hdr, vk, keyslot);
5820         if (r < 0)
5821                 goto out;
5822         digest = r;
5823
5824         /* nothing to do, volume key in keyslot is already assigned to default segment */
5825         r = LUKS2_digest_verify_by_segment(cd, hdr, CRYPT_DEFAULT_SEGMENT, vk);
5826         if (r >= 0)
5827                 goto out;
5828
5829         /* FIXME: check new volume key is usable with current default segment */
5830
5831         r = update_volume_key_segment_digest(cd, &cd->u.luks2.hdr, digest, 1);
5832         if (r)
5833                 log_err(cd, _("Failed to assign keyslot %u as the new volume key."), keyslot);
5834 out:
5835         crypt_free_volume_key(vk);
5836         return r < 0 ? r : keyslot;
5837 }
5838
5839
5840 int crypt_keyslot_add_by_key(struct crypt_device *cd,
5841         int keyslot,
5842         const char *volume_key,
5843         size_t volume_key_size,
5844         const char *passphrase,
5845         size_t passphrase_size,
5846         uint32_t flags)
5847 {
5848         int digest, r;
5849         struct luks2_keyslot_params params;
5850         struct volume_key *vk = NULL;
5851
5852         if (!passphrase || ((flags & CRYPT_VOLUME_KEY_NO_SEGMENT) &&
5853                             (flags & CRYPT_VOLUME_KEY_SET)))
5854                 return -EINVAL;
5855
5856         log_dbg(cd, "Adding new keyslot %d with volume key %sassigned to a crypt segment.",
5857                 keyslot, flags & CRYPT_VOLUME_KEY_NO_SEGMENT ? "un" : "");
5858
5859         if ((r = onlyLUKS2(cd)))
5860                 return r;
5861
5862         /* new volume key assignment */
5863         if ((flags & CRYPT_VOLUME_KEY_SET) && crypt_keyslot_status(cd, keyslot) > CRYPT_SLOT_INACTIVE)
5864                 return verify_and_update_segment_digest(cd, &cd->u.luks2.hdr,
5865                         keyslot, volume_key, volume_key_size, passphrase, passphrase_size);
5866
5867         r = keyslot_verify_or_find_empty(cd, &keyslot);
5868         if (r < 0)
5869                 return r;
5870
5871         if (volume_key)
5872                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
5873         else if (flags & CRYPT_VOLUME_KEY_NO_SEGMENT)
5874                 vk = crypt_generate_volume_key(cd, volume_key_size);
5875         else if (cd->volume_key)
5876                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
5877         else
5878                 return -EINVAL;
5879
5880         if (!vk)
5881                 return -ENOMEM;
5882
5883         /* if key matches volume key digest tear down new vk flag */
5884         digest = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
5885         if (digest >= 0)
5886                 flags &= ~CRYPT_VOLUME_KEY_SET;
5887
5888         /* if key matches any existing digest, do not create new digest */
5889         if (digest < 0 && (flags & CRYPT_VOLUME_KEY_DIGEST_REUSE))
5890                 digest = LUKS2_digest_any_matching(cd, &cd->u.luks2.hdr, vk);
5891
5892         /* no segment flag or new vk flag requires new key digest */
5893         if (flags & (CRYPT_VOLUME_KEY_NO_SEGMENT | CRYPT_VOLUME_KEY_SET)) {
5894                 if (digest < 0 || !(flags & CRYPT_VOLUME_KEY_DIGEST_REUSE))
5895                         digest = LUKS2_digest_create(cd, "pbkdf2", &cd->u.luks2.hdr, vk);
5896         }
5897
5898         r = digest;
5899         if (r < 0) {
5900                 log_err(cd, _("Volume key does not match the volume."));
5901                 goto out;
5902         }
5903
5904         r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
5905         if (r < 0) {
5906                 log_err(cd, _("Failed to initialize default LUKS2 keyslot parameters."));
5907                 goto out;
5908         }
5909
5910         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot, digest, 1, 0);
5911         if (r < 0) {
5912                 log_err(cd, _("Failed to assign keyslot %d to digest."), keyslot);
5913                 goto out;
5914         }
5915
5916         r = LUKS2_keyslot_store(cd, &cd->u.luks2.hdr, keyslot,
5917                                 passphrase, passphrase_size, vk, &params);
5918
5919         if (r >= 0 && (flags & CRYPT_VOLUME_KEY_SET))
5920                 r = update_volume_key_segment_digest(cd, &cd->u.luks2.hdr, digest, 1);
5921 out:
5922         crypt_free_volume_key(vk);
5923         if (r < 0) {
5924                 _luks2_reload(cd);
5925                 return r;
5926         }
5927         return keyslot;
5928 }
5929
5930 /*
5931  * Keyring handling
5932  */
5933
5934 int crypt_use_keyring_for_vk(struct crypt_device *cd)
5935 {
5936         uint32_t dmc_flags;
5937
5938         /* dm backend must be initialized */
5939         if (!cd || !isLUKS2(cd->type))
5940                 return 0;
5941
5942         if (!_vk_via_keyring || !kernel_keyring_support())
5943                 return 0;
5944
5945         if (dm_flags(cd, DM_CRYPT, &dmc_flags))
5946                 return dmcrypt_keyring_bug() ? 0 : 1;
5947
5948         return (dmc_flags & DM_KERNEL_KEYRING_SUPPORTED);
5949 }
5950
5951 int crypt_volume_key_keyring(struct crypt_device *cd, int enable)
5952 {
5953         _vk_via_keyring = enable ? 1 : 0;
5954         return 0;
5955 }
5956
5957 /* internal only */
5958 int crypt_volume_key_load_in_keyring(struct crypt_device *cd, struct volume_key *vk)
5959 {
5960         int r;
5961         const char *type_name = key_type_name(LOGON_KEY);
5962
5963         if (!vk || !cd || !type_name)
5964                 return -EINVAL;
5965
5966         if (!vk->key_description) {
5967                 log_dbg(cd, "Invalid key description");
5968                 return -EINVAL;
5969         }
5970
5971         log_dbg(cd, "Loading key (%zu bytes, type %s) in thread keyring.", vk->keylength, type_name);
5972
5973         r = keyring_add_key_in_thread_keyring(LOGON_KEY, vk->key_description, vk->key, vk->keylength);
5974         if (r) {
5975                 log_dbg(cd, "keyring_add_key_in_thread_keyring failed (error %d)", r);
5976                 log_err(cd, _("Failed to load key in kernel keyring."));
5977         } else
5978                 crypt_set_key_in_keyring(cd, 1);
5979
5980         return r;
5981 }
5982
5983 /* internal only */
5984 int crypt_key_in_keyring(struct crypt_device *cd)
5985 {
5986         return cd ? cd->key_in_keyring : 0;
5987 }
5988
5989 /* internal only */
5990 void crypt_set_key_in_keyring(struct crypt_device *cd, unsigned key_in_keyring)
5991 {
5992         if (!cd)
5993                 return;
5994
5995         cd->key_in_keyring = key_in_keyring;
5996 }
5997
5998 /* internal only */
5999 void crypt_drop_keyring_key_by_description(struct crypt_device *cd, const char *key_description, key_type_t ktype)
6000 {
6001         int r;
6002         const char *type_name = key_type_name(ktype);
6003
6004         if (!key_description || !type_name)
6005                 return;
6006
6007         log_dbg(cd, "Requesting keyring %s key for revoke and unlink.", type_name);
6008
6009         r = keyring_revoke_and_unlink_key(ktype, key_description);
6010         if (r)
6011                 log_dbg(cd, "keyring_revoke_and_unlink_key failed (error %d)", r);
6012         crypt_set_key_in_keyring(cd, 0);
6013 }
6014
6015 /* internal only */
6016 void crypt_drop_keyring_key(struct crypt_device *cd, struct volume_key *vks)
6017 {
6018         struct volume_key *vk = vks;
6019
6020         while (vk) {
6021                 crypt_drop_keyring_key_by_description(cd, vk->key_description, LOGON_KEY);
6022                 vk = crypt_volume_key_next(vk);
6023         }
6024 }
6025
6026 int crypt_activate_by_keyring(struct crypt_device *cd,
6027                               const char *name,
6028                               const char *key_description,
6029                               int keyslot,
6030                               uint32_t flags)
6031 {
6032         char *passphrase;
6033         size_t passphrase_size;
6034         int r;
6035
6036         if (!cd || !key_description)
6037                 return -EINVAL;
6038
6039         log_dbg(cd, "%s volume %s [keyslot %d] using passphrase in keyring.",
6040                 name ? "Activating" : "Checking", name ?: "passphrase", keyslot);
6041
6042         if (!kernel_keyring_support()) {
6043                 log_err(cd, _("Kernel keyring is not supported by the kernel."));
6044                 return -EINVAL;
6045         }
6046
6047         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
6048         if (r < 0)
6049                 return r;
6050
6051         r = keyring_get_passphrase(key_description, &passphrase, &passphrase_size);
6052         if (r < 0) {
6053                 log_err(cd, _("Failed to read passphrase from keyring (error %d)."), r);
6054                 return -EINVAL;
6055         }
6056
6057         r = _activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
6058
6059         crypt_safe_memzero(passphrase, passphrase_size);
6060         free(passphrase);
6061
6062         return r;
6063 }
6064
6065 /*
6066  * Workaround for serialization of parallel activation and memory-hard PBKDF
6067  * In specific situation (systemd activation) this causes OOM killer activation.
6068  * For now, let's provide this ugly way to serialize unlocking of devices.
6069  */
6070 int crypt_serialize_lock(struct crypt_device *cd)
6071 {
6072         if (!cd->memory_hard_pbkdf_lock_enabled)
6073                 return 0;
6074
6075         log_dbg(cd, "Taking global memory-hard access serialization lock.");
6076         if (crypt_write_lock(cd, "memory-hard-access", true, &cd->pbkdf_memory_hard_lock)) {
6077                 log_err(cd, _("Failed to acquire global memory-hard access serialization lock."));
6078                 cd->pbkdf_memory_hard_lock = NULL;
6079                 return -EINVAL;
6080         }
6081
6082         return 0;
6083 }
6084
6085 void crypt_serialize_unlock(struct crypt_device *cd)
6086 {
6087         if (!cd->memory_hard_pbkdf_lock_enabled)
6088                 return;
6089
6090         crypt_unlock_internal(cd, cd->pbkdf_memory_hard_lock);
6091         cd->pbkdf_memory_hard_lock = NULL;
6092 }
6093
6094 crypt_reencrypt_info crypt_reencrypt_status(struct crypt_device *cd,
6095                 struct crypt_params_reencrypt *params)
6096 {
6097         if (!cd || !isLUKS2(cd->type))
6098                 return CRYPT_REENCRYPT_NONE;
6099
6100         if (_onlyLUKS2(cd, CRYPT_CD_QUIET, CRYPT_REQUIREMENT_ONLINE_REENCRYPT))
6101                 return CRYPT_REENCRYPT_INVALID;
6102
6103         return LUKS2_reencrypt_get_params(&cd->u.luks2.hdr, params);
6104 }
6105
6106 static void __attribute__((destructor)) libcryptsetup_exit(void)
6107 {
6108         crypt_backend_destroy();
6109         crypt_random_exit();
6110 }