Imported Upstream version 2.6.1
[platform/upstream/cryptsetup.git] / src / utils_reencrypt.c
1 /*
2  * cryptsetup - action re-encryption utilities
3  *
4  * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2009-2023 Milan Broz
6  * Copyright (C) 2021-2023 Ondrej Kozina
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <uuid/uuid.h>
24
25 #include "cryptsetup.h"
26 #include "cryptsetup_args.h"
27 #include "utils_luks.h"
28
29 extern int64_t data_shift;
30 extern const char *device_type;
31 extern const char *set_pbkdf;
32
33 enum device_status_info {
34         DEVICE_LUKS2 = 0,       /* LUKS2 device */
35         DEVICE_LUKS2_REENCRYPT, /* LUKS2 device in reencryption  */
36         DEVICE_LUKS1,           /* LUKS1 device */
37         DEVICE_LUKS1_UNUSABLE,  /* LUKS1 device in reencryption (legacy) */
38         DEVICE_NOT_LUKS,        /* device is not LUKS type */
39         DEVICE_INVALID          /* device is invalid */
40 };
41
42 static void _set_reencryption_flags(uint32_t *flags)
43 {
44         if (ARG_SET(OPT_INIT_ONLY_ID))
45                 *flags |= CRYPT_REENCRYPT_INITIALIZE_ONLY;
46
47         if (ARG_SET(OPT_RESUME_ONLY_ID))
48                 *flags |= CRYPT_REENCRYPT_RESUME_ONLY;
49 }
50
51 static int reencrypt_check_passphrase(struct crypt_device *cd,
52         int keyslot,
53         const char *passphrase,
54         size_t passphrase_len)
55 {
56         int r;
57
58         assert(cd);
59
60         r = crypt_activate_by_passphrase(cd, NULL, keyslot,
61                                          passphrase, passphrase_len, 0);
62         check_signal(&r);
63         tools_passphrase_msg(r);
64         tools_keyslot_msg(r, UNLOCKED);
65
66         return r;
67 }
68
69 static int set_keyslot_params(struct crypt_device *cd, int keyslot)
70 {
71         const char *cipher;
72         struct crypt_pbkdf_type pbkdf;
73         size_t key_size;
74
75         cipher = crypt_keyslot_get_encryption(cd, keyslot, &key_size);
76         if (!cipher)
77                 return -EINVAL;
78
79         if (crypt_is_cipher_null(cipher)) {
80                 log_dbg("Keyslot %d uses cipher_null. "
81                         "Replacing with default encryption in new keyslot.", keyslot);
82                 cipher = DEFAULT_LUKS2_KEYSLOT_CIPHER;
83                 key_size = DEFAULT_LUKS2_KEYSLOT_KEYBITS / 8;
84         }
85
86         if (crypt_keyslot_set_encryption(cd, cipher, key_size))
87                 return -EINVAL;
88
89         /* if requested any of those just reinitialize context pbkdf */
90         if (set_pbkdf || ARG_SET(OPT_HASH_ID) || ARG_SET(OPT_PBKDF_FORCE_ITERATIONS_ID) ||
91             ARG_SET(OPT_ITER_TIME_ID))
92                 return set_pbkdf_params(cd, CRYPT_LUKS2);
93
94         if (crypt_keyslot_get_pbkdf(cd, keyslot, &pbkdf))
95                 return -EINVAL;
96
97         pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK;
98
99         return crypt_set_pbkdf_type(cd, &pbkdf);
100 }
101
102 static int get_active_device_name(struct crypt_device *cd,
103         const char *data_device,
104         char **r_active_name)
105 {
106         char *msg;
107         int r;
108
109         assert(data_device);
110
111         r = tools_lookup_crypt_device(cd, crypt_get_type(cd), data_device, r_active_name);
112         if (r > 0) {
113                 log_dbg("Device %s has %d active holders.", data_device, r);
114
115                 if (!*r_active_name) {
116                         log_err(_("Device %s is still in use."), data_device);
117                         return -EINVAL;
118                 }
119                 if (!ARG_SET(OPT_BATCH_MODE_ID))
120                         log_std(_("Auto-detected active dm device '%s' for data device %s.\n"),
121                                 *r_active_name, data_device);
122         } else if (r < 0) {
123                 if (r != -ENOTBLK) {
124                         log_err(_("Failed to auto-detect device %s holders."), data_device);
125                         return -EINVAL;
126                 }
127
128                 r = -EINVAL;
129                 if (!ARG_SET(OPT_BATCH_MODE_ID)) {
130                         log_std(_("Device %s is not a block device.\n"), data_device);
131
132                         r = asprintf(&msg, _("Unable to decide if device %s is activated or not.\n"
133                                              "Are you sure you want to proceed with reencryption in offline mode?\n"
134                                              "It may lead to data corruption if the device is actually activated.\n"
135                                              "To run reencryption in online mode, use --active-name parameter instead.\n"), data_device);
136                         if (r < 0)
137                                 return -ENOMEM;
138                         r = noDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
139                         free(msg);
140                 } else {
141                         log_err(_("Device %s is not a block device. Can not auto-detect if it is active or not.\n"
142                                 "Use --force-offline-reencrypt to bypass the check and run in offline mode (dangerous!)."), data_device);
143                 }
144         } else {
145                 *r_active_name = NULL;
146                 log_dbg("Device %s is unused. Proceeding with offline reencryption.", data_device);
147         }
148
149         return r;
150 }
151
152 static int reencrypt_get_active_name(struct crypt_device *cd,
153         const char *data_device,
154         char **r_active_name)
155 {
156         assert(cd);
157         assert(r_active_name);
158
159         if (ARG_SET(OPT_ACTIVE_NAME_ID))
160                 return (*r_active_name = strdup(ARG_STR(OPT_ACTIVE_NAME_ID))) ? 0 : -ENOMEM;
161
162         return get_active_device_name(cd, data_device, r_active_name);
163 }
164
165 static int decrypt_verify_and_set_params(struct crypt_params_reencrypt *params)
166 {
167         const char *resilience;
168
169         assert(params);
170
171         if (!ARG_SET(OPT_RESILIENCE_ID))
172                 return 0;
173
174         resilience = ARG_STR(OPT_RESILIENCE_ID);
175
176         if (!strcmp(resilience, "datashift") ||
177             !strcmp(resilience, "none")) {
178                 log_err(_("Requested --resilience option cannot be applied "
179                           "to current reencryption operation."));
180                 return -EINVAL;
181         } else if (!strcmp(resilience, "journal"))
182                 params->resilience = "datashift-journal";
183         else if (!strcmp(resilience, "checksum"))
184                 params->resilience = "datashift-checksum";
185         else if (!strcmp(resilience, "datashift-checksum") ||
186                  !strcmp(resilience, "datashift-journal"))
187                 params->resilience = resilience;
188         else {
189                 log_err(_("Unsupported resilience mode %s"), resilience);
190                 return -EINVAL;
191         }
192
193         return 0;
194 }
195
196 static int reencrypt_verify_and_update_params(struct crypt_params_reencrypt *params,
197         char **r_hash)
198 {
199         assert(params);
200         assert(r_hash);
201
202         if (ARG_SET(OPT_ENCRYPT_ID) && params->mode != CRYPT_REENCRYPT_ENCRYPT) {
203                 log_err(_("Device is not in LUKS2 encryption. Conflicting option --encrypt."));
204                 return -EINVAL;
205         }
206
207         if (ARG_SET(OPT_DECRYPT_ID) && params->mode != CRYPT_REENCRYPT_DECRYPT) {
208                 log_err(_("Device is not in LUKS2 decryption. Conflicting option --decrypt."));
209                 return -EINVAL;
210         }
211
212         if (ARG_SET(OPT_RESILIENCE_ID)) {
213                 if (!strcmp(params->resilience, "datashift") &&
214                     strcmp(ARG_STR(OPT_RESILIENCE_ID), "datashift")) {
215                         log_err(_("Device is in reencryption using datashift resilience. "
216                                   "Requested --resilience option cannot be applied."));
217                         return -EINVAL;
218                 }
219                 if (strcmp(params->resilience, "datashift") &&
220                     !strcmp(ARG_STR(OPT_RESILIENCE_ID), "datashift")) {
221                         log_err(_("Requested --resilience option cannot be applied "
222                                   "to current reencryption operation."));
223                         return -EINVAL;
224                 }
225
226                 if (!strncmp(params->resilience, "datashift-", 10)) {
227                         /* decryption with datashift in progress */
228                         if (decrypt_verify_and_set_params(params))
229                                 return -EINVAL;
230                 } else if (!strncmp(ARG_STR(OPT_RESILIENCE_ID), "datashift-", 10)) {
231                         log_err(_("Requested --resilience option cannot be applied "
232                                   "to current reencryption operation."));
233                         return -EINVAL;
234                 } else
235                         params->resilience = ARG_STR(OPT_RESILIENCE_ID);
236
237                 /* we have to copy hash string returned by API */
238                 if (params->hash && !ARG_SET(OPT_RESILIENCE_HASH_ID)) {
239                         /* r_hash owns the memory. Freed by caller */
240                         *r_hash = strdup(params->hash);
241                         if (!*r_hash)
242                                 return -ENOMEM;
243                         params->hash = *r_hash;
244                 }
245
246                 /* Add default hash when switching to checksum based resilience */
247                 if (!params->hash && !ARG_SET(OPT_RESILIENCE_HASH_ID) &&
248                     (!strcmp(params->resilience, "checksum") ||
249                     !strcmp(params->resilience, "datashift-checksum")))
250                         params->hash = "sha256";
251
252                 if (ARG_SET(OPT_RESILIENCE_HASH_ID))
253                         params->hash = ARG_STR(OPT_RESILIENCE_HASH_ID);
254         } else
255                 params->resilience = NULL;
256
257         params->max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE;
258         params->device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE;
259         params->flags = CRYPT_REENCRYPT_RESUME_ONLY;
260
261         return 0;
262 }
263
264 static int reencrypt_hint_force_offline_reencrypt(const char *data_device)
265 {
266         struct stat st;
267
268         if (ARG_SET(OPT_ACTIVE_NAME_ID) ||
269             !ARG_SET(OPT_BATCH_MODE_ID) ||
270             ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
271                 return 0;
272
273         if (stat(data_device, &st) == 0 && S_ISREG(st.st_mode)) {
274                 log_err(_("Device %s is not a block device. Can not auto-detect if it is active or not.\n"
275                         "Use --force-offline-reencrypt to bypass the check and run in offline mode (dangerous!)."), data_device);
276                 return -EINVAL;
277         }
278
279         return 0;
280 }
281
282 static int reencrypt_luks2_load(struct crypt_device *cd, const char *data_device)
283 {
284         char *msg;
285         crypt_reencrypt_info ri;
286         int r;
287         size_t passwordLen;
288         char *active_name = NULL, *hash = NULL, *password = NULL;
289         struct crypt_params_reencrypt params = {};
290
291         ri = crypt_reencrypt_status(cd, &params);
292         if (ri == CRYPT_REENCRYPT_CRASH)
293                 log_err(_("Device requires reencryption recovery. Run repair first."));
294
295         if (ri != CRYPT_REENCRYPT_CLEAN)
296                 return -EINVAL;
297
298         r = reencrypt_verify_and_update_params(&params, &hash);
299         if (r < 0)
300                 return r;
301
302         r = reencrypt_hint_force_offline_reencrypt(data_device);
303         if (r < 0)
304                 goto out;
305
306         if (!ARG_SET(OPT_BATCH_MODE_ID) && !ARG_SET(OPT_RESUME_ONLY_ID)) {
307                 r = asprintf(&msg, _("Device %s is already in LUKS2 reencryption. "
308                                      "Do you wish to resume previously initialised operation?"),
309                              crypt_get_metadata_device_name(cd) ?: data_device);
310                 if (r < 0) {
311                         r = -ENOMEM;
312                         goto out;
313                 }
314                 r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
315                 free(msg);
316                 if (r < 0)
317                         goto out;
318         }
319
320         r = tools_get_key(NULL, &password, &passwordLen,
321                         ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID),
322                         ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID),
323                         verify_passphrase(0), 0, cd);
324         if (r < 0)
325                 goto out;
326
327         if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
328                 r = reencrypt_get_active_name(cd, data_device, &active_name);
329         if (r >= 0)
330                 r = crypt_reencrypt_init_by_passphrase(cd, active_name, password,
331                                 passwordLen, ARG_INT32(OPT_KEY_SLOT_ID),
332                                 ARG_INT32(OPT_KEY_SLOT_ID), NULL, NULL, &params);
333 out:
334         free(hash);
335         crypt_safe_free(password);
336         free(active_name);
337         return r;
338 }
339
340 /*
341  *   1: in-progress
342  *   0: clean luks2 device
343  * < 0: error
344  */
345 static int luks2_reencrypt_in_progress(struct crypt_device *cd)
346 {
347         uint32_t flags;
348
349         if (crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &flags))
350                 return -EINVAL;
351
352         if (flags & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) {
353                 log_err(_("Legacy LUKS2 reencryption is no longer supported."));
354                 return -EINVAL;
355         }
356
357         return flags & CRYPT_REQUIREMENT_ONLINE_REENCRYPT;
358 }
359
360 /*
361  * Returns crypt context for:
362  *   DEVICE_LUKS2
363  *   DEVICE_LUKS2_REENCRYPT
364  *   DEVICE_LUKS1
365  */
366 static enum device_status_info load_luks(struct crypt_device **r_cd,
367         const char *header_device,
368         const char *data_device)
369 {
370         int r;
371         struct crypt_device *cd;
372         struct stat st;
373
374         assert(r_cd);
375         assert(data_device);
376
377         if (header_device && stat(header_device, &st) < 0 && errno == ENOENT)
378                 return DEVICE_NOT_LUKS;
379
380         if (crypt_init_data_device(&cd, uuid_or_device(header_device ?: data_device), data_device))
381                 return DEVICE_INVALID;
382
383         if ((r = crypt_load(cd, CRYPT_LUKS, NULL))) {
384                 crypt_free(cd);
385
386                 if (r == -EBUSY) /* luks2 locking error (message printed by libcryptsetup) */
387                         return DEVICE_INVALID;
388
389                 r = reencrypt_luks1_in_progress(uuid_or_device(header_device ?: data_device));
390                 if (!r)
391                         return DEVICE_LUKS1_UNUSABLE;
392
393                 return DEVICE_NOT_LUKS;
394         }
395
396         if (isLUKS2(crypt_get_type(cd))) {
397                 r = luks2_reencrypt_in_progress(cd);
398                 if (r < 0) {
399                         crypt_free(cd);
400                         return DEVICE_INVALID;
401                 }
402         }
403
404         *r_cd = cd;
405
406         if (r > 0)
407                 return DEVICE_LUKS2_REENCRYPT;
408
409         return isLUKS2(crypt_get_type(cd)) ? DEVICE_LUKS2 : DEVICE_LUKS1;
410 }
411
412 static bool luks2_reencrypt_eligible(struct crypt_device *cd)
413 {
414         struct crypt_params_integrity ip = { 0 };
415
416         /* raw integrity info is available since 2.0 */
417         if (crypt_get_integrity_info(cd, &ip) || ip.tag_size) {
418                 log_err(_("Reencryption of device with integrity profile is not supported."));
419                 return false;
420         }
421
422         return true;
423 }
424
425 static enum device_status_info check_luks_device(const char *device)
426 {
427         enum device_status_info dev_st;
428         struct crypt_device *cd = NULL;
429
430         dev_st = load_luks(&cd, NULL, device);
431         crypt_free(cd);
432
433         return dev_st;
434 }
435
436 static int reencrypt_check_data_sb_block_size(const char *data_device, uint32_t new_sector_size)
437 {
438         int r;
439         char sb_name[32];
440         unsigned block_size;
441
442         assert(data_device);
443
444         r = tools_superblock_block_size(data_device, sb_name, sizeof(sb_name), &block_size);
445         if (r <= 0)
446                 return r;
447
448         if (new_sector_size > block_size) {
449                 log_err(_("Requested --sector-size %" PRIu32 " is incompatible with %s superblock\n"
450                           "(block size: %" PRIu32 " bytes) detected on device %s."),
451                         new_sector_size, sb_name, block_size, data_device);
452                 return -EINVAL;
453         }
454
455         return 0;
456 }
457
458 static int reencrypt_check_active_device_sb_block_size(const char *active_device, uint32_t new_sector_size)
459 {
460         int r;
461         char dm_device[PATH_MAX];
462
463         r = snprintf(dm_device, sizeof(dm_device), "%s/%s", crypt_get_dir(), active_device);
464         if (r < 0 || (size_t)r >= sizeof(dm_device))
465                 return -EINVAL;
466
467         return reencrypt_check_data_sb_block_size(dm_device, new_sector_size);
468 }
469
470 static int reencrypt_is_header_detached(const char *header_device, const char *data_device)
471 {
472         int r;
473         struct stat st;
474         struct crypt_device *cd;
475
476         if (!header_device)
477                 return 0;
478
479         if (header_device && stat(header_device, &st) < 0 && errno == ENOENT)
480                 return 1;
481
482         if ((r = crypt_init_data_device(&cd, header_device, data_device)))
483                 return r;
484
485         r = crypt_header_is_detached(cd);
486         crypt_free(cd);
487         return r;
488 }
489
490 static int encrypt_luks2_init(struct crypt_device **cd, const char *data_device, const char *device_name)
491 {
492         int keyslot, r, fd;
493         uuid_t uuid;
494         size_t passwordLen;
495         char *tmp, uuid_str[37], header_file[PATH_MAX] = { 0 }, *password = NULL;
496         uint32_t activate_flags = 0;
497         const struct crypt_params_luks2 luks2_params = {
498                 .sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: SECTOR_SIZE
499         };
500         struct crypt_params_reencrypt params = {
501                 .mode = CRYPT_REENCRYPT_ENCRYPT,
502                 .direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD,
503                 .resilience = ARG_STR(OPT_RESILIENCE_ID) ?: "checksum",
504                 .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
505                 .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
506                 .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
507                 .luks2 = &luks2_params,
508                 .flags = CRYPT_REENCRYPT_INITIALIZE_ONLY
509         };
510
511         _set_reencryption_flags(&params.flags);
512
513         if (!data_shift) {
514                 r = reencrypt_is_header_detached(ARG_STR(OPT_HEADER_ID), data_device);
515                 if (r < 0)
516                         return r;
517                 if (!r) {
518                         log_err(_("Encryption without detached header (--header) is not possible without data device size reduction (--reduce-device-size)."));
519                         return -ENOTSUP;
520                 }
521         }
522
523         if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) &&
524             data_shift && (ARG_UINT64(OPT_OFFSET_ID) > (uint64_t)(imaxabs(data_shift) / (2 * SECTOR_SIZE)))) {
525                 log_err(_("Requested data offset must be less than or equal to half of --reduce-device-size parameter."));
526                 return -EINVAL;
527         }
528
529         /* TODO: ask user to confirm. It's useless to do data device reduction and than use smaller value */
530         if (!ARG_SET(OPT_HEADER_ID) && ARG_UINT64(OPT_OFFSET_ID) &&
531             data_shift && (ARG_UINT64(OPT_OFFSET_ID) < (uint64_t)(imaxabs(data_shift) / (2 * SECTOR_SIZE)))) {
532                 data_shift = -(ARG_UINT64(OPT_OFFSET_ID) * 2 * SECTOR_SIZE);
533                 if (data_shift >= 0)
534                         return -EINVAL;
535                 log_std(_("Adjusting --reduce-device-size value to twice the --offset %" PRIu64 " (sectors).\n"), ARG_UINT64(OPT_OFFSET_ID) * 2);
536         }
537
538         if (ARG_SET(OPT_UUID_ID) && uuid_parse(ARG_STR(OPT_UUID_ID), uuid) == -1) {
539                 log_err(_("Wrong LUKS UUID format provided."));
540                 return -EINVAL;
541         }
542
543         if (ARG_SET(OPT_SECTOR_SIZE_ID)) {
544                 r = reencrypt_check_data_sb_block_size(data_device, ARG_UINT32(OPT_SECTOR_SIZE_ID));
545                 if (r < 0)
546                         return r;
547         }
548
549         if (!ARG_SET(OPT_UUID_ID)) {
550                 uuid_generate(uuid);
551                 uuid_unparse(uuid, uuid_str);
552                 if (!(tmp = strdup(uuid_str)))
553                         return -ENOMEM;
554                 ARG_SET_STR(OPT_UUID_ID, tmp);
555         }
556
557         if (!ARG_SET(OPT_HEADER_ID)) {
558                 r = snprintf(header_file, sizeof(header_file), "LUKS2-temp-%s.new", ARG_STR(OPT_UUID_ID));
559                 if (r < 0 || (size_t)r >= sizeof(header_file))
560                         return -EINVAL;
561
562                 fd = open(header_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
563                 if (fd == -1) {
564                         if (errno == EEXIST)
565                                 log_err(_("Temporary header file %s already exists. Aborting."), header_file);
566                         else
567                                 log_err(_("Cannot create temporary header file %s."), header_file);
568                         return -EINVAL;
569                 }
570
571                 r = posix_fallocate(fd, 0, 4096);
572                 close(fd);
573                 if (r) {
574                         log_err(_("Cannot create temporary header file %s."), header_file);
575                         r = -EINVAL;
576                         goto out;
577                 }
578
579                 if (!(tmp = strdup(header_file))) {
580                         r = -ENOMEM;
581                         goto out;
582                 }
583                 ARG_SET_STR(OPT_HEADER_ID, tmp);
584
585                 /*
586                  * FIXME: just override offset here, but we should support both.
587                  * offset and implicit offset via data shift (lvprepend?)
588                  */
589                 if (!ARG_UINT64(OPT_OFFSET_ID))
590                         ARG_SET_UINT64(OPT_OFFSET_ID, imaxabs(data_shift) / (2 * SECTOR_SIZE));
591                 data_shift >>= 1;
592                 params.flags |= CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT;
593         } else if (data_shift < 0) {
594                 if (!ARG_SET(OPT_LUKS2_METADATA_SIZE_ID))
595                         ARG_SET_UINT64(OPT_LUKS2_METADATA_SIZE_ID, 0x4000); /* missing default here */
596                 if (!ARG_SET(OPT_LUKS2_KEYSLOTS_SIZE_ID))
597                         ARG_SET_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID, -data_shift - 2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID));
598                 if (2 * ARG_UINT64(OPT_LUKS2_METADATA_SIZE_ID) + ARG_UINT64(OPT_LUKS2_KEYSLOTS_SIZE_ID) > (uint64_t)-data_shift) {
599                         log_err(_("LUKS2 metadata size is larger than data shift value."));
600                         return -EINVAL;
601                 }
602         }
603
604         r = luksFormat(cd, &password, &passwordLen);
605         if (r < 0)
606                 goto out;
607
608         if (!luks2_reencrypt_eligible(*cd)) {
609                 r = -EINVAL;
610                 goto out;
611         }
612
613         if (data_shift) {
614                 params.data_shift = imaxabs(data_shift) / SECTOR_SIZE,
615                 params.resilience = "datashift";
616         }
617         keyslot = !ARG_SET(OPT_KEY_SLOT_ID) ? 0 : ARG_INT32(OPT_KEY_SLOT_ID);
618         r = crypt_reencrypt_init_by_passphrase(*cd, NULL, password, passwordLen,
619                         CRYPT_ANY_SLOT, keyslot, crypt_get_cipher(*cd),
620                         crypt_get_cipher_mode(*cd), &params);
621         if (r < 0) {
622                 crypt_keyslot_destroy(*cd, keyslot);
623                 goto out;
624         }
625
626         /* Restore temporary header in head of data device */
627         if (*header_file) {
628                 crypt_free(*cd);
629                 *cd = NULL;
630
631                 r = crypt_init(cd, data_device);
632                 if (!r)
633                         r = crypt_header_restore(*cd, CRYPT_LUKS2, header_file);
634
635                 if (r) {
636                         log_err(_("Failed to place new header at head of device %s."), data_device);
637                         goto out;
638                 }
639         }
640
641         /* activate device */
642         if (device_name) {
643                 set_activation_flags(&activate_flags);
644                 r = crypt_activate_by_passphrase(*cd, device_name, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen, activate_flags);
645                 if (r >= 0)
646                         log_std(_("%s/%s is now active and ready for online encryption.\n"), crypt_get_dir(), device_name);
647         }
648
649         if (r < 0)
650                 goto out;
651
652         /* just load reencryption context to continue reencryption */
653         if (!ARG_SET(OPT_INIT_ONLY_ID)) {
654                 params.flags &= ~CRYPT_REENCRYPT_INITIALIZE_ONLY;
655                 r = crypt_reencrypt_init_by_passphrase(*cd, device_name, password, passwordLen,
656                                 CRYPT_ANY_SLOT, keyslot, NULL, NULL, &params);
657         }
658 out:
659         crypt_safe_free(password);
660         if (*header_file)
661                 unlink(header_file);
662         return r;
663 }
664
665 static enum device_status_info load_luks2_by_name(struct crypt_device **r_cd, const char *active_name, const char *header_device)
666 {
667         int r;
668         struct crypt_device *cd;
669         struct stat st;
670
671         assert(r_cd);
672         assert(active_name);
673
674         if (header_device && stat(header_device, &st) < 0 && errno == ENOENT)
675                 return DEVICE_NOT_LUKS;
676
677         r = crypt_init_by_name_and_header(&cd, active_name, header_device);
678         if (r)
679                 return DEVICE_INVALID;
680
681         if (!isLUKS2(crypt_get_type(cd))) {
682                 log_err(_("Active device %s is not LUKS2."), active_name);
683                 crypt_free(cd);
684                 return DEVICE_INVALID;
685         }
686
687         r = luks2_reencrypt_in_progress(cd);
688         if (r < 0) {
689                 crypt_free(cd);
690                 return DEVICE_INVALID;
691         }
692
693         *r_cd = cd;
694
695         return !r ? DEVICE_LUKS2 : DEVICE_LUKS2_REENCRYPT;
696 }
697
698 static int reencrypt_restore_header(struct crypt_device **cd,
699         const char *data_device, const char *header)
700 {
701         int r;
702
703         assert(cd);
704         assert(data_device);
705         assert(header);
706
707         crypt_free(*cd);
708         *cd = NULL;
709
710         log_verbose(_("Restoring original LUKS2 header."));
711
712         r = crypt_init(cd, data_device);
713         if (r < 0)
714                 return r;
715
716         r = crypt_header_restore(*cd, CRYPT_LUKS2, header);
717         if (r < 0)
718                 log_err(_("Original LUKS2 header restore failed."));
719
720         return r;
721 }
722
723 static int decrypt_luks2_datashift_init(struct crypt_device **cd,
724         const char *data_device,
725         const char *expheader)
726 {
727         int fd, r;
728         size_t passwordLen;
729         struct stat hdr_st;
730         bool remove_header = false;
731         char *msg, *active_name = NULL, *password = NULL;
732         struct crypt_params_reencrypt params = {
733                 .mode = CRYPT_REENCRYPT_DECRYPT,
734                 .direction = CRYPT_REENCRYPT_FORWARD,
735                 .resilience = "datashift-checksum",
736                 .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
737                 .data_shift = crypt_get_data_offset(*cd),
738                 .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
739                 .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
740                 .flags = CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT
741         };
742
743         if (!ARG_SET(OPT_BATCH_MODE_ID)) {
744                 r = asprintf(&msg, _("Header file %s does not exist. Do you want to initialize LUKS2 "
745                                      "decryption of device %s and export LUKS2 header to file %s?"),
746                              expheader, data_device, expheader);
747                 if (r < 0)
748                         return -ENOMEM;
749                 r = yesDialog(msg, _("Operation aborted.\n")) ? 0 : -EINVAL;
750                 free(msg);
751                 if (r < 0)
752                         return r;
753         }
754
755         if ((r = decrypt_verify_and_set_params(&params)))
756                 return r;
757
758         r = reencrypt_hint_force_offline_reencrypt(data_device);
759         if (r < 0)
760                 return r;
761
762         r = tools_get_key(NULL, &password, &passwordLen,
763                         ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID),
764                         ARG_STR(OPT_KEY_FILE_ID), ARG_UINT32(OPT_TIMEOUT_ID),
765                         verify_passphrase(0), 0, *cd);
766         if (r < 0)
767                 return r;
768
769         r = reencrypt_check_passphrase(*cd, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen);
770         if (r < 0)
771                 goto out;
772
773         r = crypt_header_backup(*cd, CRYPT_LUKS2, expheader);
774         if (r < 0)
775                 goto out;
776
777         remove_header = true;
778
779         fd = open(expheader, O_RDONLY);
780         if (fd < 0)
781                 goto out;
782
783         if (fstat(fd, &hdr_st)) {
784                 close(fd);
785                 r = -EINVAL;
786                 goto out;
787         }
788
789         r = fchmod(fd, hdr_st.st_mode  | S_IRUSR | S_IWUSR);
790         close(fd);
791         if (r) {
792                 log_err(_("Failed to add read/write permissions to exported header file."));
793                 r = -EINVAL;
794                 goto out;
795         }
796
797         crypt_free(*cd);
798         *cd = NULL;
799
800         /* reload with exported header */
801         if (ARG_SET(OPT_ACTIVE_NAME_ID)) {
802                 if (load_luks2_by_name(cd, ARG_STR(OPT_ACTIVE_NAME_ID), expheader) != DEVICE_LUKS2) {
803                         r = -EINVAL;
804                         goto out;
805                 }
806         } else {
807                 if ((r = crypt_init_data_device(cd, expheader, data_device)))
808                         goto out;
809                 if ((r = crypt_load(*cd, CRYPT_LUKS2, NULL)))
810                         goto out;
811         }
812
813         _set_reencryption_flags(&params.flags);
814
815         if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
816                 r = reencrypt_get_active_name(*cd, data_device, &active_name);
817
818         if (r < 0)
819                 goto out;
820
821         r = tools_wipe_all_signatures(data_device, active_name == NULL, true);
822         if (r < 0) {
823                 /* if header restore fails keep original header backup */
824                 if (reencrypt_restore_header(cd, data_device, expheader) < 0)
825                         remove_header = false;
826                 goto out;
827         }
828
829         remove_header = false;
830
831         r = crypt_reencrypt_init_by_passphrase(*cd, active_name, password,
832                         passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), CRYPT_ANY_SLOT,
833                         NULL, NULL, &params);
834
835         if (r < 0 && crypt_reencrypt_status(*cd, NULL) == CRYPT_REENCRYPT_NONE) {
836                 /* if restore is successful we can remove header backup */
837                 if (!reencrypt_restore_header(cd, data_device, expheader))
838                         remove_header = true;
839         }
840 out:
841         free(active_name);
842         crypt_safe_free(password);
843
844         if (r < 0 && !remove_header && !stat(expheader, &hdr_st) && S_ISREG(hdr_st.st_mode))
845                 log_err(_("Reencryption initialization failed. Header backup is available in %s."),
846                         expheader);
847         if (remove_header)
848                 unlink(expheader);
849
850         return r;
851 }
852
853 static int decrypt_luks2_init(struct crypt_device *cd, const char *data_device)
854 {
855         int r;
856         size_t passwordLen;
857         char *active_name = NULL, *password = NULL;
858         struct crypt_params_reencrypt params = {
859                 .mode = CRYPT_REENCRYPT_DECRYPT,
860                 .direction = data_shift > 0 ? CRYPT_REENCRYPT_FORWARD : CRYPT_REENCRYPT_BACKWARD,
861                 .resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"),
862                 .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
863                 .data_shift = imaxabs(data_shift) / SECTOR_SIZE,
864                 .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
865                 .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
866         };
867
868         if (!luks2_reencrypt_eligible(cd))
869                 return -EINVAL;
870
871         if ((!crypt_get_metadata_device_name(cd) || crypt_header_is_detached(cd) <= 0 ||
872             crypt_get_data_offset(cd) > 0)) {
873                 log_err(_("LUKS2 decryption is supported with detached header device only (with data offset set to 0)."));
874                 return -ENOTSUP;
875         }
876
877         r = reencrypt_hint_force_offline_reencrypt(data_device);
878         if (r < 0)
879                 return r;
880
881         _set_reencryption_flags(&params.flags);
882
883         r = tools_get_key(NULL, &password, &passwordLen,
884                         ARG_UINT64(OPT_KEYFILE_OFFSET_ID), ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID),
885                         ARG_UINT32(OPT_TIMEOUT_ID), verify_passphrase(0), 0, cd);
886         if (r < 0)
887                 return r;
888
889         r = reencrypt_check_passphrase(cd, ARG_INT32(OPT_KEY_SLOT_ID), password, passwordLen);
890         if (r < 0)
891                 goto out;
892
893         if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID))
894                 r = reencrypt_get_active_name(cd, data_device, &active_name);
895         if (r >= 0)
896                 r = crypt_reencrypt_init_by_passphrase(cd, active_name, password,
897                                 passwordLen, ARG_INT32(OPT_KEY_SLOT_ID), CRYPT_ANY_SLOT, NULL, NULL, &params);
898
899 out:
900         free(active_name);
901         crypt_safe_free(password);
902         return r;
903 }
904
905 struct keyslot_passwords {
906         char *password;
907         size_t passwordLen;
908         int new;
909 };
910
911 static struct keyslot_passwords *init_keyslot_passwords(size_t count)
912 {
913         size_t i;
914         struct keyslot_passwords *tmp = calloc(count, sizeof(struct keyslot_passwords));
915
916         if (!tmp)
917                 return tmp;
918
919         for (i = 0; i < count; i++)
920                 tmp[i].new = -1;
921
922         return tmp;
923 }
924
925 static int init_passphrase(struct keyslot_passwords *kp, size_t keyslot_passwords_length,
926                            struct crypt_device *cd, const char *msg, int slot_to_check)
927 {
928         crypt_keyslot_info ki;
929         char *password;
930         int r = -EINVAL, retry_count;
931         size_t passwordLen;
932
933         if (slot_to_check != CRYPT_ANY_SLOT) {
934                 ki = crypt_keyslot_status(cd, slot_to_check);
935                 if (ki < CRYPT_SLOT_ACTIVE || ki == CRYPT_SLOT_UNBOUND)
936                         return -ENOENT;
937         }
938
939         retry_count = set_tries_tty();
940
941         while (retry_count--) {
942                 r = tools_get_key(msg,  &password, &passwordLen, 0, 0,
943                                   ARG_STR(OPT_KEY_FILE_ID), 0, 0, 0 /*pwquality*/, cd);
944                 if (r < 0)
945                         return r;
946                 if (quit) {
947                         crypt_safe_free(password);
948                         password = NULL;
949                         passwordLen = 0;
950                         return -EAGAIN;
951                 }
952
953                 r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
954                                                  password, passwordLen, 0);
955                 if (r < 0) {
956                         crypt_safe_free(password);
957                         password = NULL;
958                         passwordLen = 0;
959                 }
960                 if (r < 0 && r != -EPERM)
961                         return r;
962
963                 if (r >= 0) {
964                         tools_keyslot_msg(r, UNLOCKED);
965                         if ((size_t)r >= keyslot_passwords_length) {
966                                 crypt_safe_free(password);
967                                 return -EINVAL;
968                         }
969                         kp[r].password = password;
970                         kp[r].passwordLen = passwordLen;
971                         break;
972                 }
973                 tools_passphrase_msg(r);
974         }
975
976         password = NULL;
977         passwordLen = 0;
978
979         return r;
980 }
981
982 static int _check_luks2_keyslots(struct crypt_device *cd, bool vk_change)
983 {
984         int i, new_vk_slot = (vk_change ? 1 : 0), max = crypt_keyslot_max(CRYPT_LUKS2), active = 0, unbound = 0;
985
986         if (max < 0)
987                 return max;
988
989         for (i = 0; i < max; i++) {
990                 switch (crypt_keyslot_status(cd, i)) {
991                 case CRYPT_SLOT_INVALID:
992                         return -EINVAL;
993                 case CRYPT_SLOT_ACTIVE:
994                         /* fall-through */
995                 case CRYPT_SLOT_ACTIVE_LAST:
996                         active++;
997                         break;
998                 case CRYPT_SLOT_UNBOUND:
999                         unbound++;
1000                         /* fall-through */
1001                 default:
1002                         break;
1003                 }
1004         }
1005
1006         /* at least one keyslot for reencryption plus new volume key (if needed) */
1007         if (active + unbound + new_vk_slot + 1 > max) {
1008                 log_err(_("Not enough free keyslots for reencryption."));
1009                 return -EINVAL;
1010         }
1011
1012         if (!vk_change)
1013                 return 0;
1014
1015         if ((ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) &&
1016             (2 * active + unbound + 1 > max)) {
1017                 log_err(_("Not enough free keyslots for reencryption."));
1018                 return -EINVAL;
1019         }
1020
1021         return 0;
1022 }
1023
1024 static int fill_keyslot_passwords(struct crypt_device *cd,
1025                 struct keyslot_passwords *kp, size_t kp_size,
1026                 bool vk_change)
1027 {
1028         char msg[128];
1029         crypt_keyslot_info ki;
1030         int i, r = 0;
1031
1032         if (vk_change && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT && ARG_SET(OPT_KEY_FILE_ID)) {
1033                 for (i = 0; (size_t)i < kp_size; i++) {
1034                         ki = crypt_keyslot_status(cd, i);
1035                         if (ki == CRYPT_SLOT_INVALID)
1036                                 return -EINVAL;
1037                         if (ki == CRYPT_SLOT_ACTIVE) {
1038                                 log_err(_("Key file can be used only with --key-slot or with "
1039                                           "exactly one key slot active."));
1040                                 return -EINVAL;
1041                         }
1042                 }
1043         }
1044
1045         if (ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT) {
1046                 for (i = 0; (size_t)i < kp_size; i++) {
1047                         if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i) < 0)
1048                                 return -EINVAL;
1049                         r = init_passphrase(kp, kp_size, cd, msg, i);
1050                         /* no need to initialize all keyslots with --keep-key */
1051                         if (r >= 0 && !vk_change)
1052                                 break;
1053                         if (r == -ENOENT)
1054                                 r = 0;
1055                         if (r < 0)
1056                                 break;
1057                 }
1058         } else {
1059                 if (snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %u: "), ARG_INT32(OPT_KEY_SLOT_ID)) < 0)
1060                         return -EINVAL;
1061                 r = init_passphrase(kp, kp_size, cd, msg, ARG_INT32(OPT_KEY_SLOT_ID));
1062         }
1063
1064         return r < 0 ? r : 0;
1065 }
1066
1067 static int assign_tokens(struct crypt_device *cd, int keyslot_old, int keyslot_new)
1068 {
1069         int token = 0, r = crypt_token_is_assigned(cd, token, keyslot_old);
1070
1071         while (r != -EINVAL) {
1072                 if (!r && (token != crypt_token_assign_keyslot(cd, token, keyslot_new)))
1073                         return -EINVAL;
1074                 token++;
1075                 r = crypt_token_is_assigned(cd, token, keyslot_old);
1076         }
1077
1078         /* we reached max token number, exit */
1079         return 0;
1080 }
1081
1082 static int reencrypt_luks2_init(struct crypt_device *cd, const char *data_device)
1083 {
1084         bool vk_size_change, sector_size_change, sector_size_increase, vk_change;
1085         size_t i, vk_size, kp_size;
1086         int r, keyslot_old = CRYPT_ANY_SLOT, keyslot_new = CRYPT_ANY_SLOT, key_size;
1087         char cipher[MAX_CIPHER_LEN], mode[MAX_CIPHER_LEN], *vk = NULL, *active_name = NULL;
1088         const char *new_cipher = NULL;
1089         struct keyslot_passwords *kp = NULL;
1090         struct crypt_params_luks2 luks2_params = {};
1091         struct crypt_params_reencrypt params = {
1092                 .mode = CRYPT_REENCRYPT_REENCRYPT,
1093                 .direction = data_shift < 0 ? CRYPT_REENCRYPT_BACKWARD : CRYPT_REENCRYPT_FORWARD,
1094                 .resilience = data_shift ? "datashift" : (ARG_STR(OPT_RESILIENCE_ID) ?: "checksum"),
1095                 .hash = ARG_STR(OPT_RESILIENCE_HASH_ID) ?: "sha256",
1096                 .data_shift = imaxabs(data_shift) / SECTOR_SIZE,
1097                 .max_hotzone_size = ARG_UINT64(OPT_HOTZONE_SIZE_ID) / SECTOR_SIZE,
1098                 .device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID) / SECTOR_SIZE,
1099                 .luks2 = &luks2_params,
1100         };
1101
1102         if (!luks2_reencrypt_eligible(cd))
1103                 return -EINVAL;
1104
1105         _set_reencryption_flags(&params.flags);
1106
1107         /* cipher */
1108         if (ARG_SET(OPT_CIPHER_ID))
1109                 new_cipher = ARG_STR(OPT_CIPHER_ID);
1110         else if (!ARG_SET(OPT_CIPHER_ID) && crypt_is_cipher_null(crypt_get_cipher(cd))) {
1111                 log_std(_("Switching data encryption cipher to %s.\n"), DEFAULT_CIPHER(LUKS1));
1112                 new_cipher = DEFAULT_CIPHER(LUKS1);
1113         }
1114
1115         if (!new_cipher) {
1116                 strncpy(cipher, crypt_get_cipher(cd), MAX_CIPHER_LEN - 1);
1117                 strncpy(mode, crypt_get_cipher_mode(cd), MAX_CIPHER_LEN - 1);
1118                 cipher[MAX_CIPHER_LEN-1] = '\0';
1119                 mode[MAX_CIPHER_LEN-1] = '\0';
1120         } else {
1121                 if ((r = crypt_parse_name_and_mode(new_cipher, cipher, NULL, mode))) {
1122                         log_err(_("No known cipher specification pattern detected."));
1123                         return r;
1124                 }
1125
1126                 /* the segment cipher is identical with existing one */
1127                 if (!strcmp(cipher, crypt_get_cipher(cd)) && !strcmp(mode, crypt_get_cipher_mode(cd)))
1128                         new_cipher = NULL;
1129         }
1130
1131         /* sector size */
1132         luks2_params.sector_size = ARG_UINT32(OPT_SECTOR_SIZE_ID) ?: (uint32_t)crypt_get_sector_size(cd);
1133         sector_size_change = luks2_params.sector_size != (uint32_t)crypt_get_sector_size(cd);
1134         sector_size_increase = luks2_params.sector_size > (uint32_t)crypt_get_sector_size(cd);
1135
1136         /* key size */
1137         if (ARG_SET(OPT_KEY_SIZE_ID) || new_cipher)
1138                 key_size = get_adjusted_key_size(mode, DEFAULT_LUKS1_KEYBITS, 0);
1139         else
1140                 key_size = crypt_get_volume_key_size(cd);
1141
1142         if (!key_size)
1143                 return -EINVAL;
1144         vk_size = key_size;
1145
1146         vk_size_change = key_size != crypt_get_volume_key_size(cd);
1147
1148         /* volume key */
1149         vk_change = !ARG_SET(OPT_KEEP_KEY_ID);
1150
1151         if (vk_change && ARG_SET(OPT_VOLUME_KEY_FILE_ID)) {
1152                 r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &vk, key_size);
1153                 if (r < 0)
1154                         goto out;
1155
1156                 if (!crypt_volume_key_verify(cd, vk, key_size)) {
1157                         /* passed key was valid volume key */
1158                         vk_change = false;
1159                         crypt_safe_free(vk);
1160                         vk = NULL;
1161                 }
1162         }
1163
1164         if (!vk_change && !vk_size_change && !new_cipher && !sector_size_change) {
1165                 log_err(_("No data segment parameters changed. Reencryption aborted."));
1166                 r = -EINVAL;
1167                 goto out;
1168         }
1169
1170         if (!ARG_SET(OPT_INIT_ONLY_ID) || (tools_blkid_supported() && sector_size_increase)) {
1171                 r = reencrypt_hint_force_offline_reencrypt(data_device);
1172                 if (r < 0)
1173                         goto out;
1174         }
1175
1176         r = _check_luks2_keyslots(cd, vk_change);
1177         if (r)
1178                 goto out;
1179
1180         r = crypt_keyslot_max(CRYPT_LUKS2);
1181         if (r < 0)
1182                 goto out;
1183         kp_size = r;
1184
1185         kp = init_keyslot_passwords(kp_size);
1186         if (!kp) {
1187                 r = -ENOMEM;
1188                 goto out;
1189         }
1190
1191         /* coverity[overrun-call] */
1192         r = fill_keyslot_passwords(cd, kp, kp_size, vk_change);
1193         if (r)
1194                 goto out;
1195
1196         r = -ENOENT;
1197
1198         for (i = 0; i < kp_size; i++) {
1199                 if (!vk_change) {
1200                         if (kp[i].password) {
1201                                 r = keyslot_old = kp[i].new = i;
1202                                 break;
1203                         }
1204                         continue;
1205                 }
1206
1207                 if (kp[i].password && keyslot_new < 0) {
1208                         r = set_keyslot_params(cd, i);
1209                         if (r < 0)
1210                                 break;
1211                         r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size,
1212                                         kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT);
1213                         tools_keyslot_msg(r, CREATED);
1214                         if (r < 0)
1215                                 break;
1216
1217                         kp[i].new = r;
1218                         keyslot_new = r;
1219                         keyslot_old = i;
1220                         if (!vk) {
1221                                 /* key generated in crypt_keyslot_add_by_key() call above */
1222                                 vk = crypt_safe_alloc(key_size);
1223                                 if (!vk) {
1224                                         r = -ENOMEM;
1225                                         break;
1226                                 }
1227                                 r = crypt_volume_key_get(cd, keyslot_new, vk, &vk_size, kp[i].password, kp[i].passwordLen);
1228                                 if (r < 0)
1229                                         break;
1230                         }
1231                         r = assign_tokens(cd, i, r);
1232                         if (r < 0)
1233                                 break;
1234                 } else if (kp[i].password) {
1235                         r = set_keyslot_params(cd, i);
1236                         if (r < 0)
1237                                 break;
1238                         r = crypt_keyslot_add_by_key(cd, CRYPT_ANY_SLOT, vk, key_size,
1239                                         kp[i].password, kp[i].passwordLen, CRYPT_VOLUME_KEY_NO_SEGMENT | CRYPT_VOLUME_KEY_DIGEST_REUSE);
1240                         tools_keyslot_msg(r, CREATED);
1241                         if (r < 0)
1242                                 break;
1243                         kp[i].new = r;
1244                         r = assign_tokens(cd, i, r);
1245                         if (r < 0)
1246                                 break;
1247                 }
1248         }
1249
1250         if (r < 0)
1251                 goto out;
1252
1253         /*
1254          * with --init-only lookup active device only if
1255          * blkid probes are allowed and sector size increase
1256          * is requested.
1257          */
1258         if (!ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID) &&
1259             (!ARG_SET(OPT_INIT_ONLY_ID) || (tools_blkid_supported() && sector_size_increase))) {
1260                 r = reencrypt_get_active_name(cd, data_device, &active_name);
1261                 if (r < 0)
1262                         goto out;
1263         }
1264
1265         if (sector_size_increase && !active_name && tools_blkid_supported() &&
1266             !ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID)) {
1267                 log_err(_("Encryption sector size increase on offline device is not supported.\n"
1268                           "Activate the device first or use --force-offline-reencrypt option (dangerous!)."));
1269                 r = -EINVAL;
1270                 goto out;
1271         }
1272
1273         if (sector_size_increase && active_name) {
1274                 r = reencrypt_check_active_device_sb_block_size(active_name, luks2_params.sector_size);
1275                 if (r < 0)
1276                         goto out;
1277         }
1278
1279         r = crypt_reencrypt_init_by_passphrase(cd,
1280                         ARG_SET(OPT_INIT_ONLY_ID) ? NULL : active_name,
1281                         kp[keyslot_old].password, kp[keyslot_old].passwordLen,
1282                         keyslot_old, kp[keyslot_old].new, cipher, mode, &params);
1283 out:
1284         crypt_safe_free(vk);
1285         if (kp) {
1286                 for (i = 0; i < kp_size; i++) {
1287                         crypt_safe_free(kp[i].password);
1288                         if (r < 0 && kp[i].new >= 0 && kp[i].new != (int)i &&
1289                             crypt_reencrypt_status(cd, NULL) == CRYPT_REENCRYPT_NONE &&
1290                             crypt_keyslot_destroy(cd, kp[i].new))
1291                                 log_dbg("Failed to remove keyslot %d with unbound key.", kp[i].new);
1292                 }
1293                 free(kp);
1294         }
1295         free(active_name);
1296         return r;
1297 }
1298
1299 static int reencrypt_luks2_resume(struct crypt_device *cd)
1300 {
1301         int r;
1302         char *backing_file = NULL;
1303         struct tools_progress_params prog_parms = {
1304                 .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
1305                 .batch_mode = ARG_SET(OPT_BATCH_MODE_ID),
1306                 .json_output = ARG_SET(OPT_PROGRESS_JSON_ID),
1307                 .interrupt_message = _("\nReencryption interrupted."),
1308                 .device = tools_get_device_name(crypt_get_device_name(cd), &backing_file)
1309         };
1310
1311         if (ARG_SET(OPT_FORCE_OFFLINE_REENCRYPT_ID) && !ARG_SET(OPT_BATCH_MODE_ID))
1312                 log_std(_("Resuming LUKS reencryption in forced offline mode.\n"));
1313
1314         set_int_handler(0);
1315         r = crypt_reencrypt_run(cd, tools_progress, &prog_parms);
1316         free(backing_file);
1317         return r;
1318 }
1319
1320 static int check_broken_luks_signature(const char *device)
1321 {
1322         int r;
1323         size_t count;
1324
1325         r = tools_detect_signatures(device, PRB_ONLY_LUKS, &count, ARG_SET(OPT_BATCH_MODE_ID));
1326         if (r < 0)
1327                 return -EINVAL;
1328         if (count) {
1329                 log_err(_("Device %s contains broken LUKS metadata. Aborting operation."), device);
1330                 return -EINVAL;
1331         }
1332
1333         return 0;
1334 }
1335
1336 static int _encrypt(struct crypt_device *cd, const char *type, enum device_status_info dev_st, int action_argc, const char **action_argv)
1337 {
1338         const char *device_ptr;
1339         enum device_status_info data_dev_st;
1340         struct stat st;
1341         struct crypt_device *encrypt_cd = NULL;
1342         int r = -EINVAL;
1343
1344         if (dev_st == DEVICE_LUKS2 || dev_st == DEVICE_LUKS1) {
1345                 log_err(_("Device %s is already LUKS device. Aborting operation."),
1346                         uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
1347                 return -EINVAL;
1348         }
1349
1350         if (dev_st == DEVICE_NOT_LUKS &&
1351             (!ARG_SET(OPT_HEADER_ID) || !stat(ARG_STR(OPT_HEADER_ID), &st))) {
1352                 device_ptr = ARG_SET(OPT_HEADER_ID) ? ARG_STR(OPT_HEADER_ID) : action_argv[0];
1353                 r = check_broken_luks_signature(device_ptr);
1354                 if (r < 0)
1355                         return r;
1356         }
1357
1358         /* check data device type/state */
1359         if (ARG_SET(OPT_HEADER_ID)) {
1360                 device_ptr = cd ? crypt_get_device_name(cd) : action_argv[0];
1361                 data_dev_st = check_luks_device(device_ptr);
1362
1363                 if (data_dev_st == DEVICE_INVALID)
1364                         return -EINVAL;
1365
1366                 if (data_dev_st == DEVICE_LUKS2 || data_dev_st == DEVICE_LUKS1) {
1367                         log_err(_("Device %s is already LUKS device. Aborting operation."),
1368                                 device_ptr);
1369                         return -EINVAL;
1370                 }
1371
1372                 if (data_dev_st == DEVICE_LUKS2_REENCRYPT || data_dev_st == DEVICE_LUKS1_UNUSABLE) {
1373                         log_err(_("Device %s is already in LUKS reencryption. Aborting operation."),
1374                                 device_ptr);
1375                         return -EINVAL;
1376                 }
1377
1378                 r = check_broken_luks_signature(device_ptr);
1379                 if (r < 0)
1380                         return r;
1381         }
1382
1383         if (!type)
1384                 type = crypt_get_default_type();
1385
1386         if (dev_st == DEVICE_LUKS1_UNUSABLE || isLUKS1(type)) {
1387                 r = reencrypt_is_header_detached(ARG_STR(OPT_HEADER_ID), action_argv[0]);
1388                 if (r < 0)
1389                         return r;
1390                 if (!r && !ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID)) {
1391                         log_err(_("Encryption without detached header (--header) is not possible without data device size reduction (--reduce-device-size)."));
1392                         return -ENOTSUP;
1393                 }
1394                 return reencrypt_luks1(action_argv[0]);
1395         } else if (dev_st == DEVICE_NOT_LUKS) {
1396                 r = encrypt_luks2_init(&encrypt_cd, action_argv[0], action_argc > 1 ? action_argv[1] : NULL);
1397                 if (r < 0 || ARG_SET(OPT_INIT_ONLY_ID)) {
1398                         crypt_free(encrypt_cd);
1399                         return r;
1400                 }
1401                 cd = encrypt_cd;
1402                 dev_st = DEVICE_LUKS2_REENCRYPT;
1403         } else if (dev_st == DEVICE_LUKS2_REENCRYPT &&
1404                    (r = reencrypt_luks2_load(cd, action_argv[0])) < 0)
1405                 return r;
1406
1407         if (dev_st != DEVICE_LUKS2_REENCRYPT)
1408                 return -EINVAL;
1409
1410         r = reencrypt_luks2_resume(cd);
1411
1412         crypt_free(encrypt_cd);
1413         return r;
1414 }
1415
1416 static int _decrypt(struct crypt_device **cd, enum device_status_info dev_st, const char *data_device)
1417 {
1418         int r;
1419         struct stat st;
1420         bool export_header = false;
1421
1422         assert(cd);
1423
1424         if (dev_st == DEVICE_LUKS1 || dev_st == DEVICE_LUKS1_UNUSABLE)
1425                 return reencrypt_luks1(data_device);
1426
1427         /* header file does not exist, try loading device type from data device */
1428         if (dev_st == DEVICE_NOT_LUKS && ARG_SET(OPT_HEADER_ID) &&
1429             (stat(ARG_STR(OPT_HEADER_ID), &st) < 0) && errno == ENOENT) {
1430                 if (ARG_SET(OPT_ACTIVE_NAME_ID))
1431                         dev_st = load_luks2_by_name(cd, ARG_STR(OPT_ACTIVE_NAME_ID), NULL);
1432                 else
1433                         dev_st = load_luks(cd, NULL, uuid_or_device(data_device));
1434
1435                 /*
1436                  * If data device is not LUKS2 report 'header is missing' error
1437                  * message user would get originally.
1438                  */
1439                 if (dev_st != DEVICE_LUKS2) {
1440                         log_err(_("Device %s does not exist or access denied."),
1441                                 ARG_STR(OPT_HEADER_ID));
1442                         return -EINVAL;
1443                 }
1444
1445                 export_header = true;
1446         }
1447
1448         if (dev_st == DEVICE_LUKS2_REENCRYPT) {
1449                 if ((r = reencrypt_luks2_load(*cd, data_device)) < 0)
1450                         return r;
1451         } else if (dev_st == DEVICE_LUKS2) {
1452                 if (!ARG_SET(OPT_HEADER_ID)) {
1453                         log_err(_("LUKS2 decryption requires --header option."));
1454                         return -EINVAL;
1455                 }
1456
1457                 if (export_header)
1458                         r = decrypt_luks2_datashift_init(cd, data_device, ARG_STR(OPT_HEADER_ID));
1459                 else
1460                         r = decrypt_luks2_init(*cd, data_device);
1461
1462                 if (r < 0 || ARG_SET(OPT_INIT_ONLY_ID))
1463                         return r;
1464         } else if (dev_st == DEVICE_NOT_LUKS) {
1465                 log_err(_("Device %s is not a valid LUKS device."),
1466                         ARG_STR(OPT_HEADER_ID) ?: uuid_or_device(data_device));
1467                 return -EINVAL;
1468         }
1469
1470         r = reencrypt_luks2_resume(*cd);
1471         return r;
1472 }
1473
1474 static int _reencrypt(struct crypt_device *cd, enum device_status_info dev_st, const char *data_device)
1475 {
1476         int r;
1477
1478         if (dev_st == DEVICE_LUKS1 || dev_st == DEVICE_LUKS1_UNUSABLE)
1479                 return reencrypt_luks1(data_device);
1480         else if (dev_st == DEVICE_LUKS2_REENCRYPT) {
1481                 if ((r = reencrypt_luks2_load(cd, data_device)) < 0)
1482                         return r;
1483         } else if (dev_st == DEVICE_LUKS2) {
1484                 r = reencrypt_luks2_init(cd, data_device);
1485                 if (r < 0|| ARG_SET(OPT_INIT_ONLY_ID))
1486                         return r;
1487         } else
1488                 return -EINVAL;
1489
1490         return reencrypt_luks2_resume(cd);
1491 }
1492
1493 int reencrypt(int action_argc, const char **action_argv)
1494 {
1495         enum device_status_info dev_st;
1496         int r = -EINVAL;
1497         struct crypt_device *cd = NULL;
1498         const char *type = luksType(device_type);
1499
1500         if (action_argc < 1 && (!ARG_SET(OPT_ACTIVE_NAME_ID) || ARG_SET(OPT_ENCRYPT_ID))) {
1501                 log_err(_("Command requires device as argument."));
1502                 return r;
1503         }
1504
1505         if (ARG_SET(OPT_ACTIVE_NAME_ID))
1506                 dev_st = load_luks2_by_name(&cd, ARG_STR(OPT_ACTIVE_NAME_ID), ARG_STR(OPT_HEADER_ID));
1507         else
1508                 dev_st = load_luks(&cd, ARG_STR(OPT_HEADER_ID), uuid_or_device(action_argv[0]));
1509
1510         if (dev_st == DEVICE_INVALID)
1511                 return r;
1512
1513         if (dev_st == DEVICE_LUKS1 && isLUKS2(type)) {
1514                 log_err(_("Conflicting versions. Device %s is LUKS1."),
1515                         uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
1516                 goto out;
1517         }
1518
1519         if (dev_st == DEVICE_LUKS1_UNUSABLE && isLUKS2(type)) {
1520                 log_err(_("Conflicting versions. Device %s is in LUKS1 reencryption."),
1521                         uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
1522                 goto out;
1523         }
1524
1525         if (dev_st == DEVICE_LUKS2 && isLUKS1(type)) {
1526                 log_err(_("Conflicting versions. Device %s is LUKS2."),
1527                         uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
1528                 goto out;
1529         }
1530
1531         if (dev_st == DEVICE_LUKS2_REENCRYPT && isLUKS1(type)) {
1532                 log_err(_("Conflicting versions. Device %s is in LUKS2 reencryption."),
1533                         uuid_or_device(ARG_STR(OPT_HEADER_ID) ?: action_argv[0]));
1534                 goto out;
1535         }
1536
1537         if (dev_st == DEVICE_LUKS2_REENCRYPT && ARG_SET(OPT_INIT_ONLY_ID)) {
1538                 log_err(_("LUKS2 reencryption already initialized. Aborting operation."));
1539                 r = -EINVAL;
1540                 goto out;
1541         }
1542
1543         if (ARG_SET(OPT_RESUME_ONLY_ID) &&
1544             (dev_st == DEVICE_LUKS2 || dev_st == DEVICE_LUKS1 || dev_st == DEVICE_NOT_LUKS)) {
1545                 log_err(_("Device reencryption not in progress."));
1546                 r = -EINVAL;
1547                 goto out;
1548         }
1549
1550         if (ARG_SET(OPT_ENCRYPT_ID))
1551                 r = _encrypt(cd, type, dev_st, action_argc, action_argv);
1552         else if (ARG_SET(OPT_DECRYPT_ID))
1553                 r = _decrypt(&cd, dev_st, action_argv[0]);
1554         else
1555                 r = _reencrypt(cd, dev_st, action_argv[0]);
1556
1557 out:
1558         crypt_free(cd);
1559         return r;
1560 }