567f26249a7036aac0cbce174440e4c655492a12
[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-2020 Red Hat, Inc. All rights reserved.
7  * Copyright (C) 2009-2020 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_reenc_context *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)) {
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_reenc_context(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         if (cd->metadata_device) {
849                 log_err(cd, _("Detached metadata device is not supported for this crypt type."));
850                 return -EINVAL;
851         }
852
853         r = init_crypto(cd);
854         if (r < 0)
855                 return r;
856
857         memcpy(&cd->u.tcrypt.params, params, sizeof(*params));
858
859         r = TCRYPT_read_phdr(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
860
861         cd->u.tcrypt.params.passphrase = NULL;
862         cd->u.tcrypt.params.passphrase_size = 0;
863         cd->u.tcrypt.params.keyfiles = NULL;
864         cd->u.tcrypt.params.keyfiles_count = 0;
865         cd->u.tcrypt.params.veracrypt_pim = 0;
866
867         if (r < 0)
868                 return r;
869
870         if (!cd->type && !(cd->type = strdup(CRYPT_TCRYPT)))
871                 return -ENOMEM;
872
873         return r;
874 }
875
876 static int _crypt_load_verity(struct crypt_device *cd, struct crypt_params_verity *params)
877 {
878         int r;
879         size_t sb_offset = 0;
880
881         r = init_crypto(cd);
882         if (r < 0)
883                 return r;
884
885         if (params && params->flags & CRYPT_VERITY_NO_HEADER)
886                 return -EINVAL;
887
888         if (params)
889                 sb_offset = params->hash_area_offset;
890
891         r = VERITY_read_sb(cd, sb_offset, &cd->u.verity.uuid, &cd->u.verity.hdr);
892         if (r < 0)
893                 return r;
894
895         //FIXME: use crypt_free
896         if (!cd->type && !(cd->type = strdup(CRYPT_VERITY))) {
897                 free(CONST_CAST(void*)cd->u.verity.hdr.hash_name);
898                 free(CONST_CAST(void*)cd->u.verity.hdr.salt);
899                 free(cd->u.verity.uuid);
900                 crypt_safe_memzero(&cd->u.verity.hdr, sizeof(cd->u.verity.hdr));
901                 return -ENOMEM;
902         }
903
904         if (params)
905                 cd->u.verity.hdr.flags = params->flags;
906
907         /* Hash availability checked in sb load */
908         cd->u.verity.root_hash_size = crypt_hash_size(cd->u.verity.hdr.hash_name);
909         if (cd->u.verity.root_hash_size > 4096)
910                 return -EINVAL;
911
912         if (params && params->data_device &&
913             (r = crypt_set_data_device(cd, params->data_device)) < 0)
914                 return r;
915
916         if (params && params->fec_device) {
917                 r = device_alloc(cd, &cd->u.verity.fec_device, params->fec_device);
918                 if (r < 0)
919                         return r;
920                 cd->u.verity.hdr.fec_area_offset = params->fec_area_offset;
921                 cd->u.verity.hdr.fec_roots = params->fec_roots;
922         }
923
924         return r;
925 }
926
927 static int _crypt_load_integrity(struct crypt_device *cd,
928                                  struct crypt_params_integrity *params)
929 {
930         int r;
931
932         r = init_crypto(cd);
933         if (r < 0)
934                 return r;
935
936         r = INTEGRITY_read_sb(cd, &cd->u.integrity.params, &cd->u.integrity.sb_flags);
937         if (r < 0)
938                 return r;
939
940         // FIXME: add checks for fields in integrity sb vs params
941
942         if (params) {
943                 cd->u.integrity.params.journal_watermark = params->journal_watermark;
944                 cd->u.integrity.params.journal_commit_time = params->journal_commit_time;
945                 cd->u.integrity.params.buffer_sectors = params->buffer_sectors;
946                 // FIXME: check ENOMEM
947                 if (params->integrity)
948                         cd->u.integrity.params.integrity = strdup(params->integrity);
949                 cd->u.integrity.params.integrity_key_size = params->integrity_key_size;
950                 if (params->journal_integrity)
951                         cd->u.integrity.params.journal_integrity = strdup(params->journal_integrity);
952                 if (params->journal_crypt)
953                         cd->u.integrity.params.journal_crypt = strdup(params->journal_crypt);
954
955                 if (params->journal_crypt_key) {
956                         cd->u.integrity.journal_crypt_key =
957                                 crypt_alloc_volume_key(params->journal_crypt_key_size,
958                                                        params->journal_crypt_key);
959                         if (!cd->u.integrity.journal_crypt_key)
960                                 return -ENOMEM;
961                 }
962                 if (params->journal_integrity_key) {
963                         cd->u.integrity.journal_mac_key =
964                                 crypt_alloc_volume_key(params->journal_integrity_key_size,
965                                                        params->journal_integrity_key);
966                         if (!cd->u.integrity.journal_mac_key)
967                                 return -ENOMEM;
968                 }
969         }
970
971         if (!cd->type && !(cd->type = strdup(CRYPT_INTEGRITY))) {
972                 free(CONST_CAST(void*)cd->u.integrity.params.integrity);
973                 return -ENOMEM;
974         }
975
976         return 0;
977 }
978
979 static int _crypt_load_bitlk(struct crypt_device *cd,
980                              struct bitlk_metadata *params)
981 {
982         int r;
983
984         r = init_crypto(cd);
985         if (r < 0)
986                 return r;
987
988         r = BITLK_read_sb(cd, &cd->u.bitlk.params);
989         if (r < 0)
990                 return r;
991
992         if (asprintf(&cd->u.bitlk.cipher_spec, "%s-%s",
993                      cd->u.bitlk.params.cipher, cd->u.bitlk.params.cipher_mode) < 0) {
994                 cd->u.bitlk.cipher_spec = NULL;
995                 return -ENOMEM;
996         }
997
998         if (!cd->type && !(cd->type = strdup(CRYPT_BITLK)))
999                 return -ENOMEM;
1000
1001         return 0;
1002 }
1003
1004 int crypt_load(struct crypt_device *cd,
1005                const char *requested_type,
1006                void *params)
1007 {
1008         int r;
1009
1010         if (!cd)
1011                 return -EINVAL;
1012
1013         log_dbg(cd, "Trying to load %s crypt type from device %s.",
1014                 requested_type ?: "any", mdata_device_path(cd) ?: "(none)");
1015
1016         if (!crypt_metadata_device(cd))
1017                 return -EINVAL;
1018
1019         crypt_reset_null_type(cd);
1020         cd->data_offset = 0;
1021         cd->metadata_size = 0;
1022         cd->keyslots_size = 0;
1023
1024         if (!requested_type || isLUKS1(requested_type) || isLUKS2(requested_type)) {
1025                 if (cd->type && !isLUKS1(cd->type) && !isLUKS2(cd->type)) {
1026                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1027                         return -EINVAL;
1028                 }
1029
1030                 r = _crypt_load_luks(cd, requested_type, 1, 0);
1031         } else if (isVERITY(requested_type)) {
1032                 if (cd->type && !isVERITY(cd->type)) {
1033                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1034                         return -EINVAL;
1035                 }
1036                 r = _crypt_load_verity(cd, params);
1037         } else if (isTCRYPT(requested_type)) {
1038                 if (cd->type && !isTCRYPT(cd->type)) {
1039                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1040                         return -EINVAL;
1041                 }
1042                 r = _crypt_load_tcrypt(cd, params);
1043         } else if (isINTEGRITY(requested_type)) {
1044                 if (cd->type && !isINTEGRITY(cd->type)) {
1045                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1046                         return -EINVAL;
1047                 }
1048                 r = _crypt_load_integrity(cd, params);
1049         } else if (isBITLK(requested_type)) {
1050                 if (cd->type && !isBITLK(cd->type)) {
1051                         log_dbg(cd, "Context is already initialized to type %s", cd->type);
1052                         return -EINVAL;
1053                 }
1054                 r = _crypt_load_bitlk(cd, params);
1055         } else
1056                 return -EINVAL;
1057
1058         return r;
1059 }
1060
1061 /*
1062  * crypt_init() helpers
1063  */
1064 static int _init_by_name_crypt_none(struct crypt_device *cd)
1065 {
1066         int r;
1067         char _mode[MAX_CIPHER_LEN];
1068         struct crypt_dm_active_device dmd;
1069         struct dm_target *tgt = &dmd.segment;
1070
1071         if (cd->type || !cd->u.none.active_name)
1072                 return -EINVAL;
1073
1074         r = dm_query_device(cd, cd->u.none.active_name,
1075                         DM_ACTIVE_CRYPT_CIPHER |
1076                         DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
1077         if (r < 0)
1078                 return r;
1079         if (!single_segment(&dmd) || tgt->type != DM_CRYPT)
1080                 r = -EINVAL;
1081         if (r >= 0)
1082                 r = crypt_parse_name_and_mode(tgt->u.crypt.cipher,
1083                                               cd->u.none.cipher, NULL,
1084                                               _mode);
1085
1086         if (!r) {
1087                 snprintf(cd->u.none.cipher_spec, sizeof(cd->u.none.cipher_spec),
1088                          "%s-%s", cd->u.none.cipher, _mode);
1089                 cd->u.none.cipher_mode = cd->u.none.cipher_spec + strlen(cd->u.none.cipher) + 1;
1090                 cd->u.none.key_size = tgt->u.crypt.vk->keylength;
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_reenc_context_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 (!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.jobj)))
1854                 log_std(cd, _("WARNING: LUKS2 metadata size changed to %" PRIu64 " bytes.\n"),
1855                         LUKS2_metadata_size(cd->u.luks2.hdr.jobj));
1856
1857         if (cd->keyslots_size && (cd->keyslots_size != LUKS2_keyslots_size(cd->u.luks2.hdr.jobj)))
1858                 log_std(cd, _("WARNING: LUKS2 keyslots area size changed to %" PRIu64 " bytes.\n"),
1859                         LUKS2_keyslots_size(cd->u.luks2.hdr.jobj));
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);
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.jobj))
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)) &&
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) &&
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) &&
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         if (_compare_volume_keys(src->u.crypt.vk, 0, tgt->u.crypt.vk, tgt->u.crypt.vk->key_description != NULL)) {
2392                 log_dbg(cd, "Keys in context and target device do not match.");
2393                 return -EINVAL;
2394         }
2395
2396         /* CIPHER checks */
2397         if (!src->u.crypt.cipher || !tgt->u.crypt.cipher)
2398                 return -EINVAL;
2399         if (strcmp(src->u.crypt.cipher, tgt->u.crypt.cipher)) {
2400                 log_dbg(cd, "Cipher specs do not match.");
2401                 return -EINVAL;
2402         }
2403         if (crypt_strcmp(src->u.crypt.integrity, tgt->u.crypt.integrity)) {
2404                 log_dbg(cd, "Integrity parameters do not match.");
2405                 return -EINVAL;
2406         }
2407
2408         if (src->u.crypt.offset      != tgt->u.crypt.offset ||
2409             src->u.crypt.sector_size != tgt->u.crypt.sector_size ||
2410             src->u.crypt.iv_offset   != tgt->u.crypt.iv_offset ||
2411             src->u.crypt.tag_size    != tgt->u.crypt.tag_size) {
2412                 log_dbg(cd, "Integer parameters do not match.");
2413                 return -EINVAL;
2414         }
2415
2416         if (!device_is_identical(src->data_device, tgt->data_device)) {
2417                 log_dbg(cd, "Data devices do not match.");
2418                 return -EINVAL;
2419         }
2420
2421         return 0;
2422 }
2423
2424 static int _compare_integrity_devices(struct crypt_device *cd,
2425                                const struct dm_target *src,
2426                                const struct dm_target *tgt)
2427 {
2428         /*
2429          * some parameters may be implicit (and set in dm-integrity ctor)
2430          *
2431          *      journal_size
2432          *      journal_watermark
2433          *      journal_commit_time
2434          *      buffer_sectors
2435          *      interleave_sectors
2436          */
2437
2438         /* check remaining integer values that makes sense */
2439         if (src->u.integrity.tag_size     != tgt->u.integrity.tag_size ||
2440             src->u.integrity.offset       != tgt->u.integrity.offset   ||
2441             src->u.integrity.sector_size  != tgt->u.integrity.sector_size) {
2442                 log_dbg(cd, "Integer parameters do not match.");
2443                 return -EINVAL;
2444         }
2445
2446         if (crypt_strcmp(src->u.integrity.integrity,         tgt->u.integrity.integrity) ||
2447             crypt_strcmp(src->u.integrity.journal_integrity, tgt->u.integrity.journal_integrity) ||
2448             crypt_strcmp(src->u.integrity.journal_crypt,     tgt->u.integrity.journal_crypt)) {
2449                 log_dbg(cd, "Journal parameters do not match.");
2450                 return -EINVAL;
2451         }
2452
2453         /* unfortunately dm-integrity doesn't support keyring */
2454         if (_compare_volume_keys(src->u.integrity.vk, 0, tgt->u.integrity.vk, 0) ||
2455             _compare_volume_keys(src->u.integrity.journal_integrity_key, 0, tgt->u.integrity.journal_integrity_key, 0) ||
2456             _compare_volume_keys(src->u.integrity.journal_crypt_key, 0, tgt->u.integrity.journal_crypt_key, 0)) {
2457                 log_dbg(cd, "Journal keys do not match.");
2458                 return -EINVAL;
2459         }
2460
2461         /* unsupported underneath dm-crypt with auth. encryption */
2462         if (src->u.integrity.meta_device || tgt->u.integrity.meta_device)
2463                 return -ENOTSUP;
2464
2465         if (src->size != tgt->size) {
2466                 log_dbg(cd, "Device size parameters do not match.");
2467                 return -EINVAL;
2468         }
2469
2470         if (!device_is_identical(src->data_device, tgt->data_device)) {
2471                 log_dbg(cd, "Data devices do not match.");
2472                 return -EINVAL;
2473         }
2474
2475         return 0;
2476 }
2477
2478 int crypt_compare_dm_devices(struct crypt_device *cd,
2479                                const struct crypt_dm_active_device *src,
2480                                const struct crypt_dm_active_device *tgt)
2481 {
2482         int r;
2483         const struct dm_target *s, *t;
2484
2485         if (!src || !tgt)
2486                 return -EINVAL;
2487
2488         r = _compare_device_types(cd, src, tgt);
2489         if (r)
2490                 return r;
2491
2492         s = &src->segment;
2493         t = &tgt->segment;
2494
2495         while (s || t) {
2496                 if (!s || !t) {
2497                         log_dbg(cd, "segments count mismatch.");
2498                         return -EINVAL;
2499                 }
2500                 if (s->type != t->type) {
2501                         log_dbg(cd, "segment type mismatch.");
2502                         r = -EINVAL;
2503                         break;
2504                 }
2505
2506                 switch (s->type) {
2507                 case DM_CRYPT:
2508                         r = _compare_crypt_devices(cd, s, t);
2509                         break;
2510                 case DM_INTEGRITY:
2511                         r = _compare_integrity_devices(cd, s, t);
2512                         break;
2513                 case DM_LINEAR:
2514                         r = (s->u.linear.offset == t->u.linear.offset) ? 0 : -EINVAL;
2515                         break;
2516                 default:
2517                         r = -ENOTSUP;
2518                 }
2519
2520                 if (r)
2521                         break;
2522
2523                 s = s->next;
2524                 t = t->next;
2525         }
2526
2527         return r;
2528 }
2529
2530 static int _reload_device(struct crypt_device *cd, const char *name,
2531                           struct crypt_dm_active_device *sdmd)
2532 {
2533         int r;
2534         struct crypt_dm_active_device tdmd;
2535         struct dm_target *src, *tgt = &tdmd.segment;
2536
2537         if (!cd || !cd->type || !name || !(sdmd->flags & CRYPT_ACTIVATE_REFRESH))
2538                 return -EINVAL;
2539
2540         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
2541                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
2542                                   DM_ACTIVE_CRYPT_KEY, &tdmd);
2543         if (r < 0) {
2544                 log_err(cd, _("Device %s is not active."), name);
2545                 return -EINVAL;
2546         }
2547
2548         if (!single_segment(&tdmd) || tgt->type != DM_CRYPT || tgt->u.crypt.tag_size) {
2549                 r = -ENOTSUP;
2550                 log_err(cd, _("Unsupported parameters on device %s."), name);
2551                 goto out;
2552         }
2553
2554         r = crypt_compare_dm_devices(cd, sdmd, &tdmd);
2555         if (r) {
2556                 log_err(cd, _("Mismatching parameters on device %s."), name);
2557                 goto out;
2558         }
2559
2560         src = &sdmd->segment;
2561
2562         /* Changing read only flag for active device makes no sense */
2563         if (tdmd.flags & CRYPT_ACTIVATE_READONLY)
2564                 sdmd->flags |= CRYPT_ACTIVATE_READONLY;
2565         else
2566                 sdmd->flags &= ~CRYPT_ACTIVATE_READONLY;
2567
2568         if (sdmd->flags & CRYPT_ACTIVATE_KEYRING_KEY) {
2569                 r = crypt_volume_key_set_description(tgt->u.crypt.vk, src->u.crypt.vk->key_description);
2570                 if (r)
2571                         goto out;
2572         } else {
2573                 crypt_free_volume_key(tgt->u.crypt.vk);
2574                 tgt->u.crypt.vk = crypt_alloc_volume_key(src->u.crypt.vk->keylength, src->u.crypt.vk->key);
2575                 if (!tgt->u.crypt.vk) {
2576                         r = -ENOMEM;
2577                         goto out;
2578                 }
2579         }
2580
2581         r = device_block_adjust(cd, src->data_device, DEV_OK,
2582                                 src->u.crypt.offset, &sdmd->size, NULL);
2583         if (r)
2584                 goto out;
2585
2586         tdmd.flags = sdmd->flags;
2587         tgt->size = tdmd.size = sdmd->size;
2588
2589         r = dm_reload_device(cd, name, &tdmd, 0, 1);
2590 out:
2591         dm_targets_free(cd, &tdmd);
2592         free(CONST_CAST(void*)tdmd.uuid);
2593
2594         return r;
2595 }
2596
2597 static int _reload_device_with_integrity(struct crypt_device *cd,
2598         const char *name,
2599         const char *iname,
2600         const char *ipath,
2601         struct crypt_dm_active_device *sdmd,
2602         struct crypt_dm_active_device *sdmdi)
2603 {
2604         int r;
2605         struct crypt_dm_active_device tdmd, tdmdi = {};
2606         struct dm_target *src, *srci, *tgt = &tdmd.segment, *tgti = &tdmdi.segment;
2607         struct device *data_device = NULL;
2608
2609         if (!cd || !cd->type || !name || !iname || !(sdmd->flags & CRYPT_ACTIVATE_REFRESH))
2610                 return -EINVAL;
2611
2612         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE | DM_ACTIVE_CRYPT_CIPHER |
2613                                   DM_ACTIVE_UUID | DM_ACTIVE_CRYPT_KEYSIZE |
2614                                   DM_ACTIVE_CRYPT_KEY, &tdmd);
2615         if (r < 0) {
2616                 log_err(cd, _("Device %s is not active."), name);
2617                 return -EINVAL;
2618         }
2619
2620         if (!single_segment(&tdmd) || tgt->type != DM_CRYPT || !tgt->u.crypt.tag_size) {
2621                 r = -ENOTSUP;
2622                 log_err(cd, _("Unsupported parameters on device %s."), name);
2623                 goto out;
2624         }
2625
2626         r = dm_query_device(cd, iname, DM_ACTIVE_DEVICE | DM_ACTIVE_UUID, &tdmdi);
2627         if (r < 0) {
2628                 log_err(cd, _("Device %s is not active."), iname);
2629                 r = -EINVAL;
2630                 goto out;
2631         }
2632
2633         if (!single_segment(&tdmdi) || tgti->type != DM_INTEGRITY) {
2634                 r = -ENOTSUP;
2635                 log_err(cd, _("Unsupported parameters on device %s."), iname);
2636                 goto out;
2637         }
2638
2639         r = crypt_compare_dm_devices(cd, sdmdi, &tdmdi);
2640         if (r) {
2641                 log_err(cd, _("Mismatching parameters on device %s."), iname);
2642                 goto out;
2643         }
2644
2645         src = &sdmd->segment;
2646         srci = &sdmdi->segment;
2647
2648         r = device_alloc(cd, &data_device, ipath);
2649         if (r < 0)
2650                 goto out;
2651
2652         r = device_block_adjust(cd, srci->data_device, DEV_OK,
2653                                 srci->u.integrity.offset, &sdmdi->size, NULL);
2654         if (r)
2655                 goto out;
2656
2657         src->data_device = data_device;
2658
2659         r = crypt_compare_dm_devices(cd, sdmd, &tdmd);
2660         if (r) {
2661                 log_err(cd, _("Crypt devices mismatch."));
2662                 goto out;
2663         }
2664
2665         /* Changing read only flag for active device makes no sense */
2666         if (tdmd.flags & CRYPT_ACTIVATE_READONLY)
2667                 sdmd->flags |= CRYPT_ACTIVATE_READONLY;
2668         else
2669                 sdmd->flags &= ~CRYPT_ACTIVATE_READONLY;
2670
2671         if (tdmdi.flags & CRYPT_ACTIVATE_READONLY)
2672                 sdmdi->flags |= CRYPT_ACTIVATE_READONLY;
2673         else
2674                 sdmdi->flags &= ~CRYPT_ACTIVATE_READONLY;
2675
2676         if (sdmd->flags & CRYPT_ACTIVATE_KEYRING_KEY) {
2677                 r = crypt_volume_key_set_description(tgt->u.crypt.vk, src->u.crypt.vk->key_description);
2678                 if (r)
2679                         goto out;
2680         } else {
2681                 crypt_free_volume_key(tgt->u.crypt.vk);
2682                 tgt->u.crypt.vk = crypt_alloc_volume_key(src->u.crypt.vk->keylength, src->u.crypt.vk->key);
2683                 if (!tgt->u.crypt.vk) {
2684                         r = -ENOMEM;
2685                         goto out;
2686                 }
2687         }
2688
2689         r = device_block_adjust(cd, src->data_device, DEV_OK,
2690                                 src->u.crypt.offset, &sdmd->size, NULL);
2691         if (r)
2692                 goto out;
2693
2694         tdmd.flags = sdmd->flags;
2695         tdmd.size = sdmd->size;
2696
2697         if ((r = dm_reload_device(cd, iname, sdmdi, 0, 0))) {
2698                 log_err(cd, _("Failed to reload device %s."), iname);
2699                 goto out;
2700         }
2701
2702         if ((r = dm_reload_device(cd, name, &tdmd, 0, 0))) {
2703                 log_err(cd, _("Failed to reload device %s."), name);
2704                 goto err_clear;
2705         }
2706
2707         if ((r = dm_suspend_device(cd, name, 0))) {
2708                 log_err(cd, _("Failed to suspend device %s."), name);
2709                 goto err_clear;
2710         }
2711
2712         if ((r = dm_suspend_device(cd, iname, 0))) {
2713                 log_err(cd, _("Failed to suspend device %s."), iname);
2714                 goto err_clear;
2715         }
2716
2717         if ((r = dm_resume_device(cd, iname, act2dmflags(sdmdi->flags)))) {
2718                 log_err(cd, _("Failed to resume device %s."), iname);
2719                 goto err_clear;
2720         }
2721
2722         r = dm_resume_device(cd, name, act2dmflags(tdmd.flags));
2723         if (!r)
2724                 goto out;
2725
2726         /*
2727          * This is worst case scenario. We have active underlying dm-integrity device with
2728          * new table but dm-crypt resume failed for some reason. Tear everything down and
2729          * burn it for good.
2730          */
2731
2732         log_err(cd, _("Fatal error while reloading device %s (on top of device %s)."), name, iname);
2733
2734         if (dm_error_device(cd, name))
2735                 log_err(cd, _("Failed to switch device %s to dm-error."), name);
2736         if (dm_error_device(cd, iname))
2737                 log_err(cd, _("Failed to switch device %s to dm-error."), iname);
2738         goto out;
2739
2740 err_clear:
2741         dm_clear_device(cd, name);
2742         dm_clear_device(cd, iname);
2743
2744         if (dm_status_suspended(cd, name) > 0)
2745                 dm_resume_device(cd, name, 0);
2746         if (dm_status_suspended(cd, iname) > 0)
2747                 dm_resume_device(cd, iname, 0);
2748 out:
2749         dm_targets_free(cd, &tdmd);
2750         dm_targets_free(cd, &tdmdi);
2751         free(CONST_CAST(void*)tdmdi.uuid);
2752         free(CONST_CAST(void*)tdmd.uuid);
2753         device_free(cd, data_device);
2754
2755         return r;
2756 }
2757
2758 int crypt_resize(struct crypt_device *cd, const char *name, uint64_t new_size)
2759 {
2760         struct crypt_dm_active_device dmdq, dmd = {};
2761         struct dm_target *tgt = &dmdq.segment;
2762         int r;
2763
2764         /*
2765          * FIXME: Also with LUKS2 we must not allow resize when there's
2766          *        explicit size stored in metadata (length != "dynamic")
2767          */
2768
2769         /* Device context type must be initialized */
2770         if (!cd || !cd->type || !name)
2771                 return -EINVAL;
2772
2773         log_dbg(cd, "Resizing device %s to %" PRIu64 " sectors.", name, new_size);
2774
2775         r = dm_query_device(cd, name, DM_ACTIVE_CRYPT_KEYSIZE | DM_ACTIVE_CRYPT_KEY, &dmdq);
2776         if (r < 0) {
2777                 log_err(cd, _("Device %s is not active."), name);
2778                 return -EINVAL;
2779         }
2780         if (!single_segment(&dmdq) || tgt->type != DM_CRYPT) {
2781                 log_dbg(cd, "Unsupported device table detected in %s.", name);
2782                 r = -EINVAL;
2783                 goto out;
2784         }
2785
2786         if ((dmdq.flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_key_in_keyring(cd)) {
2787                 r = -EPERM;
2788                 goto out;
2789         }
2790
2791         if (crypt_key_in_keyring(cd)) {
2792                 if (!isLUKS2(cd->type)) {
2793                         r = -EINVAL;
2794                         goto out;
2795                 }
2796                 r = LUKS2_key_description_by_segment(cd, &cd->u.luks2.hdr,
2797                                         tgt->u.crypt.vk, CRYPT_DEFAULT_SEGMENT);
2798                 if (r)
2799                         goto out;
2800
2801                 dmdq.flags |= CRYPT_ACTIVATE_KEYRING_KEY;
2802         }
2803
2804         if (crypt_loop_device(crypt_get_device_name(cd))) {
2805                 log_dbg(cd, "Trying to resize underlying loop device %s.",
2806                         crypt_get_device_name(cd));
2807                 /* Here we always use default size not new_size */
2808                 if (crypt_loop_resize(crypt_get_device_name(cd)))
2809                         log_err(cd, _("Cannot resize loop device."));
2810         }
2811
2812         r = device_block_adjust(cd, crypt_data_device(cd), DEV_OK,
2813                                 crypt_get_data_offset(cd), &new_size, &dmdq.flags);
2814         if (r)
2815                 goto out;
2816
2817         if (MISALIGNED(new_size, tgt->u.crypt.sector_size >> SECTOR_SHIFT)) {
2818                 log_err(cd, _("Device size is not aligned to requested sector size."));
2819                 r = -EINVAL;
2820                 goto out;
2821         }
2822
2823         if (MISALIGNED(new_size, device_block_size(cd, crypt_data_device(cd)) >> SECTOR_SHIFT)) {
2824                 log_err(cd, _("Device size is not aligned to device logical block size."));
2825                 r = -EINVAL;
2826                 goto out;
2827         }
2828
2829         dmd.uuid = crypt_get_uuid(cd);
2830         dmd.size = new_size;
2831         dmd.flags = dmdq.flags | CRYPT_ACTIVATE_REFRESH;
2832         r = dm_crypt_target_set(&dmd.segment, 0, new_size, crypt_data_device(cd),
2833                         tgt->u.crypt.vk, crypt_get_cipher_spec(cd),
2834                         crypt_get_iv_offset(cd), crypt_get_data_offset(cd),
2835                         crypt_get_integrity(cd), crypt_get_integrity_tag_size(cd),
2836                         crypt_get_sector_size(cd));
2837         if (r < 0)
2838                 goto out;
2839
2840         if (new_size == dmdq.size) {
2841                 log_dbg(cd, "Device has already requested size %" PRIu64
2842                         " sectors.", dmdq.size);
2843                 r = 0;
2844         } else {
2845                 if (isTCRYPT(cd->type))
2846                         r = -ENOTSUP;
2847                 else if (isLUKS2(cd->type))
2848                         r = LUKS2_unmet_requirements(cd, &cd->u.luks2.hdr, 0, 0);
2849                 if (!r)
2850                         r = _reload_device(cd, name, &dmd);
2851         }
2852 out:
2853         dm_targets_free(cd, &dmd);
2854         dm_targets_free(cd, &dmdq);
2855
2856         return r;
2857 }
2858
2859 int crypt_set_uuid(struct crypt_device *cd, const char *uuid)
2860 {
2861         const char *active_uuid;
2862         int r;
2863
2864         log_dbg(cd, "%s device uuid.", uuid ? "Setting new" : "Refreshing");
2865
2866         if ((r = onlyLUKS(cd)))
2867                 return r;
2868
2869         active_uuid = crypt_get_uuid(cd);
2870
2871         if (uuid && active_uuid && !strncmp(uuid, active_uuid, UUID_STRING_L)) {
2872                 log_dbg(cd, "UUID is the same as requested (%s) for device %s.",
2873                         uuid, mdata_device_path(cd));
2874                 return 0;
2875         }
2876
2877         if (uuid)
2878                 log_dbg(cd, "Requested new UUID change to %s for %s.", uuid, mdata_device_path(cd));
2879         else
2880                 log_dbg(cd, "Requested new UUID refresh for %s.", mdata_device_path(cd));
2881
2882         if (!crypt_confirm(cd, _("Do you really want to change UUID of device?")))
2883                 return -EPERM;
2884
2885         if (isLUKS1(cd->type))
2886                 return LUKS_hdr_uuid_set(&cd->u.luks1.hdr, uuid, cd);
2887         else
2888                 return LUKS2_hdr_uuid(cd, &cd->u.luks2.hdr, uuid);
2889 }
2890
2891 int crypt_set_label(struct crypt_device *cd, const char *label, const char *subsystem)
2892 {
2893         int r;
2894
2895         log_dbg(cd, "Setting new labels.");
2896
2897         if ((r = onlyLUKS2(cd)))
2898                 return r;
2899
2900         return LUKS2_hdr_labels(cd, &cd->u.luks2.hdr, label, subsystem, 1);
2901 }
2902
2903 int crypt_header_backup(struct crypt_device *cd,
2904                         const char *requested_type,
2905                         const char *backup_file)
2906 {
2907         int r;
2908
2909         if (requested_type && !isLUKS(requested_type))
2910                 return -EINVAL;
2911
2912         if (!backup_file)
2913                 return -EINVAL;
2914
2915         /* Load with repair */
2916         r = _crypt_load_luks(cd, requested_type, 1, 0);
2917         if (r < 0)
2918                 return r;
2919
2920         log_dbg(cd, "Requested header backup of device %s (%s) to "
2921                 "file %s.", mdata_device_path(cd), requested_type ?: "any type", backup_file);
2922
2923         if (isLUKS1(cd->type) && (!requested_type || isLUKS1(requested_type)))
2924                 r = LUKS_hdr_backup(backup_file, cd);
2925         else if (isLUKS2(cd->type) && (!requested_type || isLUKS2(requested_type)))
2926                 r = LUKS2_hdr_backup(cd, &cd->u.luks2.hdr, backup_file);
2927         else
2928                 r = -EINVAL;
2929
2930         return r;
2931 }
2932
2933 int crypt_header_restore(struct crypt_device *cd,
2934                          const char *requested_type,
2935                          const char *backup_file)
2936 {
2937         struct luks_phdr hdr1;
2938         struct luks2_hdr hdr2;
2939         int r, version;
2940
2941         if (requested_type && !isLUKS(requested_type))
2942                 return -EINVAL;
2943
2944         if (!cd || (cd->type && !isLUKS(cd->type)) || !backup_file)
2945                 return -EINVAL;
2946
2947         r = init_crypto(cd);
2948         if (r < 0)
2949                 return r;
2950
2951         log_dbg(cd, "Requested header restore to device %s (%s) from "
2952                 "file %s.", mdata_device_path(cd), requested_type ?: "any type", backup_file);
2953
2954         version = LUKS2_hdr_version_unlocked(cd, backup_file);
2955         if (!version ||
2956            (requested_type && version == 1 && !isLUKS1(requested_type)) ||
2957            (requested_type && version == 2 && !isLUKS2(requested_type))) {
2958                 log_err(cd, _("Header backup file does not contain compatible LUKS header."));
2959                 return -EINVAL;
2960         }
2961
2962         memset(&hdr2, 0, sizeof(hdr2));
2963
2964         if (!cd->type) {
2965                 if (version == 1)
2966                         r = LUKS_hdr_restore(backup_file, &hdr1, cd);
2967                 else
2968                         r = LUKS2_hdr_restore(cd, &hdr2, backup_file);
2969
2970                 crypt_safe_memzero(&hdr1, sizeof(hdr1));
2971                 crypt_safe_memzero(&hdr2, sizeof(hdr2));
2972         } else if (isLUKS2(cd->type) && (!requested_type || isLUKS2(requested_type))) {
2973                 r = LUKS2_hdr_restore(cd, &cd->u.luks2.hdr, backup_file);
2974                 if (r)
2975                         _luks2_reload(cd);
2976         } else if (isLUKS1(cd->type) && (!requested_type || isLUKS1(requested_type)))
2977                 r = LUKS_hdr_restore(backup_file, &cd->u.luks1.hdr, cd);
2978         else
2979                 r = -EINVAL;
2980
2981         if (!r)
2982                 r = _crypt_load_luks(cd, version == 1 ? CRYPT_LUKS1 : CRYPT_LUKS2, 1, 1);
2983
2984         return r;
2985 }
2986
2987 void crypt_free(struct crypt_device *cd)
2988 {
2989         if (!cd)
2990                 return;
2991
2992         log_dbg(cd, "Releasing crypt device %s context.", mdata_device_path(cd));
2993
2994         dm_backend_exit(cd);
2995         crypt_free_volume_key(cd->volume_key);
2996
2997         crypt_free_type(cd);
2998
2999         device_free(cd, cd->device);
3000         device_free(cd, cd->metadata_device);
3001
3002         free(CONST_CAST(void*)cd->pbkdf.type);
3003         free(CONST_CAST(void*)cd->pbkdf.hash);
3004
3005         /* Some structures can contain keys (TCRYPT), wipe it */
3006         crypt_safe_memzero(cd, sizeof(*cd));
3007         free(cd);
3008 }
3009
3010 static char *crypt_get_device_key_description(struct crypt_device *cd, const char *name)
3011 {
3012         char *desc = NULL;
3013         struct crypt_dm_active_device dmd;
3014         struct dm_target *tgt = &dmd.segment;
3015
3016         if (dm_query_device(cd, name, DM_ACTIVE_CRYPT_KEY | DM_ACTIVE_CRYPT_KEYSIZE, &dmd) < 0)
3017                 return NULL;
3018
3019         if (single_segment(&dmd) && tgt->type == DM_CRYPT &&
3020             (dmd.flags & CRYPT_ACTIVATE_KEYRING_KEY) && tgt->u.crypt.vk->key_description)
3021                 desc = strdup(tgt->u.crypt.vk->key_description);
3022
3023         dm_targets_free(cd, &dmd);
3024
3025         return desc;
3026 }
3027
3028 int crypt_suspend(struct crypt_device *cd,
3029                   const char *name)
3030 {
3031         char *key_desc;
3032         crypt_status_info ci;
3033         int r;
3034         uint32_t dmflags = DM_SUSPEND_WIPE_KEY;
3035
3036         /* FIXME: check context uuid matches the dm-crypt device uuid (onlyLUKS branching) */
3037
3038         if (!cd || !name)
3039                 return -EINVAL;
3040
3041         log_dbg(cd, "Suspending volume %s.", name);
3042
3043         if (cd->type)
3044                 r = onlyLUKS(cd);
3045         else {
3046                 r = crypt_uuid_type_cmp(cd, CRYPT_LUKS1);
3047                 if (r < 0)
3048                         r = crypt_uuid_type_cmp(cd, CRYPT_LUKS2);
3049                 if (r < 0)
3050                         log_err(cd, _("This operation is supported only for LUKS device."));
3051         }
3052
3053         if (r < 0)
3054                 return r;
3055
3056         ci = crypt_status(NULL, name);
3057         if (ci < CRYPT_ACTIVE) {
3058                 log_err(cd, _("Volume %s is not active."), name);
3059                 return -EINVAL;
3060         }
3061
3062         dm_backend_init(cd);
3063
3064         r = dm_status_suspended(cd, name);
3065         if (r < 0)
3066                 goto out;
3067
3068         if (r) {
3069                 log_err(cd, _("Volume %s is already suspended."), name);
3070                 r = -EINVAL;
3071                 goto out;
3072         }
3073
3074         key_desc = crypt_get_device_key_description(cd, name);
3075
3076         /* we can't simply wipe wrapped keys */
3077         if (crypt_cipher_wrapped_key(crypt_get_cipher(cd), crypt_get_cipher_mode(cd)))
3078                 dmflags &= ~DM_SUSPEND_WIPE_KEY;
3079
3080         r = dm_suspend_device(cd, name, dmflags);
3081         if (r == -ENOTSUP)
3082                 log_err(cd, _("Suspend is not supported for device %s."), name);
3083         else if (r)
3084                 log_err(cd, _("Error during suspending device %s."), name);
3085         else
3086                 crypt_drop_keyring_key_by_description(cd, key_desc, LOGON_KEY);
3087         free(key_desc);
3088 out:
3089         dm_backend_exit(cd);
3090         return r;
3091 }
3092
3093 int crypt_resume_by_passphrase(struct crypt_device *cd,
3094                                const char *name,
3095                                int keyslot,
3096                                const char *passphrase,
3097                                size_t passphrase_size)
3098 {
3099         struct volume_key *vk = NULL;
3100         int r;
3101
3102         /* FIXME: check context uuid matches the dm-crypt device uuid */
3103
3104         if (!passphrase || !name)
3105                 return -EINVAL;
3106
3107         log_dbg(cd, "Resuming volume %s.", name);
3108
3109         if ((r = onlyLUKS(cd)))
3110                 return r;
3111
3112         r = dm_status_suspended(cd, name);
3113         if (r < 0)
3114                 return r;
3115
3116         if (!r) {
3117                 log_err(cd, _("Volume %s is not suspended."), name);
3118                 return -EINVAL;
3119         }
3120
3121         if (isLUKS1(cd->type))
3122                 r = LUKS_open_key_with_hdr(keyslot, passphrase, passphrase_size,
3123                                            &cd->u.luks1.hdr, &vk, cd);
3124         else
3125                 r = LUKS2_keyslot_open(cd, keyslot, CRYPT_DEFAULT_SEGMENT, passphrase, passphrase_size, &vk);
3126
3127         if  (r < 0)
3128                 goto out;
3129
3130         keyslot = r;
3131
3132         if (crypt_use_keyring_for_vk(cd)) {
3133                 if (!isLUKS2(cd->type)) {
3134                         r = -EINVAL;
3135                         goto out;
3136                 }
3137                 r = LUKS2_volume_key_load_in_keyring_by_keyslot(cd,
3138                                         &cd->u.luks2.hdr, vk, keyslot);
3139                 if (r < 0)
3140                         goto out;
3141         }
3142
3143         r = dm_resume_and_reinstate_key(cd, name, vk);
3144
3145         if (r == -ENOTSUP)
3146                 log_err(cd, _("Resume is not supported for device %s."), name);
3147         else if (r)
3148                 log_err(cd, _("Error during resuming device %s."), name);
3149 out:
3150         if (r < 0)
3151                 crypt_drop_keyring_key(cd, vk);
3152         crypt_free_volume_key(vk);
3153
3154         return r < 0 ? r : keyslot;
3155 }
3156
3157 int crypt_resume_by_keyfile_device_offset(struct crypt_device *cd,
3158                                           const char *name,
3159                                           int keyslot,
3160                                           const char *keyfile,
3161                                           size_t keyfile_size,
3162                                           uint64_t keyfile_offset)
3163 {
3164         struct volume_key *vk = NULL;
3165         char *passphrase_read = NULL;
3166         size_t passphrase_size_read;
3167         int r;
3168
3169         /* FIXME: check context uuid matches the dm-crypt device uuid */
3170
3171         if (!name || !keyfile)
3172                 return -EINVAL;
3173
3174         log_dbg(cd, "Resuming volume %s.", name);
3175
3176         if ((r = onlyLUKS(cd)))
3177                 return r;
3178
3179         r = dm_status_suspended(cd, name);
3180         if (r < 0)
3181                 return r;
3182
3183         if (!r) {
3184                 log_err(cd, _("Volume %s is not suspended."), name);
3185                 return -EINVAL;
3186         }
3187
3188         r = crypt_keyfile_device_read(cd, keyfile,
3189                                       &passphrase_read, &passphrase_size_read,
3190                                       keyfile_offset, keyfile_size, 0);
3191         if (r < 0)
3192                 goto out;
3193
3194         if (isLUKS1(cd->type))
3195                 r = LUKS_open_key_with_hdr(keyslot, passphrase_read, passphrase_size_read,
3196                                            &cd->u.luks1.hdr, &vk, cd);
3197         else
3198                 r = LUKS2_keyslot_open(cd, keyslot, CRYPT_DEFAULT_SEGMENT, passphrase_read, passphrase_size_read, &vk);
3199         if (r < 0)
3200                 goto out;
3201         keyslot = r;
3202
3203         if (crypt_use_keyring_for_vk(cd)) {
3204                 if (!isLUKS2(cd->type)) {
3205                         r = -EINVAL;
3206                         goto out;
3207                 }
3208                 r = LUKS2_volume_key_load_in_keyring_by_keyslot(cd,
3209                                         &cd->u.luks2.hdr, vk, keyslot);
3210                 if (r < 0)
3211                         goto out;
3212         }
3213
3214         r = dm_resume_and_reinstate_key(cd, name, vk);
3215         if (r < 0)
3216                 log_err(cd, _("Error during resuming device %s."), name);
3217 out:
3218         crypt_safe_free(passphrase_read);
3219         if (r < 0)
3220                 crypt_drop_keyring_key(cd, vk);
3221         crypt_free_volume_key(vk);
3222         return r < 0 ? r : keyslot;
3223 }
3224
3225 int crypt_resume_by_keyfile(struct crypt_device *cd,
3226                             const char *name,
3227                             int keyslot,
3228                             const char *keyfile,
3229                             size_t keyfile_size)
3230 {
3231         return crypt_resume_by_keyfile_device_offset(cd, name, keyslot,
3232                                               keyfile, keyfile_size, 0);
3233 }
3234
3235 int crypt_resume_by_keyfile_offset(struct crypt_device *cd,
3236                                    const char *name,
3237                                    int keyslot,
3238                                    const char *keyfile,
3239                                    size_t keyfile_size,
3240                                    size_t keyfile_offset)
3241 {
3242         return crypt_resume_by_keyfile_device_offset(cd, name, keyslot,
3243                                       keyfile, keyfile_size, keyfile_offset);
3244 }
3245
3246 int crypt_resume_by_volume_key(struct crypt_device *cd,
3247         const char *name,
3248         const char *volume_key,
3249         size_t volume_key_size)
3250 {
3251         struct volume_key *vk = NULL;
3252         int r;
3253
3254         if (!name || !volume_key)
3255                 return -EINVAL;
3256
3257         log_dbg(cd, "Resuming volume %s by volume key.", name);
3258
3259         if ((r = onlyLUKS(cd)))
3260                 return r;
3261
3262         r = dm_status_suspended(cd, name);
3263         if (r < 0)
3264                 return r;
3265
3266         if (!r) {
3267                 log_err(cd, _("Volume %s is not suspended."), name);
3268                 return -EINVAL;
3269         }
3270
3271         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
3272         if (!vk)
3273                 return -ENOMEM;
3274
3275         if (isLUKS1(cd->type))
3276                 r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
3277         else if (isLUKS2(cd->type))
3278                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
3279         else
3280                 r = -EINVAL;
3281         if (r == -EPERM || r == -ENOENT)
3282                 log_err(cd, _("Volume key does not match the volume."));
3283         if  (r < 0)
3284                 goto out;
3285         r = 0;
3286
3287         if (crypt_use_keyring_for_vk(cd)) {
3288                 r = LUKS2_key_description_by_segment(cd, &cd->u.luks2.hdr, vk, CRYPT_DEFAULT_SEGMENT);
3289                 if (!r)
3290                         r = crypt_volume_key_load_in_keyring(cd, vk);
3291         }
3292         if  (r < 0)
3293                 goto out;
3294
3295         r = dm_resume_and_reinstate_key(cd, name, vk);
3296         if (r < 0)
3297                 log_err(cd, _("Error during resuming device %s."), name);
3298 out:
3299         if (r < 0)
3300                 crypt_drop_keyring_key(cd, vk);
3301         crypt_free_volume_key(vk);
3302         return r;
3303 }
3304
3305 /*
3306  * Keyslot manipulation
3307  */
3308 int crypt_keyslot_add_by_passphrase(struct crypt_device *cd,
3309         int keyslot, // -1 any
3310         const char *passphrase,
3311         size_t passphrase_size,
3312         const char *new_passphrase,
3313         size_t new_passphrase_size)
3314 {
3315         int digest, r, active_slots;
3316         struct luks2_keyslot_params params;
3317         struct volume_key *vk = NULL;
3318
3319         log_dbg(cd, "Adding new keyslot, existing passphrase %sprovided,"
3320                 "new passphrase %sprovided.",
3321                 passphrase ? "" : "not ", new_passphrase  ? "" : "not ");
3322
3323         if ((r = onlyLUKS(cd)))
3324                 return r;
3325
3326         if (!passphrase || !new_passphrase)
3327                 return -EINVAL;
3328
3329         r = keyslot_verify_or_find_empty(cd, &keyslot);
3330         if (r)
3331                 return r;
3332
3333         if (isLUKS1(cd->type))
3334                 active_slots = LUKS_keyslot_active_count(&cd->u.luks1.hdr);
3335         else
3336                 active_slots = LUKS2_keyslot_active_count(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
3337         if (active_slots == 0) {
3338                 /* No slots used, try to use pre-generated key in header */
3339                 if (cd->volume_key) {
3340                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
3341                         r = vk ? 0 : -ENOMEM;
3342                 } else {
3343                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided."));
3344                         return -EINVAL;
3345                 }
3346         } else if (active_slots < 0)
3347                 return -EINVAL;
3348         else {
3349                 /* Passphrase provided, use it to unlock existing keyslot */
3350                 if (isLUKS1(cd->type))
3351                         r = LUKS_open_key_with_hdr(CRYPT_ANY_SLOT, passphrase,
3352                                                    passphrase_size, &cd->u.luks1.hdr, &vk, cd);
3353                 else
3354                         r = LUKS2_keyslot_open(cd, CRYPT_ANY_SLOT, CRYPT_DEFAULT_SEGMENT, passphrase,
3355                                                 passphrase_size, &vk);
3356         }
3357
3358         if (r < 0)
3359                 goto out;
3360
3361         if (isLUKS1(cd->type))
3362                 r = LUKS_set_key(keyslot, CONST_CAST(char*)new_passphrase,
3363                                  new_passphrase_size, &cd->u.luks1.hdr, vk, cd);
3364         else {
3365                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
3366                 digest = r;
3367
3368                 if (r >= 0)
3369                         r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
3370
3371                 if (r >= 0)
3372                         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot, digest, 1, 0);
3373
3374                 if (r >= 0)
3375                         r = LUKS2_keyslot_store(cd,  &cd->u.luks2.hdr, keyslot,
3376                                                 CONST_CAST(char*)new_passphrase,
3377                                                 new_passphrase_size, vk, &params);
3378         }
3379
3380         if (r < 0)
3381                 goto out;
3382
3383         r = 0;
3384 out:
3385         crypt_free_volume_key(vk);
3386         if (r < 0) {
3387                 _luks2_reload(cd);
3388                 return r;
3389         }
3390         return keyslot;
3391 }
3392
3393 int crypt_keyslot_change_by_passphrase(struct crypt_device *cd,
3394         int keyslot_old,
3395         int keyslot_new,
3396         const char *passphrase,
3397         size_t passphrase_size,
3398         const char *new_passphrase,
3399         size_t new_passphrase_size)
3400 {
3401         int digest = -1, r;
3402         struct luks2_keyslot_params params;
3403         struct volume_key *vk = NULL;
3404
3405         if (!passphrase || !new_passphrase)
3406                 return -EINVAL;
3407
3408         log_dbg(cd, "Changing passphrase from old keyslot %d to new %d.",
3409                 keyslot_old, keyslot_new);
3410
3411         if ((r = onlyLUKS(cd)))
3412                 return r;
3413
3414         if (isLUKS1(cd->type))
3415                 r = LUKS_open_key_with_hdr(keyslot_old, passphrase, passphrase_size,
3416                                            &cd->u.luks1.hdr, &vk, cd);
3417         else if (isLUKS2(cd->type)) {
3418                 r = LUKS2_keyslot_open(cd, keyslot_old, CRYPT_ANY_SEGMENT, passphrase, passphrase_size, &vk);
3419                 /* will fail for keyslots w/o digest. fix if supported in a future */
3420                 if (r >= 0) {
3421                         digest = LUKS2_digest_by_keyslot(&cd->u.luks2.hdr, r);
3422                         if (digest < 0)
3423                                 r = -EINVAL;
3424                 }
3425         } else
3426                 r = -EINVAL;
3427         if (r < 0)
3428                 goto out;
3429
3430         if (keyslot_old != CRYPT_ANY_SLOT && keyslot_old != r) {
3431                 log_dbg(cd, "Keyslot mismatch.");
3432                 goto out;
3433         }
3434         keyslot_old = r;
3435
3436         if (keyslot_new == CRYPT_ANY_SLOT) {
3437                 if (isLUKS1(cd->type))
3438                         keyslot_new = LUKS_keyslot_find_empty(&cd->u.luks1.hdr);
3439                 else if (isLUKS2(cd->type))
3440                         keyslot_new = LUKS2_keyslot_find_empty(&cd->u.luks2.hdr);
3441                 if (keyslot_new < 0)
3442                         keyslot_new = keyslot_old;
3443         }
3444         log_dbg(cd, "Key change, old slot %d, new slot %d.", keyslot_old, keyslot_new);
3445
3446         if (isLUKS1(cd->type)) {
3447                 if (keyslot_old == keyslot_new) {
3448                         log_dbg(cd, "Key slot %d is going to be overwritten.", keyslot_old);
3449                         (void)crypt_keyslot_destroy(cd, keyslot_old);
3450                 }
3451                 r = LUKS_set_key(keyslot_new, new_passphrase, new_passphrase_size,
3452                                  &cd->u.luks1.hdr, vk, cd);
3453         } else if (isLUKS2(cd->type)) {
3454                 r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
3455                 if (r)
3456                         goto out;
3457
3458                 if (keyslot_old != keyslot_new) {
3459                         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot_new, digest, 1, 0);
3460                         if (r < 0)
3461                                 goto out;
3462                 } else {
3463                         log_dbg(cd, "Key slot %d is going to be overwritten.", keyslot_old);
3464                         /* FIXME: improve return code so that we can detect area is damaged */
3465                         r = LUKS2_keyslot_wipe(cd, &cd->u.luks2.hdr, keyslot_old, 1);
3466                         if (r) {
3467                                 /* (void)crypt_keyslot_destroy(cd, keyslot_old); */
3468                                 r = -EINVAL;
3469                                 goto out;
3470                         }
3471                 }
3472
3473                 r = LUKS2_keyslot_store(cd,  &cd->u.luks2.hdr,
3474                                         keyslot_new, new_passphrase,
3475                                         new_passphrase_size, vk, &params);
3476         } else
3477                 r = -EINVAL;
3478
3479         if (r >= 0 && keyslot_old != keyslot_new)
3480                 r = crypt_keyslot_destroy(cd, keyslot_old);
3481
3482         if (r < 0)
3483                 log_err(cd, _("Failed to swap new key slot."));
3484 out:
3485         crypt_free_volume_key(vk);
3486         if (r < 0) {
3487                 _luks2_reload(cd);
3488                 return r;
3489         }
3490         return keyslot_new;
3491 }
3492
3493 int crypt_keyslot_add_by_keyfile_device_offset(struct crypt_device *cd,
3494         int keyslot,
3495         const char *keyfile,
3496         size_t keyfile_size,
3497         uint64_t keyfile_offset,
3498         const char *new_keyfile,
3499         size_t new_keyfile_size,
3500         uint64_t new_keyfile_offset)
3501 {
3502         int digest, r, active_slots;
3503         size_t passwordLen, new_passwordLen;
3504         struct luks2_keyslot_params params;
3505         char *password = NULL, *new_password = NULL;
3506         struct volume_key *vk = NULL;
3507
3508         if (!keyfile || !new_keyfile)
3509                 return -EINVAL;
3510
3511         log_dbg(cd, "Adding new keyslot, existing keyfile %s, new keyfile %s.",
3512                 keyfile, new_keyfile);
3513
3514         if ((r = onlyLUKS(cd)))
3515                 return r;
3516
3517         r = keyslot_verify_or_find_empty(cd, &keyslot);
3518         if (r)
3519                 return r;
3520
3521         if (isLUKS1(cd->type))
3522                 active_slots = LUKS_keyslot_active_count(&cd->u.luks1.hdr);
3523         else
3524                 active_slots = LUKS2_keyslot_active_count(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
3525         if (active_slots == 0) {
3526                 /* No slots used, try to use pre-generated key in header */
3527                 if (cd->volume_key) {
3528                         vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
3529                         r = vk ? 0 : -ENOMEM;
3530                 } else {
3531                         log_err(cd, _("Cannot add key slot, all slots disabled and no volume key provided."));
3532                         return -EINVAL;
3533                 }
3534         } else {
3535                 r = crypt_keyfile_device_read(cd, keyfile,
3536                                        &password, &passwordLen,
3537                                        keyfile_offset, keyfile_size, 0);
3538                 if (r < 0)
3539                         goto out;
3540
3541                 if (isLUKS1(cd->type))
3542                         r = LUKS_open_key_with_hdr(CRYPT_ANY_SLOT, password, passwordLen,
3543                                                    &cd->u.luks1.hdr, &vk, cd);
3544                 else
3545                         r = LUKS2_keyslot_open(cd, CRYPT_ANY_SLOT, CRYPT_DEFAULT_SEGMENT, password, passwordLen, &vk);
3546         }
3547
3548         if (r < 0)
3549                 goto out;
3550
3551         r = crypt_keyfile_device_read(cd, new_keyfile,
3552                                &new_password, &new_passwordLen,
3553                                new_keyfile_offset, new_keyfile_size, 0);
3554         if (r < 0)
3555                 goto out;
3556
3557         if (isLUKS1(cd->type))
3558                 r = LUKS_set_key(keyslot, new_password, new_passwordLen,
3559                                  &cd->u.luks1.hdr, vk, cd);
3560         else {
3561                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
3562                 digest = r;
3563
3564                 if (r >= 0)
3565                         r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
3566
3567                 if (r >= 0)
3568                         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot, digest, 1, 0);
3569
3570                 if (r >= 0)
3571                         r = LUKS2_keyslot_store(cd,  &cd->u.luks2.hdr, keyslot,
3572                                                 new_password, new_passwordLen, vk, &params);
3573         }
3574 out:
3575         crypt_safe_free(password);
3576         crypt_safe_free(new_password);
3577         crypt_free_volume_key(vk);
3578         if (r < 0) {
3579                 _luks2_reload(cd);
3580                 return r;
3581         }
3582         return keyslot;
3583 }
3584
3585 int crypt_keyslot_add_by_keyfile(struct crypt_device *cd,
3586         int keyslot,
3587         const char *keyfile,
3588         size_t keyfile_size,
3589         const char *new_keyfile,
3590         size_t new_keyfile_size)
3591 {
3592         return crypt_keyslot_add_by_keyfile_device_offset(cd, keyslot,
3593                                 keyfile, keyfile_size, 0,
3594                                 new_keyfile, new_keyfile_size, 0);
3595 }
3596
3597 int crypt_keyslot_add_by_keyfile_offset(struct crypt_device *cd,
3598         int keyslot,
3599         const char *keyfile,
3600         size_t keyfile_size,
3601         size_t keyfile_offset,
3602         const char *new_keyfile,
3603         size_t new_keyfile_size,
3604         size_t new_keyfile_offset)
3605 {
3606         return crypt_keyslot_add_by_keyfile_device_offset(cd, keyslot,
3607                                 keyfile, keyfile_size, keyfile_offset,
3608                                 new_keyfile, new_keyfile_size, new_keyfile_offset);
3609 }
3610
3611 int crypt_keyslot_add_by_volume_key(struct crypt_device *cd,
3612         int keyslot,
3613         const char *volume_key,
3614         size_t volume_key_size,
3615         const char *passphrase,
3616         size_t passphrase_size)
3617 {
3618         struct volume_key *vk = NULL;
3619         int r;
3620
3621         if (!passphrase)
3622                 return -EINVAL;
3623
3624         log_dbg(cd, "Adding new keyslot %d using volume key.", keyslot);
3625
3626         if ((r = onlyLUKS(cd)))
3627                 return r;
3628
3629         if (isLUKS2(cd->type))
3630                 return crypt_keyslot_add_by_key(cd, keyslot,
3631                                 volume_key, volume_key_size, passphrase,
3632                                 passphrase_size, 0);
3633
3634         r = keyslot_verify_or_find_empty(cd, &keyslot);
3635         if (r < 0)
3636                 return r;
3637
3638         if (volume_key)
3639                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
3640         else if (cd->volume_key)
3641                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
3642
3643         if (!vk)
3644                 return -ENOMEM;
3645
3646         r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
3647         if (r < 0)
3648                 log_err(cd, _("Volume key does not match the volume."));
3649         else
3650                 r = LUKS_set_key(keyslot, passphrase, passphrase_size,
3651                         &cd->u.luks1.hdr, vk, cd);
3652
3653         crypt_free_volume_key(vk);
3654         return (r < 0) ? r : keyslot;
3655 }
3656
3657 int crypt_keyslot_destroy(struct crypt_device *cd, int keyslot)
3658 {
3659         crypt_keyslot_info ki;
3660         int r;
3661
3662         log_dbg(cd, "Destroying keyslot %d.", keyslot);
3663
3664         if ((r = _onlyLUKS(cd, CRYPT_CD_UNRESTRICTED)))
3665                 return r;
3666
3667         ki = crypt_keyslot_status(cd, keyslot);
3668         if (ki == CRYPT_SLOT_INVALID) {
3669                 log_err(cd, _("Key slot %d is invalid."), keyslot);
3670                 return -EINVAL;
3671         }
3672
3673         if (isLUKS1(cd->type)) {
3674                 if (ki == CRYPT_SLOT_INACTIVE) {
3675                         log_err(cd, _("Keyslot %d is not active."), keyslot);
3676                         return -EINVAL;
3677                 }
3678                 return LUKS_del_key(keyslot, &cd->u.luks1.hdr, cd);
3679         }
3680
3681         return LUKS2_keyslot_wipe(cd, &cd->u.luks2.hdr, keyslot, 0);
3682 }
3683
3684 static int _check_header_data_overlap(struct crypt_device *cd, const char *name)
3685 {
3686         if (!name || !isLUKS(cd->type))
3687                 return 0;
3688
3689         if (!device_is_identical(crypt_data_device(cd), crypt_metadata_device(cd)))
3690                 return 0;
3691
3692         /* FIXME: check real header size */
3693         if (crypt_get_data_offset(cd) == 0) {
3694                 log_err(cd, _("Device header overlaps with data area."));
3695                 return -EINVAL;
3696         }
3697
3698         return 0;
3699 }
3700
3701 static int check_devices(struct crypt_device *cd, const char *name, const char *iname, uint32_t *flags)
3702 {
3703         int r;
3704
3705         if (!flags || !name)
3706                 return -EINVAL;
3707
3708         if (iname) {
3709                 r = dm_status_device(cd, iname);
3710                 if (r >= 0 && !(*flags & CRYPT_ACTIVATE_REFRESH))
3711                         return -EBUSY;
3712                 if (r < 0 && r != -ENODEV)
3713                         return r;
3714                 if (r == -ENODEV)
3715                         *flags &= ~CRYPT_ACTIVATE_REFRESH;
3716         }
3717
3718         r = dm_status_device(cd, name);
3719         if (r >= 0 && !(*flags & CRYPT_ACTIVATE_REFRESH))
3720                 return -EBUSY;
3721         if (r < 0 && r != -ENODEV)
3722                 return r;
3723         if (r == -ENODEV)
3724                 *flags &= ~CRYPT_ACTIVATE_REFRESH;
3725
3726         return 0;
3727 }
3728
3729 static int _create_device_with_integrity(struct crypt_device *cd,
3730         const char *type, const char *name, const char *iname,
3731         const char *ipath, struct crypt_dm_active_device *dmd,
3732         struct crypt_dm_active_device *dmdi)
3733 {
3734         int r;
3735         enum devcheck device_check;
3736         struct dm_target *tgt;
3737         struct device *device = NULL;
3738
3739         if (!single_segment(dmd))
3740                 return -EINVAL;
3741
3742         tgt = &dmd->segment;
3743         if (tgt->type != DM_CRYPT)
3744                 return -EINVAL;
3745
3746         device_check = dmd->flags & CRYPT_ACTIVATE_SHARED ? DEV_OK : DEV_EXCL;
3747
3748         r = INTEGRITY_activate_dmd_device(cd, iname, CRYPT_INTEGRITY, dmdi, 0);
3749         if (r)
3750                 return r;
3751
3752         r = device_alloc(cd, &device, ipath);
3753         if (r < 0)
3754                 goto out;
3755         tgt->data_device = device;
3756
3757         r = device_block_adjust(cd, tgt->data_device, device_check,
3758                                 tgt->u.crypt.offset, &dmd->size, &dmd->flags);
3759
3760         if (!r)
3761                 r = dm_create_device(cd, name, type, dmd);
3762 out:
3763         if (r < 0)
3764                 dm_remove_device(cd, iname, 0);
3765
3766         device_free(cd, device);
3767         return r;
3768 }
3769
3770 static int kernel_keyring_support(void)
3771 {
3772         static unsigned _checked = 0;
3773
3774         if (!_checked) {
3775                 _kernel_keyring_supported = keyring_check();
3776                 _checked = 1;
3777         }
3778
3779         return _kernel_keyring_supported;
3780 }
3781
3782 static int dmcrypt_keyring_bug(void)
3783 {
3784         uint64_t kversion;
3785
3786         if (kernel_version(&kversion))
3787                 return 1;
3788         return kversion < version(4,15,0,0);
3789 }
3790
3791 int create_or_reload_device(struct crypt_device *cd, const char *name,
3792                      const char *type, struct crypt_dm_active_device *dmd)
3793 {
3794         int r;
3795         enum devcheck device_check;
3796         struct dm_target *tgt;
3797
3798         if (!type || !name || !single_segment(dmd))
3799                 return -EINVAL;
3800
3801         tgt = &dmd->segment;
3802         if (tgt->type != DM_CRYPT)
3803                 return -EINVAL;
3804
3805         /* drop CRYPT_ACTIVATE_REFRESH flag if any device is inactive */
3806         r = check_devices(cd, name, NULL, &dmd->flags);
3807         if (r)
3808                 return r;
3809
3810         if (dmd->flags & CRYPT_ACTIVATE_REFRESH)
3811                 r = _reload_device(cd, name, dmd);
3812         else {
3813                 device_check = dmd->flags & CRYPT_ACTIVATE_SHARED ? DEV_OK : DEV_EXCL;
3814
3815                 r = device_block_adjust(cd, tgt->data_device, device_check,
3816                                         tgt->u.crypt.offset, &dmd->size, &dmd->flags);
3817                 if (!r) {
3818                         tgt->size = dmd->size;
3819                         r = dm_create_device(cd, name, type, dmd);
3820                 }
3821         }
3822
3823         return r;
3824 }
3825
3826 int create_or_reload_device_with_integrity(struct crypt_device *cd, const char *name,
3827                      const char *type, struct crypt_dm_active_device *dmd,
3828                      struct crypt_dm_active_device *dmdi)
3829 {
3830         int r;
3831         const char *iname = NULL;
3832         char *ipath = NULL;
3833
3834         if (!type || !name || !dmd || !dmdi)
3835                 return -EINVAL;
3836
3837         if (asprintf(&ipath, "%s/%s_dif", dm_get_dir(), name) < 0)
3838                 return -ENOMEM;
3839         iname = ipath + strlen(dm_get_dir()) + 1;
3840
3841         /* drop CRYPT_ACTIVATE_REFRESH flag if any device is inactive */
3842         r = check_devices(cd, name, iname, &dmd->flags);
3843         if (r)
3844                 goto out;
3845
3846         if (dmd->flags & CRYPT_ACTIVATE_REFRESH)
3847                 r = _reload_device_with_integrity(cd, name, iname, ipath, dmd, dmdi);
3848         else
3849                 r = _create_device_with_integrity(cd, type, name, iname, ipath, dmd, dmdi);
3850 out:
3851         free(ipath);
3852
3853         return r;
3854 }
3855
3856 static int load_all_keys(struct crypt_device *cd, struct luks2_hdr *hdr, struct volume_key *vks)
3857 {
3858         int r;
3859         struct volume_key *vk = vks;
3860
3861         while (vk) {
3862                 r = LUKS2_volume_key_load_in_keyring_by_digest(cd, hdr, vk, crypt_volume_key_get_id(vk));
3863                 if (r < 0)
3864                         return r;
3865                 vk = crypt_volume_key_next(vk);
3866         }
3867
3868         return 0;
3869 }
3870
3871 /* See fixmes in _open_and_activate_luks2 */
3872 int update_reencryption_flag(struct crypt_device *cd, int enable, bool commit);
3873
3874 /* TODO: This function should 1:1 with pre-reencryption code */
3875 static int _open_and_activate(struct crypt_device *cd,
3876         int keyslot,
3877         const char *name,
3878         const char *passphrase,
3879         size_t passphrase_size,
3880         uint32_t flags)
3881 {
3882         int r;
3883         struct volume_key *vk = NULL;
3884
3885         r = LUKS2_keyslot_open(cd, keyslot,
3886                                (flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) ?
3887                                CRYPT_ANY_SEGMENT : CRYPT_DEFAULT_SEGMENT,
3888                                passphrase, passphrase_size, &vk);
3889         if (r < 0)
3890                 return r;
3891         keyslot = r;
3892
3893         if ((name || (flags & CRYPT_ACTIVATE_KEYRING_KEY)) &&
3894             crypt_use_keyring_for_vk(cd)) {
3895                 r = LUKS2_volume_key_load_in_keyring_by_keyslot(cd,
3896                                 &cd->u.luks2.hdr, vk, keyslot);
3897                 if (r < 0)
3898                         goto out;
3899                 flags |= CRYPT_ACTIVATE_KEYRING_KEY;
3900         }
3901
3902         if (name)
3903                 r = LUKS2_activate(cd, name, vk, flags);
3904 out:
3905         if (r < 0)
3906                 crypt_drop_keyring_key(cd, vk);
3907         crypt_free_volume_key(vk);
3908
3909         return r < 0 ? r : keyslot;
3910 }
3911
3912 static int _open_all_keys(struct crypt_device *cd,
3913         struct luks2_hdr *hdr,
3914         int keyslot,
3915         const char *passphrase,
3916         size_t passphrase_size,
3917         uint32_t flags,
3918         struct volume_key **vks)
3919 {
3920         int r, segment;
3921         struct volume_key *_vks = NULL;
3922         crypt_reencrypt_info ri = LUKS2_reenc_status(hdr);
3923
3924         segment = (flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) ? CRYPT_ANY_SEGMENT : CRYPT_DEFAULT_SEGMENT;
3925
3926         switch (ri) {
3927         case CRYPT_REENCRYPT_NONE:
3928                 r = LUKS2_keyslot_open(cd, keyslot, segment, passphrase, passphrase_size, &_vks);
3929                 break;
3930         case CRYPT_REENCRYPT_CLEAN:
3931         case CRYPT_REENCRYPT_CRASH:
3932                 if (segment == CRYPT_ANY_SEGMENT)
3933                         r = LUKS2_keyslot_open(cd, keyslot, segment, passphrase,
3934                                                passphrase_size, &_vks);
3935                 else
3936                         r = LUKS2_keyslot_open_all_segments(cd, keyslot,
3937                                         keyslot, passphrase, passphrase_size,
3938                                         &_vks);
3939                 break;
3940         default:
3941                 r = -EINVAL;
3942         }
3943
3944         if (keyslot == CRYPT_ANY_SLOT)
3945                 keyslot = r;
3946
3947         if (r >= 0 && (flags & CRYPT_ACTIVATE_KEYRING_KEY))
3948                 r = load_all_keys(cd, hdr, _vks);
3949
3950         if (r >= 0 && vks)
3951                 MOVE_REF(*vks, _vks);
3952
3953         if (r < 0)
3954                 crypt_drop_keyring_key(cd, _vks);
3955         crypt_free_volume_key(_vks);
3956
3957         return r < 0 ? r : keyslot;
3958 }
3959
3960 static int _open_and_activate_reencrypt_device(struct crypt_device *cd,
3961         struct luks2_hdr *hdr,
3962         int keyslot,
3963         const char *name,
3964         const char *passphrase,
3965         size_t passphrase_size,
3966         uint32_t flags)
3967 {
3968         bool dynamic_size;
3969         crypt_reencrypt_info ri;
3970         uint64_t minimal_size, device_size;
3971         struct volume_key *vks = NULL;
3972         int r = 0;
3973         struct crypt_lock_handle *reencrypt_lock = NULL;
3974
3975         if (crypt_use_keyring_for_vk(cd))
3976                 flags |= CRYPT_ACTIVATE_KEYRING_KEY;
3977
3978         r = crypt_reencrypt_lock(cd, &reencrypt_lock);
3979         if (r) {
3980                 if (r == -EBUSY)
3981                         log_err(cd, _("Reencryption in-progress. Cannot activate device."));
3982                 else
3983                         log_err(cd, _("Failed to get reencryption lock."));
3984                 return r;
3985         }
3986
3987         if ((r = crypt_load(cd, CRYPT_LUKS2, NULL)))
3988                 goto err;
3989
3990         ri = LUKS2_reenc_status(hdr);
3991
3992         if (ri == CRYPT_REENCRYPT_CRASH) {
3993                 r = LUKS2_reencrypt_locked_recovery_by_passphrase(cd, keyslot,
3994                                 keyslot, passphrase, passphrase_size, flags, &vks);
3995                 if (r < 0) {
3996                         log_err(cd, _("LUKS2 reencryption recovery failed."));
3997                         goto err;
3998                 }
3999                 keyslot = r;
4000
4001                 ri = LUKS2_reenc_status(hdr);
4002         }
4003
4004         /* recovery finished reencryption or it's already finished */
4005         if (ri == CRYPT_REENCRYPT_NONE) {
4006                 crypt_drop_keyring_key(cd, vks);
4007                 crypt_free_volume_key(vks);
4008                 crypt_reencrypt_unlock(cd, reencrypt_lock);
4009                 return _open_and_activate(cd, keyslot, name, passphrase, passphrase_size, flags);
4010         }
4011
4012         if (ri > CRYPT_REENCRYPT_CLEAN) {
4013                 r = -EINVAL;
4014                 goto err;
4015         }
4016
4017         if (LUKS2_get_data_size(hdr, &minimal_size, &dynamic_size))
4018                 goto err;
4019
4020         if (!vks) {
4021                 r = _open_all_keys(cd, hdr, keyslot, passphrase, passphrase_size, flags, &vks);
4022                 if (r >= 0)
4023                         keyslot = r;
4024         }
4025
4026         log_dbg(cd, "Entering clean reencryption state mode.");
4027
4028         if (r >= 0)
4029                 r = luks2_check_device_size(cd, hdr, minimal_size, &device_size, true, dynamic_size);
4030
4031         if (r >= 0)
4032                 r = LUKS2_activate_multi(cd, name, vks, device_size >> SECTOR_SHIFT, flags);
4033 err:
4034         crypt_reencrypt_unlock(cd, reencrypt_lock);
4035         if (r < 0)
4036                 crypt_drop_keyring_key(cd, vks);
4037         crypt_free_volume_key(vks);
4038
4039         return r < 0 ? r : keyslot;
4040 }
4041
4042 /*
4043  * Activation/deactivation of a device
4044  */
4045 static int _open_and_activate_luks2(struct crypt_device *cd,
4046         int keyslot,
4047         const char *name,
4048         const char *passphrase,
4049         size_t passphrase_size,
4050         uint32_t flags)
4051 {
4052         crypt_reencrypt_info ri;
4053         int r;
4054         struct luks2_hdr *hdr = &cd->u.luks2.hdr;
4055
4056         ri = LUKS2_reenc_status(hdr);
4057         if (ri == CRYPT_REENCRYPT_INVALID)
4058                 return -EINVAL;
4059
4060         if (ri > CRYPT_REENCRYPT_NONE) {
4061                 if (name)
4062                         r = _open_and_activate_reencrypt_device(cd, hdr, keyslot, name, passphrase,
4063                                         passphrase_size, flags);
4064                 else
4065                         r = _open_all_keys(cd, hdr, keyslot, passphrase,
4066                                            passphrase_size, flags, NULL);
4067         } else
4068                 r = _open_and_activate(cd, keyslot, name, passphrase,
4069                                 passphrase_size, flags);
4070
4071         return r;
4072 }
4073
4074 static int _activate_by_passphrase(struct crypt_device *cd,
4075         const char *name,
4076         int keyslot,
4077         const char *passphrase,
4078         size_t passphrase_size,
4079         uint32_t flags)
4080 {
4081         int r;
4082         struct volume_key *vk = NULL;
4083
4084         if ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd))
4085                 return -EINVAL;
4086
4087         if ((flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) && name)
4088                 return -EINVAL;
4089
4090         r = _check_header_data_overlap(cd, name);
4091         if (r < 0)
4092                 return r;
4093
4094         if (flags & CRYPT_ACTIVATE_SERIALIZE_MEMORY_HARD_PBKDF)
4095                 cd->memory_hard_pbkdf_lock_enabled = true;
4096
4097         /* plain, use hashed passphrase */
4098         if (isPLAIN(cd->type)) {
4099                 r = -EINVAL;
4100                 if (!name)
4101                         goto out;
4102
4103                 r = process_key(cd, cd->u.plain.hdr.hash,
4104                                 cd->u.plain.key_size,
4105                                 passphrase, passphrase_size, &vk);
4106                 if (r < 0)
4107                         goto out;
4108
4109                 r = PLAIN_activate(cd, name, vk, cd->u.plain.hdr.size, flags);
4110                 keyslot = 0;
4111         } else if (isLUKS1(cd->type)) {
4112                 r = LUKS_open_key_with_hdr(keyslot, passphrase,
4113                                            passphrase_size, &cd->u.luks1.hdr, &vk, cd);
4114                 if (r >= 0) {
4115                         keyslot = r;
4116                         if (name)
4117                                 r = LUKS1_activate(cd, name, vk, flags);
4118                 }
4119         } else if (isLUKS2(cd->type)) {
4120                 r = _open_and_activate_luks2(cd, keyslot, name, passphrase, passphrase_size, flags);
4121                 keyslot = r;
4122         } else if (isBITLK(cd->type)) {
4123                 r = BITLK_activate(cd, name, passphrase, passphrase_size,
4124                                    &cd->u.bitlk.params, flags);
4125                 keyslot = 0;
4126         } else {
4127                 log_err(cd, _("Device type is not properly initialized."));
4128                 r = -EINVAL;
4129         }
4130 out:
4131         if (r < 0)
4132                 crypt_drop_keyring_key(cd, vk);
4133         crypt_free_volume_key(vk);
4134
4135         cd->memory_hard_pbkdf_lock_enabled = false;
4136
4137         return r < 0 ? r : keyslot;
4138 }
4139
4140 static int _activate_loopaes(struct crypt_device *cd,
4141         const char *name,
4142         char *buffer,
4143         size_t buffer_size,
4144         uint32_t flags)
4145 {
4146         int r;
4147         unsigned int key_count = 0;
4148         struct volume_key *vk = NULL;
4149
4150         r = LOOPAES_parse_keyfile(cd, &vk, cd->u.loopaes.hdr.hash, &key_count,
4151                                   buffer, buffer_size);
4152
4153         if (!r && name)
4154                 r = LOOPAES_activate(cd, name, cd->u.loopaes.cipher, key_count,
4155                                      vk, flags);
4156
4157         crypt_free_volume_key(vk);
4158
4159         return r;
4160 }
4161
4162 static int _activate_check_status(struct crypt_device *cd, const char *name, unsigned reload)
4163 {
4164         crypt_status_info ci;
4165
4166         if (!name)
4167                 return 0;
4168
4169         ci = crypt_status(cd, name);
4170         if (ci == CRYPT_INVALID) {
4171                 log_err(cd, _("Cannot use device %s, name is invalid or still in use."), name);
4172                 return -EINVAL;
4173         } else if (ci >= CRYPT_ACTIVE && !reload) {
4174                 log_err(cd, _("Device %s already exists."), name);
4175                 return -EEXIST;
4176         }
4177
4178         return 0;
4179 }
4180
4181 // activation/deactivation of device mapping
4182 int crypt_activate_by_passphrase(struct crypt_device *cd,
4183         const char *name,
4184         int keyslot,
4185         const char *passphrase,
4186         size_t passphrase_size,
4187         uint32_t flags)
4188 {
4189         int r;
4190
4191         if (!cd || !passphrase || (!name && (flags & CRYPT_ACTIVATE_REFRESH)))
4192                 return -EINVAL;
4193
4194         log_dbg(cd, "%s volume %s [keyslot %d] using passphrase.",
4195                 name ? "Activating" : "Checking", name ?: "passphrase",
4196                 keyslot);
4197
4198         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4199         if (r < 0)
4200                 return r;
4201
4202         return _activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
4203 }
4204
4205 int crypt_activate_by_keyfile_device_offset(struct crypt_device *cd,
4206         const char *name,
4207         int keyslot,
4208         const char *keyfile,
4209         size_t keyfile_size,
4210         uint64_t keyfile_offset,
4211         uint32_t flags)
4212 {
4213         char *passphrase_read = NULL;
4214         size_t passphrase_size_read;
4215         int r;
4216
4217         if (!cd || !keyfile ||
4218             ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd)))
4219                 return -EINVAL;
4220
4221         log_dbg(cd, "%s volume %s [keyslot %d] using keyfile %s.",
4222                 name ? "Activating" : "Checking", name ?: "passphrase", keyslot, keyfile);
4223
4224         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4225         if (r < 0)
4226                 return r;
4227
4228         r = crypt_keyfile_device_read(cd, keyfile,
4229                                 &passphrase_read, &passphrase_size_read,
4230                                 keyfile_offset, keyfile_size, 0);
4231         if (r < 0)
4232                 goto out;
4233
4234         if (isLOOPAES(cd->type))
4235                 r = _activate_loopaes(cd, name, passphrase_read, passphrase_size_read, flags);
4236         else
4237                 r = _activate_by_passphrase(cd, name, keyslot, passphrase_read, passphrase_size_read, flags);
4238
4239 out:
4240         crypt_safe_free(passphrase_read);
4241         return r;
4242 }
4243
4244 int crypt_activate_by_keyfile(struct crypt_device *cd,
4245         const char *name,
4246         int keyslot,
4247         const char *keyfile,
4248         size_t keyfile_size,
4249         uint32_t flags)
4250 {
4251         return crypt_activate_by_keyfile_device_offset(cd, name, keyslot, keyfile,
4252                                         keyfile_size, 0, flags);
4253 }
4254
4255 int crypt_activate_by_keyfile_offset(struct crypt_device *cd,
4256         const char *name,
4257         int keyslot,
4258         const char *keyfile,
4259         size_t keyfile_size,
4260         size_t keyfile_offset,
4261         uint32_t flags)
4262 {
4263         return crypt_activate_by_keyfile_device_offset(cd, name, keyslot, keyfile,
4264                                         keyfile_size, keyfile_offset, flags);
4265 }
4266 int crypt_activate_by_volume_key(struct crypt_device *cd,
4267         const char *name,
4268         const char *volume_key,
4269         size_t volume_key_size,
4270         uint32_t flags)
4271 {
4272         struct volume_key *vk = NULL;
4273         int r;
4274
4275         if (!cd ||
4276             ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd)))
4277                 return -EINVAL;
4278
4279         log_dbg(cd, "%s volume %s by volume key.", name ? "Activating" : "Checking",
4280                 name ?: "");
4281
4282         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4283         if (r < 0)
4284                 return r;
4285
4286         r = _check_header_data_overlap(cd, name);
4287         if (r < 0)
4288                 return r;
4289
4290         /* use key directly, no hash */
4291         if (isPLAIN(cd->type)) {
4292                 if (!name)
4293                         return -EINVAL;
4294
4295                 if (!volume_key || !volume_key_size || volume_key_size != cd->u.plain.key_size) {
4296                         log_err(cd, _("Incorrect volume key specified for plain device."));
4297                         return -EINVAL;
4298                 }
4299
4300                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4301                 if (!vk)
4302                         return -ENOMEM;
4303
4304                 r = PLAIN_activate(cd, name, vk, cd->u.plain.hdr.size, flags);
4305         } else if (isLUKS1(cd->type)) {
4306                 /* If key is not provided, try to use internal key */
4307                 if (!volume_key) {
4308                         if (!cd->volume_key) {
4309                                 log_err(cd, _("Volume key does not match the volume."));
4310                                 return -EINVAL;
4311                         }
4312                         volume_key_size = cd->volume_key->keylength;
4313                         volume_key = cd->volume_key->key;
4314                 }
4315
4316                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4317                 if (!vk)
4318                         return -ENOMEM;
4319                 r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
4320
4321                 if (r == -EPERM)
4322                         log_err(cd, _("Volume key does not match the volume."));
4323
4324                 if (!r && name)
4325                         r = LUKS1_activate(cd, name, vk, flags);
4326         } else if (isLUKS2(cd->type)) {
4327                 /* If key is not provided, try to use internal key */
4328                 if (!volume_key) {
4329                         if (!cd->volume_key) {
4330                                 log_err(cd, _("Volume key does not match the volume."));
4331                                 return -EINVAL;
4332                         }
4333                         volume_key_size = cd->volume_key->keylength;
4334                         volume_key = cd->volume_key->key;
4335                 }
4336
4337                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4338                 if (!vk)
4339                         return -ENOMEM;
4340
4341                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
4342                 if (r == -EPERM || r == -ENOENT)
4343                         log_err(cd, _("Volume key does not match the volume."));
4344                 if (r > 0)
4345                         r = 0;
4346
4347                 if (!r && (name || (flags & CRYPT_ACTIVATE_KEYRING_KEY)) &&
4348                     crypt_use_keyring_for_vk(cd)) {
4349                         r = LUKS2_key_description_by_segment(cd,
4350                                 &cd->u.luks2.hdr, vk, CRYPT_DEFAULT_SEGMENT);
4351                         if (!r)
4352                                 r = crypt_volume_key_load_in_keyring(cd, vk);
4353                         if (!r)
4354                                 flags |= CRYPT_ACTIVATE_KEYRING_KEY;
4355                 }
4356
4357                 if (!r && name)
4358                         r = LUKS2_activate(cd, name, vk, flags);
4359         } else if (isVERITY(cd->type)) {
4360                 r = crypt_activate_by_signed_key(cd, name, volume_key, volume_key_size, NULL, 0, flags);
4361         } else if (isTCRYPT(cd->type)) {
4362                 if (!name)
4363                         return 0;
4364                 r = TCRYPT_activate(cd, name, &cd->u.tcrypt.hdr,
4365                                     &cd->u.tcrypt.params, flags);
4366         } else if (isINTEGRITY(cd->type)) {
4367                 if (!name)
4368                         return 0;
4369                 if (volume_key) {
4370                         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4371                         if (!vk)
4372                                 return -ENOMEM;
4373                 }
4374                 r = INTEGRITY_activate(cd, name, &cd->u.integrity.params, vk,
4375                                        cd->u.integrity.journal_crypt_key,
4376                                        cd->u.integrity.journal_mac_key, flags,
4377                                        cd->u.integrity.sb_flags);
4378         } else {
4379                 log_err(cd, _("Device type is not properly initialized."));
4380                 r = -EINVAL;
4381         }
4382
4383         if (r < 0)
4384                 crypt_drop_keyring_key(cd, vk);
4385         crypt_free_volume_key(vk);
4386
4387         return r;
4388 }
4389
4390 int crypt_activate_by_signed_key(struct crypt_device *cd,
4391         const char *name,
4392         const char *volume_key,
4393         size_t volume_key_size,
4394         const char *signature,
4395         size_t signature_size,
4396         uint32_t flags)
4397 {
4398         char description[512];
4399         int r;
4400
4401         if (!cd || !isVERITY(cd->type))
4402                 return -EINVAL;
4403
4404         if (!volume_key || !volume_key_size || (!name && signature)) {
4405                 log_err(cd, _("Incorrect root hash specified for verity device."));
4406                 return -EINVAL;
4407         }
4408
4409         log_dbg(cd, "%s volume %s by signed key.", name ? "Activating" : "Checking", name ?: "");
4410
4411         if (cd->u.verity.hdr.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE && !signature) {
4412                 log_err(cd, _("Root hash signature required."));
4413                 return -EINVAL;
4414         }
4415
4416         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
4417         if (r < 0)
4418                 return r;
4419
4420         if (signature && !kernel_keyring_support()) {
4421                 log_err(cd, _("Kernel keyring missing: required for passing signature to kernel."));
4422                 return -EINVAL;
4423         }
4424
4425         /* volume_key == root hash */
4426         free(CONST_CAST(void*)cd->u.verity.root_hash);
4427         cd->u.verity.root_hash = NULL;
4428
4429         if (signature) {
4430                 r = snprintf(description, sizeof(description)-1, "cryptsetup:%s%s%s",
4431                              crypt_get_uuid(cd) ?: "", crypt_get_uuid(cd) ? "-" : "", name);
4432                 if (r < 0)
4433                         return -EINVAL;
4434
4435                 log_dbg(cd, "Adding signature into keyring %s", description);
4436                 r = keyring_add_key_in_thread_keyring(USER_KEY, description, signature, signature_size);
4437                 if (r) {
4438                         log_err(cd, _("Failed to load key in kernel keyring."));
4439                         return r;
4440                 }
4441         }
4442
4443         r = VERITY_activate(cd, name, volume_key, volume_key_size,
4444                             signature ? description : NULL,
4445                             cd->u.verity.fec_device,
4446                             &cd->u.verity.hdr, flags | CRYPT_ACTIVATE_READONLY);
4447
4448         if (!r) {
4449                 cd->u.verity.root_hash_size = volume_key_size;
4450                 cd->u.verity.root_hash = malloc(volume_key_size);
4451                 if (cd->u.verity.root_hash)
4452                         memcpy(CONST_CAST(void*)cd->u.verity.root_hash, volume_key, volume_key_size);
4453         }
4454
4455         if (signature)
4456                 crypt_drop_keyring_key_by_description(cd, description, USER_KEY);
4457
4458         return r;
4459 }
4460
4461 int crypt_deactivate_by_name(struct crypt_device *cd, const char *name, uint32_t flags)
4462 {
4463         struct crypt_device *fake_cd = NULL;
4464         struct luks2_hdr *hdr2 = NULL;
4465         struct crypt_dm_active_device dmd = {};
4466         int r;
4467         uint32_t get_flags = DM_ACTIVE_DEVICE | DM_ACTIVE_UUID | DM_ACTIVE_HOLDERS;
4468
4469         if (!name)
4470                 return -EINVAL;
4471
4472         log_dbg(cd, "Deactivating volume %s.", name);
4473
4474         if (!cd) {
4475                 r = crypt_init_by_name(&fake_cd, name);
4476                 if (r < 0)
4477                         return r;
4478                 cd = fake_cd;
4479         }
4480
4481         /* skip holders detection and early abort when some flags raised */
4482         if (flags & (CRYPT_DEACTIVATE_FORCE | CRYPT_DEACTIVATE_DEFERRED))
4483                 get_flags &= ~DM_ACTIVE_HOLDERS;
4484
4485         switch (crypt_status(cd, name)) {
4486                 case CRYPT_ACTIVE:
4487                 case CRYPT_BUSY:
4488                         r = dm_query_device(cd, name, get_flags, &dmd);
4489                         if (r >= 0) {
4490                                 if (dmd.holders) {
4491                                         log_err(cd, _("Device %s is still in use."), name);
4492                                         r = -EBUSY;
4493                                         break;
4494                                 }
4495                         }
4496
4497                         if (isLUKS2(cd->type))
4498                                 hdr2 = crypt_get_hdr(cd, CRYPT_LUKS2);
4499
4500                         if ((dmd.uuid && !strncmp(CRYPT_LUKS2, dmd.uuid, sizeof(CRYPT_LUKS2)-1)) || hdr2)
4501                                 r = LUKS2_deactivate(cd, name, hdr2, &dmd, flags);
4502                         else if (isTCRYPT(cd->type))
4503                                 r = TCRYPT_deactivate(cd, name, flags);
4504                         else
4505                                 r = dm_remove_device(cd, name, flags);
4506                         if (r < 0 && crypt_status(cd, name) == CRYPT_BUSY) {
4507                                 log_err(cd, _("Device %s is still in use."), name);
4508                                 r = -EBUSY;
4509                         }
4510                         break;
4511                 case CRYPT_INACTIVE:
4512                         log_err(cd, _("Device %s is not active."), name);
4513                         r = -ENODEV;
4514                         break;
4515                 default:
4516                         log_err(cd, _("Invalid device %s."), name);
4517                         r = -EINVAL;
4518         }
4519
4520         dm_targets_free(cd, &dmd);
4521         free(CONST_CAST(void*)dmd.uuid);
4522         crypt_free(fake_cd);
4523
4524         return r;
4525 }
4526
4527 int crypt_deactivate(struct crypt_device *cd, const char *name)
4528 {
4529         return crypt_deactivate_by_name(cd, name, 0);
4530 }
4531
4532 int crypt_get_active_device(struct crypt_device *cd, const char *name,
4533                             struct crypt_active_device *cad)
4534 {
4535         int r;
4536         struct crypt_dm_active_device dmd, dmdi = {};
4537         const char *namei = NULL;
4538         struct dm_target *tgt = &dmd.segment;
4539         uint64_t min_offset = UINT64_MAX;
4540
4541         if (!cd || !name || !cad)
4542                 return -EINVAL;
4543
4544         r = dm_query_device(cd, name, DM_ACTIVE_DEVICE, &dmd);
4545         if (r < 0)
4546                 return r;
4547
4548         /* For LUKS2 with integrity we need flags from underlying dm-integrity */
4549         if (isLUKS2(cd->type) && crypt_get_integrity_tag_size(cd) && single_segment(&dmd)) {
4550                 namei = device_dm_name(tgt->data_device);
4551                 if (namei && dm_query_device(cd, namei, 0, &dmdi) >= 0)
4552                         dmd.flags |= dmdi.flags;
4553         }
4554
4555         if (cd && isTCRYPT(cd->type)) {
4556                 cad->offset     = TCRYPT_get_data_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
4557                 cad->iv_offset  = TCRYPT_get_iv_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
4558         } else {
4559                 while (tgt) {
4560                         if (tgt->type == DM_CRYPT && (min_offset > tgt->u.crypt.offset)) {
4561                                 min_offset = tgt->u.crypt.offset;
4562                                 cad->iv_offset = tgt->u.crypt.iv_offset;
4563                         } else if (tgt->type == DM_INTEGRITY && (min_offset > tgt->u.integrity.offset)) {
4564                                 min_offset = tgt->u.integrity.offset;
4565                                 cad->iv_offset = 0;
4566                         } else if (tgt->type == DM_LINEAR && (min_offset > tgt->u.linear.offset)) {
4567                                 min_offset = tgt->u.linear.offset;
4568                                 cad->iv_offset = 0;
4569                         }
4570                         tgt = tgt->next;
4571                 }
4572         }
4573
4574         if (min_offset != UINT64_MAX)
4575                 cad->offset = min_offset;
4576
4577         cad->size       = dmd.size;
4578         cad->flags      = dmd.flags;
4579
4580         r = 0;
4581         dm_targets_free(cd, &dmd);
4582         dm_targets_free(cd, &dmdi);
4583
4584         return r;
4585 }
4586
4587 uint64_t crypt_get_active_integrity_failures(struct crypt_device *cd, const char *name)
4588 {
4589         struct crypt_dm_active_device dmd;
4590         uint64_t failures = 0;
4591
4592         if (!name)
4593                 return 0;
4594
4595         /* FIXME: LUKS2 / dm-crypt does not provide this count. */
4596         if (dm_query_device(cd, name, 0, &dmd) < 0)
4597                 return 0;
4598
4599         if (single_segment(&dmd) && dmd.segment.type == DM_INTEGRITY)
4600                 (void)dm_status_integrity_failures(cd, name, &failures);
4601
4602         dm_targets_free(cd, &dmd);
4603
4604         return failures;
4605 }
4606
4607 /*
4608  * Volume key handling
4609  */
4610 int crypt_volume_key_get(struct crypt_device *cd,
4611         int keyslot,
4612         char *volume_key,
4613         size_t *volume_key_size,
4614         const char *passphrase,
4615         size_t passphrase_size)
4616 {
4617         struct volume_key *vk = NULL;
4618         int key_len, r = -EINVAL;
4619
4620         if (!cd || !volume_key || !volume_key_size || (!isTCRYPT(cd->type) && !isVERITY(cd->type) && !passphrase))
4621                 return -EINVAL;
4622
4623         if (isLUKS2(cd->type) && keyslot != CRYPT_ANY_SLOT)
4624                 key_len = LUKS2_get_keyslot_stored_key_size(&cd->u.luks2.hdr, keyslot);
4625         else
4626                 key_len = crypt_get_volume_key_size(cd);
4627
4628         if (key_len < 0)
4629                 return -EINVAL;
4630
4631         if (key_len > (int)*volume_key_size) {
4632                 log_err(cd, _("Volume key buffer too small."));
4633                 return -ENOMEM;
4634         }
4635
4636         if (isPLAIN(cd->type) && cd->u.plain.hdr.hash) {
4637                 r = process_key(cd, cd->u.plain.hdr.hash, key_len,
4638                                 passphrase, passphrase_size, &vk);
4639                 if (r < 0)
4640                         log_err(cd, _("Cannot retrieve volume key for plain device."));
4641         } else if (isLUKS1(cd->type)) {
4642                 r = LUKS_open_key_with_hdr(keyslot, passphrase,
4643                                         passphrase_size, &cd->u.luks1.hdr, &vk, cd);
4644         } else if (isLUKS2(cd->type)) {
4645                 r = LUKS2_keyslot_open(cd, keyslot,
4646                                 keyslot == CRYPT_ANY_SLOT ? CRYPT_DEFAULT_SEGMENT : CRYPT_ANY_SEGMENT,
4647                                 passphrase, passphrase_size, &vk);
4648         } else if (isTCRYPT(cd->type)) {
4649                 r = TCRYPT_get_volume_key(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params, &vk);
4650         } else if (isVERITY(cd->type)) {
4651                 /* volume_key == root hash */
4652                 if (cd->u.verity.root_hash) {
4653                         memcpy(volume_key, cd->u.verity.root_hash, cd->u.verity.root_hash_size);
4654                         *volume_key_size = cd->u.verity.root_hash_size;
4655                         r = 0;
4656                 } else
4657                         log_err(cd, _("Cannot retrieve root hash for verity device."));
4658         } else
4659                 log_err(cd, _("This operation is not supported for %s crypt device."), cd->type ?: "(none)");
4660
4661         if (r >= 0 && vk) {
4662                 memcpy(volume_key, vk->key, vk->keylength);
4663                 *volume_key_size = vk->keylength;
4664         }
4665
4666         crypt_free_volume_key(vk);
4667         return r;
4668 }
4669
4670 int crypt_volume_key_verify(struct crypt_device *cd,
4671         const char *volume_key,
4672         size_t volume_key_size)
4673 {
4674         struct volume_key *vk;
4675         int r;
4676
4677         if ((r = _onlyLUKS(cd, CRYPT_CD_UNRESTRICTED)))
4678                 return r;
4679
4680         vk = crypt_alloc_volume_key(volume_key_size, volume_key);
4681         if (!vk)
4682                 return -ENOMEM;
4683
4684         if (isLUKS1(cd->type))
4685                 r = LUKS_verify_volume_key(&cd->u.luks1.hdr, vk);
4686         else if (isLUKS2(cd->type))
4687                 r = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
4688         else
4689                 r = -EINVAL;
4690
4691
4692         if (r == -EPERM)
4693                 log_err(cd, _("Volume key does not match the volume."));
4694
4695         crypt_free_volume_key(vk);
4696
4697         return r >= 0 ? 0 : r;
4698 }
4699
4700 /*
4701  * RNG and memory locking
4702  */
4703 void crypt_set_rng_type(struct crypt_device *cd, int rng_type)
4704 {
4705         if (!cd)
4706                 return;
4707
4708         switch (rng_type) {
4709         case CRYPT_RNG_URANDOM:
4710         case CRYPT_RNG_RANDOM:
4711                 log_dbg(cd, "RNG set to %d (%s).", rng_type, rng_type ? "random" : "urandom");
4712                 cd->rng_type = rng_type;
4713         }
4714 }
4715
4716 int crypt_get_rng_type(struct crypt_device *cd)
4717 {
4718         if (!cd)
4719                 return -EINVAL;
4720
4721         return cd->rng_type;
4722 }
4723
4724 int crypt_memory_lock(struct crypt_device *cd, int lock)
4725 {
4726         return lock ? crypt_memlock_inc(cd) : crypt_memlock_dec(cd);
4727 }
4728
4729 void crypt_set_compatibility(struct crypt_device *cd, uint32_t flags)
4730 {
4731         if (cd)
4732                 cd->compatibility = flags;
4733 }
4734
4735 uint32_t crypt_get_compatibility(struct crypt_device *cd)
4736 {
4737         if (cd)
4738                 return cd->compatibility;
4739
4740         return 0;
4741 }
4742
4743 /*
4744  * Reporting
4745  */
4746 crypt_status_info crypt_status(struct crypt_device *cd, const char *name)
4747 {
4748         int r;
4749
4750         if (!name)
4751                 return CRYPT_INVALID;
4752
4753         if (!cd)
4754                 dm_backend_init(cd);
4755
4756         r = dm_status_device(cd, name);
4757
4758         if (!cd)
4759                 dm_backend_exit(cd);
4760
4761         if (r < 0 && r != -ENODEV)
4762                 return CRYPT_INVALID;
4763
4764         if (r == 0)
4765                 return CRYPT_ACTIVE;
4766
4767         if (r > 0)
4768                 return CRYPT_BUSY;
4769
4770         return CRYPT_INACTIVE;
4771 }
4772
4773 static void hexprint(struct crypt_device *cd, const char *d, int n, const char *sep)
4774 {
4775         int i;
4776         for(i = 0; i < n; i++)
4777                 log_std(cd, "%02hhx%s", (const char)d[i], sep);
4778 }
4779
4780 static int _luks_dump(struct crypt_device *cd)
4781 {
4782         int i;
4783
4784         log_std(cd, "LUKS header information for %s\n\n", mdata_device_path(cd));
4785         log_std(cd, "Version:       \t%" PRIu16 "\n", cd->u.luks1.hdr.version);
4786         log_std(cd, "Cipher name:   \t%s\n", cd->u.luks1.hdr.cipherName);
4787         log_std(cd, "Cipher mode:   \t%s\n", cd->u.luks1.hdr.cipherMode);
4788         log_std(cd, "Hash spec:     \t%s\n", cd->u.luks1.hdr.hashSpec);
4789         log_std(cd, "Payload offset:\t%" PRIu32 "\n", cd->u.luks1.hdr.payloadOffset);
4790         log_std(cd, "MK bits:       \t%" PRIu32 "\n", cd->u.luks1.hdr.keyBytes * 8);
4791         log_std(cd, "MK digest:     \t");
4792         hexprint(cd, cd->u.luks1.hdr.mkDigest, LUKS_DIGESTSIZE, " ");
4793         log_std(cd, "\n");
4794         log_std(cd, "MK salt:       \t");
4795         hexprint(cd, cd->u.luks1.hdr.mkDigestSalt, LUKS_SALTSIZE/2, " ");
4796         log_std(cd, "\n               \t");
4797         hexprint(cd, cd->u.luks1.hdr.mkDigestSalt+LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
4798         log_std(cd, "\n");
4799         log_std(cd, "MK iterations: \t%" PRIu32 "\n", cd->u.luks1.hdr.mkDigestIterations);
4800         log_std(cd, "UUID:          \t%s\n\n", cd->u.luks1.hdr.uuid);
4801         for(i = 0; i < LUKS_NUMKEYS; i++) {
4802                 if(cd->u.luks1.hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
4803                         log_std(cd, "Key Slot %d: ENABLED\n",i);
4804                         log_std(cd, "\tIterations:         \t%" PRIu32 "\n",
4805                                 cd->u.luks1.hdr.keyblock[i].passwordIterations);
4806                         log_std(cd, "\tSalt:               \t");
4807                         hexprint(cd, cd->u.luks1.hdr.keyblock[i].passwordSalt,
4808                                  LUKS_SALTSIZE/2, " ");
4809                         log_std(cd, "\n\t                      \t");
4810                         hexprint(cd, cd->u.luks1.hdr.keyblock[i].passwordSalt +
4811                                  LUKS_SALTSIZE/2, LUKS_SALTSIZE/2, " ");
4812                         log_std(cd, "\n");
4813
4814                         log_std(cd, "\tKey material offset:\t%" PRIu32 "\n",
4815                                 cd->u.luks1.hdr.keyblock[i].keyMaterialOffset);
4816                         log_std(cd, "\tAF stripes:            \t%" PRIu32 "\n",
4817                                 cd->u.luks1.hdr.keyblock[i].stripes);
4818                 }
4819                 else
4820                         log_std(cd, "Key Slot %d: DISABLED\n", i);
4821         }
4822         return 0;
4823 }
4824
4825 static int _verity_dump(struct crypt_device *cd)
4826 {
4827         log_std(cd, "VERITY header information for %s\n", mdata_device_path(cd));
4828         log_std(cd, "UUID:            \t%s\n", cd->u.verity.uuid ?: "");
4829         log_std(cd, "Hash type:       \t%u\n", cd->u.verity.hdr.hash_type);
4830         log_std(cd, "Data blocks:     \t%" PRIu64 "\n", cd->u.verity.hdr.data_size);
4831         log_std(cd, "Data block size: \t%u\n", cd->u.verity.hdr.data_block_size);
4832         log_std(cd, "Hash block size: \t%u\n", cd->u.verity.hdr.hash_block_size);
4833         log_std(cd, "Hash algorithm:  \t%s\n", cd->u.verity.hdr.hash_name);
4834         log_std(cd, "Salt:            \t");
4835         if (cd->u.verity.hdr.salt_size)
4836                 hexprint(cd, cd->u.verity.hdr.salt, cd->u.verity.hdr.salt_size, "");
4837         else
4838                 log_std(cd, "-");
4839         log_std(cd, "\n");
4840         if (cd->u.verity.root_hash) {
4841                 log_std(cd, "Root hash:      \t");
4842                 hexprint(cd, cd->u.verity.root_hash, cd->u.verity.root_hash_size, "");
4843                 log_std(cd, "\n");
4844         }
4845         return 0;
4846 }
4847
4848 int crypt_dump(struct crypt_device *cd)
4849 {
4850         if (!cd)
4851                 return -EINVAL;
4852         if (isLUKS1(cd->type))
4853                 return _luks_dump(cd);
4854         else if (isLUKS2(cd->type))
4855                 return LUKS2_hdr_dump(cd, &cd->u.luks2.hdr);
4856         else if (isVERITY(cd->type))
4857                 return _verity_dump(cd);
4858         else if (isTCRYPT(cd->type))
4859                 return TCRYPT_dump(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
4860         else if (isINTEGRITY(cd->type))
4861                 return INTEGRITY_dump(cd, crypt_data_device(cd), 0);
4862         else if (isBITLK(cd->type))
4863                 return BITLK_dump(cd, crypt_data_device(cd), &cd->u.bitlk.params);
4864
4865         log_err(cd, _("Dump operation is not supported for this device type."));
4866         return -EINVAL;
4867 }
4868
4869 /* internal only */
4870 const char *crypt_get_cipher_spec(struct crypt_device *cd)
4871 {
4872         if (!cd)
4873                 return NULL;
4874         else if (isLUKS2(cd->type))
4875                 return LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
4876         else if (isLUKS1(cd->type))
4877                 return cd->u.luks1.cipher_spec;
4878         else if (isPLAIN(cd->type))
4879                 return cd->u.plain.cipher_spec;
4880         else if (isLOOPAES(cd->type))
4881                 return cd->u.loopaes.cipher_spec;
4882         else if (isBITLK(cd->type))
4883                 return cd->u.bitlk.cipher_spec;
4884         else if (!cd->type && !_init_by_name_crypt_none(cd))
4885                 return cd->u.none.cipher_spec;
4886
4887         return NULL;
4888 }
4889
4890 const char *crypt_get_cipher(struct crypt_device *cd)
4891 {
4892         if (!cd)
4893                 return NULL;
4894
4895         if (isPLAIN(cd->type))
4896                 return cd->u.plain.cipher;
4897
4898         if (isLUKS1(cd->type))
4899                 return cd->u.luks1.hdr.cipherName;
4900
4901         if (isLUKS2(cd->type)) {
4902                 if (crypt_parse_name_and_mode(LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT),
4903                                               cd->u.luks2.cipher, NULL, cd->u.luks2.cipher_mode))
4904                         return NULL;
4905                 return cd->u.luks2.cipher;
4906         }
4907
4908         if (isLOOPAES(cd->type))
4909                 return cd->u.loopaes.cipher;
4910
4911         if (isTCRYPT(cd->type))
4912                 return cd->u.tcrypt.params.cipher;
4913
4914         if (isBITLK(cd->type))
4915                 return cd->u.bitlk.params.cipher;
4916
4917         if (!cd->type && !_init_by_name_crypt_none(cd))
4918                 return cd->u.none.cipher;
4919
4920         return NULL;
4921 }
4922
4923 const char *crypt_get_cipher_mode(struct crypt_device *cd)
4924 {
4925         if (!cd)
4926                 return NULL;
4927
4928         if (isPLAIN(cd->type))
4929                 return cd->u.plain.cipher_mode;
4930
4931         if (isLUKS1(cd->type))
4932                 return cd->u.luks1.hdr.cipherMode;
4933
4934         if (isLUKS2(cd->type)) {
4935                 if (crypt_parse_name_and_mode(LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT),
4936                                               cd->u.luks2.cipher, NULL, cd->u.luks2.cipher_mode))
4937                         return NULL;
4938                 return cd->u.luks2.cipher_mode;
4939         }
4940
4941         if (isLOOPAES(cd->type))
4942                 return cd->u.loopaes.cipher_mode;
4943
4944         if (isTCRYPT(cd->type))
4945                 return cd->u.tcrypt.params.mode;
4946
4947         if (isBITLK(cd->type))
4948                 return cd->u.bitlk.params.cipher_mode;
4949
4950         if (!cd->type && !_init_by_name_crypt_none(cd))
4951                 return cd->u.none.cipher_mode;
4952
4953         return NULL;
4954 }
4955
4956 /* INTERNAL only */
4957 const char *crypt_get_integrity(struct crypt_device *cd)
4958 {
4959         if (isINTEGRITY(cd->type))
4960                 return cd->u.integrity.params.integrity;
4961
4962         if (isLUKS2(cd->type))
4963                 return LUKS2_get_integrity(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
4964
4965         return NULL;
4966 }
4967
4968 /* INTERNAL only */
4969 int crypt_get_integrity_key_size(struct crypt_device *cd)
4970 {
4971         if (isINTEGRITY(cd->type))
4972                 return INTEGRITY_key_size(cd, crypt_get_integrity(cd));
4973
4974         if (isLUKS2(cd->type))
4975                 return INTEGRITY_key_size(cd, crypt_get_integrity(cd));
4976
4977         return 0;
4978 }
4979
4980 /* INTERNAL only */
4981 int crypt_get_integrity_tag_size(struct crypt_device *cd)
4982 {
4983         if (isINTEGRITY(cd->type))
4984                 return cd->u.integrity.params.tag_size;
4985
4986         if (isLUKS2(cd->type))
4987                 return INTEGRITY_tag_size(cd, crypt_get_integrity(cd),
4988                                           crypt_get_cipher(cd),
4989                                           crypt_get_cipher_mode(cd));
4990         return 0;
4991 }
4992
4993 int crypt_get_sector_size(struct crypt_device *cd)
4994 {
4995         if (!cd)
4996                 return SECTOR_SIZE;
4997
4998         if (isPLAIN(cd->type))
4999                 return cd->u.plain.hdr.sector_size;
5000
5001         if (isINTEGRITY(cd->type))
5002                 return cd->u.integrity.params.sector_size;
5003
5004         if (isLUKS2(cd->type))
5005                 return LUKS2_get_sector_size(&cd->u.luks2.hdr);
5006
5007         return SECTOR_SIZE;
5008 }
5009
5010 const char *crypt_get_uuid(struct crypt_device *cd)
5011 {
5012         if (!cd)
5013                 return NULL;
5014
5015         if (isLUKS1(cd->type))
5016                 return cd->u.luks1.hdr.uuid;
5017
5018         if (isLUKS2(cd->type))
5019                 return cd->u.luks2.hdr.uuid;
5020
5021         if (isVERITY(cd->type))
5022                 return cd->u.verity.uuid;
5023
5024         if (isBITLK(cd->type))
5025                 return cd->u.bitlk.params.guid;
5026
5027         return NULL;
5028 }
5029
5030 const char *crypt_get_device_name(struct crypt_device *cd)
5031 {
5032         const char *path;
5033
5034         if (!cd)
5035                 return NULL;
5036
5037         path = device_block_path(cd->device);
5038         if (!path)
5039                 path = device_path(cd->device);
5040
5041         return path;
5042 }
5043
5044 const char *crypt_get_metadata_device_name(struct crypt_device *cd)
5045 {
5046         const char *path;
5047
5048         if (!cd || !cd->metadata_device)
5049                 return NULL;
5050
5051         path = device_block_path(cd->metadata_device);
5052         if (!path)
5053                 path = device_path(cd->metadata_device);
5054
5055         return path;
5056 }
5057
5058 int crypt_get_volume_key_size(struct crypt_device *cd)
5059 {
5060         int r;
5061
5062         if (!cd)
5063                 return 0;
5064
5065         if (isPLAIN(cd->type))
5066                 return cd->u.plain.key_size;
5067
5068         if (isLUKS1(cd->type))
5069                 return cd->u.luks1.hdr.keyBytes;
5070
5071         if (isLUKS2(cd->type)) {
5072                 r = LUKS2_get_volume_key_size(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
5073                 if (r < 0 && cd->volume_key)
5074                         r = cd->volume_key->keylength;
5075                 return r < 0 ? 0 : r;
5076         }
5077
5078         if (isLOOPAES(cd->type))
5079                 return cd->u.loopaes.key_size;
5080
5081         if (isVERITY(cd->type))
5082                 return cd->u.verity.root_hash_size;
5083
5084         if (isTCRYPT(cd->type))
5085                 return cd->u.tcrypt.params.key_size;
5086
5087         if (isBITLK(cd->type))
5088                 return cd->u.bitlk.params.key_size / 8;
5089
5090         if (!cd->type && !_init_by_name_crypt_none(cd))
5091                 return cd->u.none.key_size;
5092
5093         return 0;
5094 }
5095
5096 int crypt_keyslot_get_key_size(struct crypt_device *cd, int keyslot)
5097 {
5098         if (!cd || !isLUKS(cd->type))
5099                 return -EINVAL;
5100
5101         if (keyslot < 0 || keyslot >= crypt_keyslot_max(cd->type))
5102                 return -EINVAL;
5103
5104         if (isLUKS1(cd->type))
5105                 return cd->u.luks1.hdr.keyBytes;
5106
5107         if (isLUKS2(cd->type))
5108                 return LUKS2_get_keyslot_stored_key_size(&cd->u.luks2.hdr, keyslot);
5109
5110         return -EINVAL;
5111 }
5112
5113 int crypt_keyslot_set_encryption(struct crypt_device *cd,
5114         const char *cipher,
5115         size_t key_size)
5116 {
5117         char *tmp;
5118
5119         if (!cd || !cipher || ! key_size || !isLUKS2(cd->type))
5120                 return -EINVAL;
5121
5122         if (LUKS2_keyslot_cipher_incompatible(cd, cipher))
5123                 return -EINVAL;
5124
5125         tmp = strdup(cipher);
5126         free(cd->u.luks2.keyslot_cipher);
5127         cd->u.luks2.keyslot_cipher = tmp;
5128         if (!cd->u.luks2.keyslot_cipher)
5129                 return -ENOMEM;
5130         cd->u.luks2.keyslot_key_size = key_size;
5131
5132         return 0;
5133 }
5134
5135 const char *crypt_keyslot_get_encryption(struct crypt_device *cd, int keyslot, size_t *key_size)
5136 {
5137         const char *cipher;
5138
5139         if (!cd || !isLUKS(cd->type) || !key_size)
5140                 return NULL;
5141
5142         if (isLUKS1(cd->type)) {
5143                 if (keyslot != CRYPT_ANY_SLOT &&
5144                     LUKS_keyslot_info(&cd->u.luks1.hdr, keyslot) < CRYPT_SLOT_ACTIVE)
5145                         return NULL;
5146                 *key_size = crypt_get_volume_key_size(cd);
5147                 return cd->u.luks1.cipher_spec;
5148         }
5149
5150         if (keyslot != CRYPT_ANY_SLOT)
5151                 return LUKS2_get_keyslot_cipher(&cd->u.luks2.hdr, keyslot, key_size);
5152
5153         /* Keyslot encryption was set through crypt_keyslot_set_encryption() */
5154         if (cd->u.luks2.keyslot_cipher) {
5155                 *key_size = cd->u.luks2.keyslot_key_size;
5156                 return cd->u.luks2.keyslot_cipher;
5157         }
5158
5159         /* Try to reuse volume encryption parameters */
5160         cipher =  LUKS2_get_cipher(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
5161         if (!LUKS2_keyslot_cipher_incompatible(cd, cipher)) {
5162                 *key_size = crypt_get_volume_key_size(cd);
5163                 if (*key_size)
5164                         return cipher;
5165         }
5166
5167         /* Fallback to default LUKS2 keyslot encryption */
5168         *key_size = DEFAULT_LUKS2_KEYSLOT_KEYBITS / 8;
5169         return DEFAULT_LUKS2_KEYSLOT_CIPHER;
5170 }
5171
5172 int crypt_keyslot_get_pbkdf(struct crypt_device *cd, int keyslot, struct crypt_pbkdf_type *pbkdf)
5173 {
5174         if (!cd || !pbkdf || keyslot == CRYPT_ANY_SLOT)
5175                 return -EINVAL;
5176
5177         if (isLUKS1(cd->type))
5178                 return LUKS_keyslot_pbkdf(&cd->u.luks1.hdr, keyslot, pbkdf);
5179         else if (isLUKS2(cd->type))
5180                 return LUKS2_keyslot_pbkdf(&cd->u.luks2.hdr, keyslot, pbkdf);
5181
5182         return -EINVAL;
5183 }
5184
5185 int crypt_set_data_offset(struct crypt_device *cd, uint64_t data_offset)
5186 {
5187         if (!cd)
5188                 return -EINVAL;
5189         if (data_offset % (MAX_SECTOR_SIZE >> SECTOR_SHIFT)) {
5190                 log_err(cd, _("Data offset is not multiple of %u bytes."), MAX_SECTOR_SIZE);
5191                 return -EINVAL;
5192         }
5193
5194         cd->data_offset = data_offset;
5195         log_dbg(cd, "Data offset set to %" PRIu64 " (512-byte) sectors.", data_offset);
5196
5197         return 0;
5198 }
5199
5200 int crypt_set_metadata_size(struct crypt_device *cd,
5201         uint64_t metadata_size,
5202         uint64_t keyslots_size)
5203 {
5204         if (!cd)
5205                 return -EINVAL;
5206
5207         if (cd->type && !isLUKS2(cd->type))
5208                 return -EINVAL;
5209
5210         if (metadata_size && LUKS2_check_metadata_area_size(metadata_size))
5211                 return -EINVAL;
5212
5213         if (keyslots_size && LUKS2_check_keyslots_area_size(keyslots_size))
5214                 return -EINVAL;
5215
5216         cd->metadata_size = metadata_size;
5217         cd->keyslots_size = keyslots_size;
5218
5219         return 0;
5220 }
5221
5222 int crypt_get_metadata_size(struct crypt_device *cd,
5223         uint64_t *metadata_size,
5224         uint64_t *keyslots_size)
5225 {
5226         uint64_t msize, ksize;
5227
5228         if (!cd)
5229                 return -EINVAL;
5230
5231         if (!cd->type) {
5232                 msize = cd->metadata_size;
5233                 ksize = cd->keyslots_size;
5234         } else if (isLUKS1(cd->type)) {
5235                 msize = LUKS_ALIGN_KEYSLOTS;
5236                 ksize = LUKS_device_sectors(&cd->u.luks1.hdr) * SECTOR_SIZE - msize;
5237         } else if (isLUKS2(cd->type)) {
5238                 msize = LUKS2_metadata_size(cd->u.luks2.hdr.jobj);
5239                 ksize = LUKS2_keyslots_size(cd->u.luks2.hdr.jobj);
5240         } else
5241                 return -EINVAL;
5242
5243         if (metadata_size)
5244                 *metadata_size = msize;
5245         if (keyslots_size)
5246                 *keyslots_size = ksize;
5247
5248         return 0;
5249 }
5250
5251 uint64_t crypt_get_data_offset(struct crypt_device *cd)
5252 {
5253         if (!cd)
5254                 return 0;
5255
5256         if (isPLAIN(cd->type))
5257                 return cd->u.plain.hdr.offset;
5258
5259         if (isLUKS1(cd->type))
5260                 return cd->u.luks1.hdr.payloadOffset;
5261
5262         if (isLUKS2(cd->type))
5263                 return LUKS2_get_data_offset(&cd->u.luks2.hdr);
5264
5265         if (isLOOPAES(cd->type))
5266                 return cd->u.loopaes.hdr.offset;
5267
5268         if (isTCRYPT(cd->type))
5269                 return TCRYPT_get_data_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
5270
5271         if (isBITLK(cd->type))
5272                 return cd->u.bitlk.params.volume_header_size / SECTOR_SIZE;
5273
5274         return cd->data_offset;
5275 }
5276
5277 uint64_t crypt_get_iv_offset(struct crypt_device *cd)
5278 {
5279         if (!cd)
5280                 return 0;
5281
5282         if (isPLAIN(cd->type))
5283                 return cd->u.plain.hdr.skip;
5284
5285         if (isLOOPAES(cd->type))
5286                 return cd->u.loopaes.hdr.skip;
5287
5288         if (isTCRYPT(cd->type))
5289                 return TCRYPT_get_iv_offset(cd, &cd->u.tcrypt.hdr, &cd->u.tcrypt.params);
5290
5291         return 0;
5292 }
5293
5294 crypt_keyslot_info crypt_keyslot_status(struct crypt_device *cd, int keyslot)
5295 {
5296         if (_onlyLUKS(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED) < 0)
5297                 return CRYPT_SLOT_INVALID;
5298
5299         if (isLUKS1(cd->type))
5300                 return LUKS_keyslot_info(&cd->u.luks1.hdr, keyslot);
5301         else if(isLUKS2(cd->type))
5302                 return LUKS2_keyslot_info(&cd->u.luks2.hdr, keyslot);
5303
5304         return CRYPT_SLOT_INVALID;
5305 }
5306
5307 int crypt_keyslot_max(const char *type)
5308 {
5309         if (type && isLUKS1(type))
5310                 return LUKS_NUMKEYS;
5311
5312         if (type && isLUKS2(type))
5313                 return LUKS2_KEYSLOTS_MAX;
5314
5315         return -EINVAL;
5316 }
5317
5318 int crypt_keyslot_area(struct crypt_device *cd,
5319         int keyslot,
5320         uint64_t *offset,
5321         uint64_t *length)
5322 {
5323         if (_onlyLUKS(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED) || !offset || !length)
5324                 return -EINVAL;
5325
5326         if (isLUKS2(cd->type))
5327                 return LUKS2_keyslot_area(&cd->u.luks2.hdr, keyslot, offset, length);
5328
5329         return LUKS_keyslot_area(&cd->u.luks1.hdr, keyslot, offset, length);
5330 }
5331
5332 crypt_keyslot_priority crypt_keyslot_get_priority(struct crypt_device *cd, int keyslot)
5333 {
5334         if (_onlyLUKS(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED))
5335                 return CRYPT_SLOT_PRIORITY_INVALID;
5336
5337         if (keyslot < 0 || keyslot >= crypt_keyslot_max(cd->type))
5338                 return CRYPT_SLOT_PRIORITY_INVALID;
5339
5340         if (isLUKS2(cd->type))
5341                 return LUKS2_keyslot_priority_get(cd, &cd->u.luks2.hdr, keyslot);
5342
5343         return CRYPT_SLOT_PRIORITY_NORMAL;
5344 }
5345
5346 int crypt_keyslot_set_priority(struct crypt_device *cd, int keyslot, crypt_keyslot_priority priority)
5347 {
5348         int r;
5349
5350         log_dbg(cd, "Setting keyslot %d to priority %d.", keyslot, priority);
5351
5352         if (priority == CRYPT_SLOT_PRIORITY_INVALID)
5353                 return -EINVAL;
5354
5355         if (keyslot < 0 || keyslot >= crypt_keyslot_max(cd->type))
5356                 return -EINVAL;
5357
5358         if ((r = onlyLUKS2(cd)))
5359                 return r;
5360
5361         return LUKS2_keyslot_priority_set(cd, &cd->u.luks2.hdr, keyslot, priority, 1);
5362 }
5363
5364 const char *crypt_get_type(struct crypt_device *cd)
5365 {
5366         return cd ? cd->type : NULL;
5367 }
5368
5369 const char *crypt_get_default_type(void)
5370 {
5371         return DEFAULT_LUKS_FORMAT;
5372 }
5373
5374 int crypt_get_verity_info(struct crypt_device *cd,
5375         struct crypt_params_verity *vp)
5376 {
5377         if (!cd || !isVERITY(cd->type) || !vp)
5378                 return -EINVAL;
5379
5380         vp->data_device = device_path(cd->device);
5381         vp->hash_device = mdata_device_path(cd);
5382         vp->fec_device  = device_path(cd->u.verity.fec_device);
5383         vp->fec_area_offset = cd->u.verity.hdr.fec_area_offset;
5384         vp->fec_roots = cd->u.verity.hdr.fec_roots;
5385         vp->hash_name = cd->u.verity.hdr.hash_name;
5386         vp->salt = cd->u.verity.hdr.salt;
5387         vp->salt_size = cd->u.verity.hdr.salt_size;
5388         vp->data_block_size = cd->u.verity.hdr.data_block_size;
5389         vp->hash_block_size = cd->u.verity.hdr.hash_block_size;
5390         vp->data_size = cd->u.verity.hdr.data_size;
5391         vp->hash_area_offset = cd->u.verity.hdr.hash_area_offset;
5392         vp->hash_type = cd->u.verity.hdr.hash_type;
5393         vp->flags = cd->u.verity.hdr.flags & (CRYPT_VERITY_NO_HEADER | CRYPT_VERITY_ROOT_HASH_SIGNATURE);
5394         return 0;
5395 }
5396
5397 int crypt_get_integrity_info(struct crypt_device *cd,
5398         struct crypt_params_integrity *ip)
5399 {
5400         if (!cd || !ip)
5401                 return -EINVAL;
5402
5403         if (isINTEGRITY(cd->type)) {
5404                 ip->journal_size = cd->u.integrity.params.journal_size;
5405                 ip->journal_watermark = cd->u.integrity.params.journal_watermark;
5406                 ip->journal_commit_time = cd->u.integrity.params.journal_commit_time;
5407                 ip->interleave_sectors = cd->u.integrity.params.interleave_sectors;
5408                 ip->tag_size = cd->u.integrity.params.tag_size;
5409                 ip->sector_size = cd->u.integrity.params.sector_size;
5410                 ip->buffer_sectors = cd->u.integrity.params.buffer_sectors;
5411
5412                 ip->integrity = cd->u.integrity.params.integrity;
5413                 ip->integrity_key_size = crypt_get_integrity_key_size(cd);
5414
5415                 ip->journal_integrity = cd->u.integrity.params.journal_integrity;
5416                 ip->journal_integrity_key_size = cd->u.integrity.params.journal_integrity_key_size;
5417                 ip->journal_integrity_key = NULL;
5418
5419                 ip->journal_crypt = cd->u.integrity.params.journal_crypt;
5420                 ip->journal_crypt_key_size = cd->u.integrity.params.journal_crypt_key_size;
5421                 ip->journal_crypt_key = NULL;
5422                 return 0;
5423         } else if (isLUKS2(cd->type)) {
5424                 ip->journal_size = 0; // FIXME
5425                 ip->journal_watermark = 0; // FIXME
5426                 ip->journal_commit_time = 0; // FIXME
5427                 ip->interleave_sectors = 0; // FIXME
5428                 ip->sector_size = crypt_get_sector_size(cd);
5429                 ip->buffer_sectors = 0; // FIXME
5430
5431                 ip->integrity = LUKS2_get_integrity(&cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT);
5432                 ip->integrity_key_size = crypt_get_integrity_key_size(cd);
5433                 ip->tag_size = INTEGRITY_tag_size(cd, ip->integrity, crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
5434
5435                 ip->journal_integrity = NULL;
5436                 ip->journal_integrity_key_size = 0;
5437                 ip->journal_integrity_key = NULL;
5438
5439                 ip->journal_crypt = NULL;
5440                 ip->journal_crypt_key_size = 0;
5441                 ip->journal_crypt_key = NULL;
5442                 return 0;
5443         }
5444
5445         return -ENOTSUP;
5446 }
5447
5448 int crypt_convert(struct crypt_device *cd,
5449                   const char *type,
5450                   void *params)
5451 {
5452         struct luks_phdr hdr1;
5453         struct luks2_hdr hdr2;
5454         int r;
5455
5456         if (!type)
5457                 return -EINVAL;
5458
5459         log_dbg(cd, "Converting LUKS device to type %s", type);
5460
5461         if ((r = onlyLUKS(cd)))
5462                 return r;
5463
5464         if (isLUKS1(cd->type) && isLUKS2(type))
5465                 r = LUKS2_luks1_to_luks2(cd, &cd->u.luks1.hdr, &hdr2);
5466         else if (isLUKS2(cd->type) && isLUKS1(type))
5467                 r = LUKS2_luks2_to_luks1(cd, &cd->u.luks2.hdr, &hdr1);
5468         else
5469                 return -EINVAL;
5470
5471         if (r < 0) {
5472                 /* in-memory header may be invalid after failed conversion */
5473                 _luks2_reload(cd);
5474                 if (r == -EBUSY)
5475                         log_err(cd, _("Cannot convert device %s which is still in use."), mdata_device_path(cd));
5476                 return r;
5477         }
5478
5479         crypt_free_type(cd);
5480
5481         return crypt_load(cd, type, params);
5482 }
5483
5484 /* Internal access function to header pointer */
5485 void *crypt_get_hdr(struct crypt_device *cd, const char *type)
5486 {
5487         /* If requested type differs, ignore it */
5488         if (strcmp(cd->type, type))
5489                 return NULL;
5490
5491         if (isPLAIN(cd->type))
5492                 return &cd->u.plain;
5493
5494         if (isLUKS1(cd->type))
5495                 return &cd->u.luks1.hdr;
5496
5497         if (isLUKS2(cd->type))
5498                 return &cd->u.luks2.hdr;
5499
5500         if (isLOOPAES(cd->type))
5501                 return &cd->u.loopaes;
5502
5503         if (isVERITY(cd->type))
5504                 return &cd->u.verity;
5505
5506         if (isTCRYPT(cd->type))
5507                 return &cd->u.tcrypt;
5508
5509         return NULL;
5510 }
5511
5512 /* internal only */
5513 struct luks2_reenc_context *crypt_get_reenc_context(struct crypt_device *cd)
5514 {
5515         return cd->u.luks2.rh;
5516 }
5517
5518 /* internal only */
5519 void crypt_set_reenc_context(struct crypt_device *cd, struct luks2_reenc_context *rh)
5520 {
5521         cd->u.luks2.rh = rh;
5522 }
5523
5524 /*
5525  * Token handling
5526  */
5527 int crypt_activate_by_token(struct crypt_device *cd,
5528         const char *name, int token, void *usrptr, uint32_t flags)
5529 {
5530         int r;
5531
5532         log_dbg(cd, "%s volume %s using token %d.",
5533                 name ? "Activating" : "Checking", name ?: "passphrase", token);
5534
5535         if ((r = _onlyLUKS2(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED, 0)))
5536                 return r;
5537
5538         if ((flags & CRYPT_ACTIVATE_KEYRING_KEY) && !crypt_use_keyring_for_vk(cd))
5539                 return -EINVAL;
5540
5541         if ((flags & CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY) && name)
5542                 return -EINVAL;
5543
5544         if (token == CRYPT_ANY_TOKEN)
5545                 return LUKS2_token_open_and_activate_any(cd, &cd->u.luks2.hdr, name, flags);
5546
5547         return LUKS2_token_open_and_activate(cd, &cd->u.luks2.hdr, token, name, flags, usrptr);
5548 }
5549
5550 int crypt_token_json_get(struct crypt_device *cd, int token, const char **json)
5551 {
5552         int r;
5553
5554         if (!json)
5555                 return -EINVAL;
5556
5557         log_dbg(cd, "Requesting JSON for token %d.", token);
5558
5559         if ((r = _onlyLUKS2(cd, CRYPT_CD_UNRESTRICTED, 0)))
5560                 return r;
5561
5562         return LUKS2_token_json_get(cd, &cd->u.luks2.hdr, token, json) ?: token;
5563 }
5564
5565 int crypt_token_json_set(struct crypt_device *cd, int token, const char *json)
5566 {
5567         int r;
5568
5569         log_dbg(cd, "Updating JSON for token %d.", token);
5570
5571         if ((r = onlyLUKS2(cd)))
5572                 return r;
5573
5574         return LUKS2_token_create(cd, &cd->u.luks2.hdr, token, json, 1);
5575 }
5576
5577 crypt_token_info crypt_token_status(struct crypt_device *cd, int token, const char **type)
5578 {
5579         if (_onlyLUKS2(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED, 0))
5580                 return CRYPT_TOKEN_INVALID;
5581
5582         return LUKS2_token_status(cd, &cd->u.luks2.hdr, token, type);
5583 }
5584
5585 int crypt_token_luks2_keyring_get(struct crypt_device *cd,
5586         int token,
5587         struct crypt_token_params_luks2_keyring *params)
5588 {
5589         crypt_token_info token_info;
5590         const char *type;
5591         int r;
5592
5593         if (!params)
5594                 return -EINVAL;
5595
5596         log_dbg(cd, "Requesting LUKS2 keyring token %d.", token);
5597
5598         if ((r = _onlyLUKS2(cd, CRYPT_CD_UNRESTRICTED, 0)))
5599                 return r;
5600
5601         token_info = LUKS2_token_status(cd, &cd->u.luks2.hdr, token, &type);
5602         switch (token_info) {
5603         case CRYPT_TOKEN_INVALID:
5604                 log_dbg(cd, "Token %d is invalid.", token);
5605                 return -EINVAL;
5606         case CRYPT_TOKEN_INACTIVE:
5607                 log_dbg(cd, "Token %d is inactive.", token);
5608                 return -EINVAL;
5609         case CRYPT_TOKEN_INTERNAL:
5610                 if (!strcmp(type, LUKS2_TOKEN_KEYRING))
5611                         break;
5612                 /* Fall through */
5613         case CRYPT_TOKEN_INTERNAL_UNKNOWN:
5614         case CRYPT_TOKEN_EXTERNAL:
5615         case CRYPT_TOKEN_EXTERNAL_UNKNOWN:
5616                 log_dbg(cd, "Token %d has unexpected type %s.", token, type);
5617                 return -EINVAL;
5618         }
5619
5620         return LUKS2_builtin_token_get(cd, &cd->u.luks2.hdr, token, LUKS2_TOKEN_KEYRING, params);
5621 }
5622
5623 int crypt_token_luks2_keyring_set(struct crypt_device *cd,
5624         int token,
5625         const struct crypt_token_params_luks2_keyring *params)
5626 {
5627         int r;
5628
5629         if (!params)
5630                 return -EINVAL;
5631
5632         log_dbg(cd, "Creating new LUKS2 keyring token (%d).", token);
5633
5634         if ((r = onlyLUKS2(cd)))
5635                 return r;
5636
5637         return LUKS2_builtin_token_create(cd, &cd->u.luks2.hdr, token, LUKS2_TOKEN_KEYRING, params, 1);
5638 }
5639
5640 int crypt_token_assign_keyslot(struct crypt_device *cd, int token, int keyslot)
5641 {
5642         int r;
5643
5644         if ((r = onlyLUKS2(cd)))
5645                 return r;
5646
5647         return LUKS2_token_assign(cd, &cd->u.luks2.hdr, keyslot, token, 1, 1);
5648 }
5649
5650 int crypt_token_unassign_keyslot(struct crypt_device *cd, int token, int keyslot)
5651 {
5652         int r;
5653
5654         if ((r = onlyLUKS2(cd)))
5655                 return r;
5656
5657         return LUKS2_token_assign(cd, &cd->u.luks2.hdr, keyslot, token, 0, 1);
5658 }
5659
5660 int crypt_token_is_assigned(struct crypt_device *cd, int token, int keyslot)
5661 {
5662         int r;
5663
5664         if ((r = _onlyLUKS2(cd, CRYPT_CD_QUIET | CRYPT_CD_UNRESTRICTED, 0)))
5665                 return r;
5666
5667         return LUKS2_token_is_assigned(cd, &cd->u.luks2.hdr, keyslot, token);
5668 }
5669
5670 /* Internal only */
5671 int crypt_metadata_locking_enabled(void)
5672 {
5673         return _metadata_locking;
5674 }
5675
5676 int crypt_metadata_locking(struct crypt_device *cd, int enable)
5677 {
5678         if (enable && !_metadata_locking)
5679                 return -EPERM;
5680
5681         _metadata_locking = enable ? 1 : 0;
5682         return 0;
5683 }
5684
5685 int crypt_persistent_flags_set(struct crypt_device *cd, crypt_flags_type type, uint32_t flags)
5686 {
5687         int r;
5688
5689         if ((r = onlyLUKS2(cd)))
5690                 return r;
5691
5692         if (type == CRYPT_FLAGS_ACTIVATION)
5693                 return LUKS2_config_set_flags(cd, &cd->u.luks2.hdr, flags);
5694
5695         if (type == CRYPT_FLAGS_REQUIREMENTS)
5696                 return LUKS2_config_set_requirements(cd, &cd->u.luks2.hdr, flags, true);
5697
5698         return -EINVAL;
5699 }
5700
5701 int crypt_persistent_flags_get(struct crypt_device *cd, crypt_flags_type type, uint32_t *flags)
5702 {
5703         int r;
5704
5705         if (!flags)
5706                 return -EINVAL;
5707
5708         if ((r = _onlyLUKS2(cd, CRYPT_CD_UNRESTRICTED, 0)))
5709                 return r;
5710
5711         if (type == CRYPT_FLAGS_ACTIVATION)
5712                 return LUKS2_config_get_flags(cd, &cd->u.luks2.hdr, flags);
5713
5714         if (type == CRYPT_FLAGS_REQUIREMENTS)
5715                 return LUKS2_config_get_requirements(cd, &cd->u.luks2.hdr, flags);
5716
5717         return -EINVAL;
5718 }
5719
5720 static int update_volume_key_segment_digest(struct crypt_device *cd, struct luks2_hdr *hdr, int digest, int commit)
5721 {
5722         int r;
5723
5724         /* Remove any assignments in memory */
5725         r = LUKS2_digest_segment_assign(cd, hdr, CRYPT_DEFAULT_SEGMENT, CRYPT_ANY_DIGEST, 0, 0);
5726         if (r)
5727                 return r;
5728
5729         /* Assign it to the specific digest */
5730         return LUKS2_digest_segment_assign(cd, hdr, CRYPT_DEFAULT_SEGMENT, digest, 1, commit);
5731 }
5732
5733 static int verify_and_update_segment_digest(struct crypt_device *cd,
5734                 struct luks2_hdr *hdr, int keyslot,
5735                 const char *volume_key, size_t volume_key_size,
5736                 const char *password, size_t password_size)
5737 {
5738         int digest, r;
5739         struct volume_key *vk = NULL;
5740
5741         if (keyslot < 0 || (volume_key && !volume_key_size))
5742                 return -EINVAL;
5743
5744         if (volume_key)
5745                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
5746         else {
5747                 r = LUKS2_keyslot_open(cd, keyslot, CRYPT_ANY_SEGMENT, password, password_size, &vk);
5748                 if (r != keyslot) {
5749                         r = -EINVAL;
5750                         goto out;
5751                 }
5752         }
5753
5754         if (!vk)
5755                 return -ENOMEM;
5756
5757         /* check volume_key (param) digest matches keyslot digest */
5758         r = LUKS2_digest_verify(cd, hdr, vk, keyslot);
5759         if (r < 0)
5760                 goto out;
5761         digest = r;
5762
5763         /* nothing to do, volume key in keyslot is already assigned to default segment */
5764         r = LUKS2_digest_verify_by_segment(cd, hdr, CRYPT_DEFAULT_SEGMENT, vk);
5765         if (r >= 0)
5766                 goto out;
5767
5768         /* FIXME: check new volume key is usable with current default segment */
5769
5770         r = update_volume_key_segment_digest(cd, &cd->u.luks2.hdr, digest, 1);
5771         if (r)
5772                 log_err(cd, _("Failed to assign keyslot %u as the new volume key."), keyslot);
5773 out:
5774         crypt_free_volume_key(vk);
5775         return r < 0 ? r : keyslot;
5776 }
5777
5778
5779 int crypt_keyslot_add_by_key(struct crypt_device *cd,
5780         int keyslot,
5781         const char *volume_key,
5782         size_t volume_key_size,
5783         const char *passphrase,
5784         size_t passphrase_size,
5785         uint32_t flags)
5786 {
5787         int digest, r;
5788         struct luks2_keyslot_params params;
5789         struct volume_key *vk = NULL;
5790
5791         if (!passphrase || ((flags & CRYPT_VOLUME_KEY_NO_SEGMENT) &&
5792                             (flags & CRYPT_VOLUME_KEY_SET)))
5793                 return -EINVAL;
5794
5795         log_dbg(cd, "Adding new keyslot %d with volume key %sassigned to a crypt segment.",
5796                 keyslot, flags & CRYPT_VOLUME_KEY_NO_SEGMENT ? "un" : "");
5797
5798         if ((r = onlyLUKS2(cd)))
5799                 return r;
5800
5801         /* new volume key assignment */
5802         if ((flags & CRYPT_VOLUME_KEY_SET) && crypt_keyslot_status(cd, keyslot) > CRYPT_SLOT_INACTIVE)
5803                 return verify_and_update_segment_digest(cd, &cd->u.luks2.hdr,
5804                         keyslot, volume_key, volume_key_size, passphrase, passphrase_size);
5805
5806         r = keyslot_verify_or_find_empty(cd, &keyslot);
5807         if (r < 0)
5808                 return r;
5809
5810         if (volume_key)
5811                 vk = crypt_alloc_volume_key(volume_key_size, volume_key);
5812         else if (flags & CRYPT_VOLUME_KEY_NO_SEGMENT)
5813                 vk = crypt_generate_volume_key(cd, volume_key_size);
5814         else if (cd->volume_key)
5815                 vk = crypt_alloc_volume_key(cd->volume_key->keylength, cd->volume_key->key);
5816         else
5817                 return -EINVAL;
5818
5819         if (!vk)
5820                 return -ENOMEM;
5821
5822         /* if key matches volume key digest tear down new vk flag */
5823         digest = LUKS2_digest_verify_by_segment(cd, &cd->u.luks2.hdr, CRYPT_DEFAULT_SEGMENT, vk);
5824         if (digest >= 0)
5825                 flags &= ~CRYPT_VOLUME_KEY_SET;
5826
5827         /* if key matches any existing digest, do not create new digest */
5828         if (digest < 0 && (flags & CRYPT_VOLUME_KEY_DIGEST_REUSE))
5829                 digest = LUKS2_digest_any_matching(cd, &cd->u.luks2.hdr, vk);
5830
5831         /* no segment flag or new vk flag requires new key digest */
5832         if (flags & (CRYPT_VOLUME_KEY_NO_SEGMENT | CRYPT_VOLUME_KEY_SET)) {
5833                 if (digest < 0 || !(flags & CRYPT_VOLUME_KEY_DIGEST_REUSE))
5834                         digest = LUKS2_digest_create(cd, "pbkdf2", &cd->u.luks2.hdr, vk);
5835         }
5836
5837         r = digest;
5838         if (r < 0) {
5839                 log_err(cd, _("Volume key does not match the volume."));
5840                 goto out;
5841         }
5842
5843         r = LUKS2_keyslot_params_default(cd, &cd->u.luks2.hdr, &params);
5844         if (r < 0) {
5845                 log_err(cd, _("Failed to initialize default LUKS2 keyslot parameters."));
5846                 goto out;
5847         }
5848
5849         r = LUKS2_digest_assign(cd, &cd->u.luks2.hdr, keyslot, digest, 1, 0);
5850         if (r < 0) {
5851                 log_err(cd, _("Failed to assign keyslot %d to digest."), keyslot);
5852                 goto out;
5853         }
5854
5855         r = LUKS2_keyslot_store(cd, &cd->u.luks2.hdr, keyslot,
5856                                 passphrase, passphrase_size, vk, &params);
5857
5858         if (r >= 0 && (flags & CRYPT_VOLUME_KEY_SET))
5859                 r = update_volume_key_segment_digest(cd, &cd->u.luks2.hdr, digest, 1);
5860 out:
5861         crypt_free_volume_key(vk);
5862         if (r < 0) {
5863                 _luks2_reload(cd);
5864                 return r;
5865         }
5866         return keyslot;
5867 }
5868
5869 /*
5870  * Keyring handling
5871  */
5872
5873 int crypt_use_keyring_for_vk(struct crypt_device *cd)
5874 {
5875         uint32_t dmc_flags;
5876
5877         /* dm backend must be initialized */
5878         if (!cd || !isLUKS2(cd->type))
5879                 return 0;
5880
5881         if (!_vk_via_keyring || !kernel_keyring_support())
5882                 return 0;
5883
5884         if (dm_flags(cd, DM_CRYPT, &dmc_flags))
5885                 return dmcrypt_keyring_bug() ? 0 : 1;
5886
5887         return (dmc_flags & DM_KERNEL_KEYRING_SUPPORTED);
5888 }
5889
5890 int crypt_volume_key_keyring(struct crypt_device *cd, int enable)
5891 {
5892         _vk_via_keyring = enable ? 1 : 0;
5893         return 0;
5894 }
5895
5896 /* internal only */
5897 int crypt_volume_key_load_in_keyring(struct crypt_device *cd, struct volume_key *vk)
5898 {
5899         int r;
5900         const char *type_name = key_type_name(LOGON_KEY);
5901
5902         if (!vk || !cd || !type_name)
5903                 return -EINVAL;
5904
5905         if (!vk->key_description) {
5906                 log_dbg(cd, "Invalid key description");
5907                 return -EINVAL;
5908         }
5909
5910         log_dbg(cd, "Loading key (%zu bytes, type %s) in thread keyring.", vk->keylength, type_name);
5911
5912         r = keyring_add_key_in_thread_keyring(LOGON_KEY, vk->key_description, vk->key, vk->keylength);
5913         if (r) {
5914                 log_dbg(cd, "keyring_add_key_in_thread_keyring failed (error %d)", r);
5915                 log_err(cd, _("Failed to load key in kernel keyring."));
5916         } else
5917                 crypt_set_key_in_keyring(cd, 1);
5918
5919         return r;
5920 }
5921
5922 /* internal only */
5923 int crypt_key_in_keyring(struct crypt_device *cd)
5924 {
5925         return cd ? cd->key_in_keyring : 0;
5926 }
5927
5928 /* internal only */
5929 void crypt_set_key_in_keyring(struct crypt_device *cd, unsigned key_in_keyring)
5930 {
5931         if (!cd)
5932                 return;
5933
5934         cd->key_in_keyring = key_in_keyring;
5935 }
5936
5937 /* internal only */
5938 void crypt_drop_keyring_key_by_description(struct crypt_device *cd, const char *key_description, key_type_t ktype)
5939 {
5940         int r;
5941         const char *type_name = key_type_name(ktype);
5942
5943         if (!key_description || !type_name)
5944                 return;
5945
5946         log_dbg(cd, "Requesting keyring %s key for revoke and unlink.", type_name);
5947
5948         r = keyring_revoke_and_unlink_key(ktype, key_description);
5949         if (r)
5950                 log_dbg(cd, "keyring_revoke_and_unlink_key failed (error %d)", r);
5951         crypt_set_key_in_keyring(cd, 0);
5952 }
5953
5954 /* internal only */
5955 void crypt_drop_keyring_key(struct crypt_device *cd, struct volume_key *vks)
5956 {
5957         struct volume_key *vk = vks;
5958
5959         while (vk) {
5960                 crypt_drop_keyring_key_by_description(cd, vk->key_description, LOGON_KEY);
5961                 vk = crypt_volume_key_next(vk);
5962         }
5963 }
5964
5965 int crypt_activate_by_keyring(struct crypt_device *cd,
5966                               const char *name,
5967                               const char *key_description,
5968                               int keyslot,
5969                               uint32_t flags)
5970 {
5971         char *passphrase;
5972         size_t passphrase_size;
5973         int r;
5974
5975         if (!cd || !key_description)
5976                 return -EINVAL;
5977
5978         log_dbg(cd, "%s volume %s [keyslot %d] using passphrase in keyring.",
5979                 name ? "Activating" : "Checking", name ?: "passphrase", keyslot);
5980
5981         if (!kernel_keyring_support()) {
5982                 log_err(cd, _("Kernel keyring is not supported by the kernel."));
5983                 return -EINVAL;
5984         }
5985
5986         r = _activate_check_status(cd, name, flags & CRYPT_ACTIVATE_REFRESH);
5987         if (r < 0)
5988                 return r;
5989
5990         r = keyring_get_passphrase(key_description, &passphrase, &passphrase_size);
5991         if (r < 0) {
5992                 log_err(cd, _("Failed to read passphrase from keyring (error %d)."), r);
5993                 return -EINVAL;
5994         }
5995
5996         r = _activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags);
5997
5998         crypt_safe_memzero(passphrase, passphrase_size);
5999         free(passphrase);
6000
6001         return r;
6002 }
6003
6004 /*
6005  * Workaround for serialization of parallel activation and memory-hard PBKDF
6006  * In specific situation (systemd activation) this causes OOM killer activation.
6007  * For now, let's provide this ugly way to serialize unlocking of devices.
6008  */
6009 int crypt_serialize_lock(struct crypt_device *cd)
6010 {
6011         if (!cd->memory_hard_pbkdf_lock_enabled)
6012                 return 0;
6013
6014         log_dbg(cd, "Taking global memory-hard access serialization lock.");
6015         if (crypt_write_lock(cd, "memory-hard-access", true, &cd->pbkdf_memory_hard_lock)) {
6016                 log_err(cd, _("Failed to acquire global memory-hard access serialization lock."));
6017                 cd->pbkdf_memory_hard_lock = NULL;
6018                 return -EINVAL;
6019         }
6020
6021         return 0;
6022 }
6023
6024 void crypt_serialize_unlock(struct crypt_device *cd)
6025 {
6026         if (!cd->memory_hard_pbkdf_lock_enabled)
6027                 return;
6028
6029         crypt_unlock_internal(cd, cd->pbkdf_memory_hard_lock);
6030         cd->pbkdf_memory_hard_lock = NULL;
6031 }
6032
6033 crypt_reencrypt_info crypt_reencrypt_status(struct crypt_device *cd,
6034                 struct crypt_params_reencrypt *params)
6035 {
6036         if (!cd || !isLUKS2(cd->type))
6037                 return CRYPT_REENCRYPT_NONE;
6038
6039         if (_onlyLUKS2(cd, CRYPT_CD_QUIET, CRYPT_REQUIREMENT_ONLINE_REENCRYPT))
6040                 return CRYPT_REENCRYPT_INVALID;
6041
6042         return LUKS2_reencrypt_status(cd, params);
6043 }
6044
6045 static void __attribute__((destructor)) libcryptsetup_exit(void)
6046 {
6047         crypt_backend_destroy();
6048         crypt_random_exit();
6049 }