2 * cryptsetup-reencrypt - crypt utility for offline re-encryption
4 * Copyright (C) 2012-2021 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2012-2021 Milan Broz All rights reserved.
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include "cryptsetup.h"
23 #include <sys/ioctl.h>
25 #include <arpa/inet.h>
26 #include <uuid/uuid.h>
28 #define PACKAGE_REENC "cryptsetup-reencrypt"
30 #define NO_UUID "cafecafe-cafe-cafe-cafe-cafecafeeeee"
32 static char *opt_cipher = NULL;
33 static char *opt_hash = NULL;
34 static char *opt_key_file = NULL;
35 static char *opt_master_key_file = NULL;
36 static char *opt_uuid = NULL;
37 static char *opt_type = NULL;
38 static char *opt_pbkdf = NULL;
39 static char *opt_header_device = NULL;
41 /* helper strings converted to uint64_t later */
42 static char *opt_reduce_size_str = NULL;
43 static char *opt_device_size_str = NULL;
45 static uint64_t opt_reduce_size = 0;
46 static uint64_t opt_device_size = 0;
48 static long opt_keyfile_size = 0;
49 static long opt_keyfile_offset = 0;
50 static int opt_iteration_time = 0;
51 static long opt_pbkdf_memory = DEFAULT_LUKS2_MEMORY_KB;
52 static long opt_pbkdf_parallel = DEFAULT_LUKS2_PARALLEL_THREADS;
53 static long opt_pbkdf_iterations = 0;
54 static int opt_random = 0;
55 static int opt_urandom = 0;
56 static int opt_bsize = 4;
57 static int opt_directio = 0;
58 static int opt_fsync = 0;
59 static int opt_write_log = 0;
60 static int opt_tries = 3;
61 static int opt_key_slot = CRYPT_ANY_SLOT;
62 static int opt_key_size = 0;
63 static int opt_new = 0;
64 static int opt_keep_key = 0;
65 static int opt_decrypt = 0;
67 static const char **action_argv;
69 static const char *set_pbkdf = NULL;
78 uint64_t device_size; /* overridden by parameter */
79 uint64_t device_size_new_real;
80 uint64_t device_size_org_real;
81 uint64_t device_offset;
82 uint64_t device_shift;
85 unsigned int stained:1;
86 unsigned int in_progress:1;
87 enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
88 enum { REENCRYPT = 0, ENCRYPT = 1, DECRYPT = 2 } reencrypt_mode;
90 char header_file_org[PATH_MAX];
91 char header_file_tmp[PATH_MAX];
92 char header_file_new[PATH_MAX];
93 char log_file[PATH_MAX];
95 char crypt_path_org[PATH_MAX];
96 char crypt_path_new[PATH_MAX];
98 char log_buf[SECTOR_SIZE];
106 uint64_t resume_bytes;
109 char MAGIC[] = {'L','U','K','S', 0xba, 0xbe};
110 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
120 void tools_cleanup(void)
122 FREE_AND_NULL(opt_cipher);
123 FREE_AND_NULL(opt_hash);
124 FREE_AND_NULL(opt_key_file);
125 FREE_AND_NULL(opt_master_key_file);
126 FREE_AND_NULL(opt_uuid);
127 FREE_AND_NULL(opt_type);
128 FREE_AND_NULL(opt_pbkdf);
129 FREE_AND_NULL(opt_header_device);
130 FREE_AND_NULL(opt_reduce_size_str);
131 FREE_AND_NULL(opt_device_size_str);
134 static void _quiet_log(int level, const char *msg, void *usrptr)
138 tool_log(level, msg, usrptr);
141 static int alignment(int fd)
145 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
151 static size_t pagesize(void)
153 long r = sysconf(_SC_PAGESIZE);
154 return r < 0 ? 4096 : (size_t)r;
157 static const char *luksType(const char *type)
159 if (type && !strcmp(type, "luks2"))
162 if (type && !strcmp(type, "luks1"))
165 if (!type || !strcmp(type, "luks"))
166 return crypt_get_default_type();
171 static const char *hdr_device(const struct reenc_ctx *rc)
173 return rc->device_header ?: rc->device;
176 static int set_reencrypt_requirement(const struct reenc_ctx *rc)
180 struct crypt_device *cd = NULL;
181 struct crypt_params_integrity ip = { 0 };
183 if (crypt_init(&cd, hdr_device(rc)) ||
184 crypt_load(cd, CRYPT_LUKS2, NULL) ||
185 crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &reqs))
188 /* reencrypt already in-progress */
189 if (reqs & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) {
190 log_err(_("Reencryption already in-progress."));
194 /* raw integrity info is available since 2.0 */
195 if (crypt_get_integrity_info(cd, &ip) || ip.tag_size) {
196 log_err(_("Reencryption of device with integrity profile is not supported."));
201 r = crypt_persistent_flags_set(cd, CRYPT_FLAGS_REQUIREMENTS, reqs | CRYPT_REQUIREMENT_OFFLINE_REENCRYPT);
207 /* Depends on the first two fields of LUKS1 header format, magic and version */
208 static int device_check(struct reenc_ctx *rc, const char *device, header_magic set_magic)
214 size_t buf_size = pagesize();
217 if (stat(device, &st)) {
218 log_err(_("Cannot open device %s."), device);
222 /* coverity[toctou] */
223 devfd = open(device, O_RDWR | (S_ISBLK(st.st_mode) ? O_EXCL : 0));
225 if (errno == EBUSY) {
226 log_err(_("Cannot exclusively open %s, device in use."),
230 log_err(_("Cannot open device %s."), device);
234 if (set_magic == CHECK_OPEN) {
239 if (posix_memalign((void *)&buf, alignment(devfd), buf_size)) {
240 log_err(_("Allocation of aligned memory failed."));
245 s = read(devfd, buf, buf_size);
246 if (s < 0 || s != (ssize_t)buf_size) {
247 log_err(_("Cannot read device %s."), device);
252 /* Be sure that we do not process new version of header */
253 memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
254 version = ntohs(version);
256 if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
258 log_verbose(_("Marking LUKS1 device %s unusable."), device);
259 memcpy(buf, NOMAGIC, MAGIC_L);
261 } else if (set_magic == MAKE_UNUSABLE && version == 2) {
262 log_verbose(_("Setting LUKS2 offline reencrypt flag on device %s."), device);
263 r = set_reencrypt_requirement(rc);
266 } else if (set_magic == CHECK_UNUSABLE && version == 1) {
267 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
269 rc->device_uuid = strndup(&buf[0xa8], 40);
274 if (!r && version == 1) {
275 if (lseek(devfd, 0, SEEK_SET) == -1)
277 s = write(devfd, buf, buf_size);
278 if (s < 0 || s != (ssize_t)buf_size || fsync(devfd) < 0) {
279 log_err(_("Cannot write device %s."), device);
282 if (s > 0 && set_magic == MAKE_UNUSABLE)
286 log_dbg("LUKS signature check failed for %s.", device);
289 memset(buf, 0, buf_size);
295 static int create_empty_header(const char *new_file)
299 log_dbg("Creating empty file %s of size 4096.", new_file);
301 /* coverity[toctou] */
302 fd = open(new_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
303 if (fd == -1 || posix_fallocate(fd, 0, 4096))
311 static int write_log(struct reenc_ctx *rc)
315 memset(rc->log_buf, 0, SECTOR_SIZE);
316 snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
317 "version = %d\nUUID = %s\ndirection = %d\nmode = %d\n"
318 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
319 2, rc->device_uuid, rc->reencrypt_direction, rc->reencrypt_mode,
320 rc->device_offset, rc->device_shift);
322 if (lseek(rc->log_fd, 0, SEEK_SET) == -1)
325 r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
326 if (r < 0 || r != SECTOR_SIZE) {
327 log_err(_("Cannot write reencryption log file."));
334 static int parse_line_log(struct reenc_ctx *rc, const char *line)
340 /* whole line is comment */
344 if (sscanf(line, "version = %d", &i) == 1) {
345 if (i < 1 || i > 2) {
346 log_dbg("Log: Unexpected version = %i", i);
349 } else if (sscanf(line, "UUID = %40s", s) == 1) {
350 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
351 log_dbg("Log: Unexpected UUID %s", s);
354 } else if (sscanf(line, "direction = %d", &i) == 1) {
355 log_dbg("Log: direction = %i", i);
356 rc->reencrypt_direction = i;
357 } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
358 log_dbg("Log: offset = %" PRIu64, u64);
359 rc->device_offset = u64;
360 } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
361 log_dbg("Log: shift = %" PRIu64, u64);
362 rc->device_shift = u64;
363 } else if (sscanf(line, "mode = %d", &i) == 1) { /* added in v2 */
364 log_dbg("Log: mode = %i", i);
365 rc->reencrypt_mode = i;
366 if (rc->reencrypt_mode != REENCRYPT &&
367 rc->reencrypt_mode != ENCRYPT &&
368 rc->reencrypt_mode != DECRYPT)
376 static int parse_log(struct reenc_ctx *rc)
381 s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
383 log_err(_("Cannot read reencryption log file."));
387 rc->log_buf[SECTOR_SIZE - 1] = '\0';
390 end = strchr(start, '\n');
393 if (parse_line_log(rc, start)) {
394 log_err("Wrong log format.");
405 static void close_log(struct reenc_ctx *rc)
407 log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
408 if (rc->log_fd != -1)
412 static int open_log(struct reenc_ctx *rc)
414 int flags = opt_fsync ? O_SYNC : 0;
416 rc->log_fd = open(rc->log_file, O_RDWR|O_EXCL|O_CREAT|flags, S_IRUSR|S_IWUSR);
417 if (rc->log_fd != -1) {
418 log_dbg("Created LUKS reencryption log file %s.", rc->log_file);
420 } else if (errno == EEXIST) {
421 log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file);
422 rc->log_fd = open(rc->log_file, O_RDWR|flags);
426 if (rc->log_fd == -1)
429 if (!rc->in_progress && write_log(rc) < 0) {
434 /* Be sure it is correct format */
435 return parse_log(rc);
438 static int activate_luks_headers(struct reenc_ctx *rc)
440 struct crypt_device *cd = NULL, *cd_new = NULL;
441 const char *pwd_old, *pwd_new, pwd_empty[] = "";
442 size_t pwd_old_len, pwd_new_len;
445 log_dbg("Activating LUKS devices from headers.");
447 /* Never use real password for empty header processing */
448 if (rc->reencrypt_mode == REENCRYPT) {
449 pwd_old = rc->p[rc->keyslot].password;
450 pwd_old_len = rc->p[rc->keyslot].passwordLen;
452 pwd_new_len = pwd_old_len;
453 } else if (rc->reencrypt_mode == DECRYPT) {
454 pwd_old = rc->p[rc->keyslot].password;
455 pwd_old_len = rc->p[rc->keyslot].passwordLen;
458 } else if (rc->reencrypt_mode == ENCRYPT) {
461 pwd_new = rc->p[rc->keyslot].password;
462 pwd_new_len = rc->p[rc->keyslot].passwordLen;
466 if ((r = crypt_init_data_device(&cd, rc->header_file_org, rc->device)) ||
467 (r = crypt_load(cd, CRYPT_LUKS, NULL)))
470 log_verbose(_("Activating temporary device using old LUKS header."));
471 if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
472 opt_key_slot, pwd_old, pwd_old_len,
473 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
476 if ((r = crypt_init_data_device(&cd_new, rc->header_file_new, rc->device)) ||
477 (r = crypt_load(cd_new, CRYPT_LUKS, NULL)))
480 log_verbose(_("Activating temporary device using new LUKS header."));
481 if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
482 opt_key_slot, pwd_new, pwd_new_len,
483 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
490 log_err(_("Activation of temporary devices failed."));
494 static int set_pbkdf_params(struct crypt_device *cd, const char *dev_type)
496 const struct crypt_pbkdf_type *pbkdf_default;
497 struct crypt_pbkdf_type pbkdf = {};
499 pbkdf_default = crypt_get_pbkdf_default(dev_type);
503 pbkdf.type = set_pbkdf ?: pbkdf_default->type;
504 pbkdf.hash = opt_hash ?: pbkdf_default->hash;
505 pbkdf.time_ms = (uint32_t)opt_iteration_time ?: pbkdf_default->time_ms;
506 if (strcmp(pbkdf.type, CRYPT_KDF_PBKDF2)) {
507 pbkdf.max_memory_kb = (uint32_t)opt_pbkdf_memory ?: pbkdf_default->max_memory_kb;
508 pbkdf.parallel_threads = (uint32_t)opt_pbkdf_parallel ?: pbkdf_default->parallel_threads;
511 if (opt_pbkdf_iterations) {
512 pbkdf.iterations = opt_pbkdf_iterations;
514 pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK;
517 return crypt_set_pbkdf_type(cd, &pbkdf);
520 static int create_new_keyslot(struct reenc_ctx *rc, int keyslot,
521 struct crypt_device *cd_old,
522 struct crypt_device *cd_new)
528 if (cd_old && crypt_keyslot_status(cd_old, keyslot) == CRYPT_SLOT_UNBOUND) {
530 key = crypt_safe_alloc(key_size);
533 r = crypt_volume_key_get(cd_old, keyslot, key, &key_size,
534 rc->p[keyslot].password, rc->p[keyslot].passwordLen);
536 r = crypt_keyslot_add_by_key(cd_new, keyslot, key, key_size,
537 rc->p[keyslot].password, rc->p[keyslot].passwordLen,
538 CRYPT_VOLUME_KEY_NO_SEGMENT);
541 crypt_safe_free(key);
543 r = crypt_keyslot_add_by_volume_key(cd_new, keyslot, NULL, 0,
544 rc->p[keyslot].password, rc->p[keyslot].passwordLen);
549 static int create_new_header(struct reenc_ctx *rc, struct crypt_device *cd_old,
550 const char *cipher, const char *cipher_mode,
552 const char *key, int key_size,
554 uint64_t metadata_size,
555 uint64_t keyslots_size,
558 struct crypt_device *cd_new = NULL;
561 if ((r = crypt_init(&cd_new, rc->header_file_new)))
565 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
566 else if (opt_urandom)
567 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
569 r = set_pbkdf_params(cd_new, type);
571 log_err(_("Failed to set pbkdf parameters."));
575 r = crypt_set_data_offset(cd_new, rc->data_offset);
577 log_err(_("Failed to set data offset."));
581 r = crypt_set_metadata_size(cd_new, metadata_size, keyslots_size);
583 log_err(_("Failed to set metadata size."));
587 r = crypt_format(cd_new, type, cipher, cipher_mode, uuid, key, key_size, params);
591 log_verbose(_("New LUKS header for device %s created."), rc->device);
593 for (i = 0; i < crypt_keyslot_max(type); i++) {
594 if (!rc->p[i].password)
597 r = create_new_keyslot(rc, i, cd_old, cd_new);
601 tools_keyslot_msg(r, CREATED);
609 static int isLUKS2(const char *type)
611 return (type && !strcmp(type, CRYPT_LUKS2));
614 static int luks2_metadata_copy(struct reenc_ctx *rc)
616 const char *json, *type;
620 struct crypt_device *cd_old = NULL, *cd_new = NULL;
622 if (crypt_init(&cd_old, rc->header_file_tmp) ||
623 crypt_load(cd_old, CRYPT_LUKS2, NULL))
626 if (crypt_init(&cd_new, rc->header_file_new) ||
627 crypt_load(cd_new, CRYPT_LUKS2, NULL))
631 * we have to erase keyslots missing in new header so that we can
632 * transfer tokens from old header to new one
634 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++)
635 if (!rc->p[i].password && crypt_keyslot_status(cd_old, i) == CRYPT_SLOT_ACTIVE) {
636 r = crypt_keyslot_destroy(cd_old, i);
641 for (i = 0; i < MAX_TOKEN; i++) {
642 ti = crypt_token_status(cd_old, i, &type);
644 case CRYPT_TOKEN_INVALID:
645 log_dbg("Internal error.");
648 case CRYPT_TOKEN_INACTIVE:
650 case CRYPT_TOKEN_INTERNAL_UNKNOWN:
651 log_err(_("This version of cryptsetup-reencrypt can't handle new internal token type %s."), type);
654 case CRYPT_TOKEN_INTERNAL:
656 case CRYPT_TOKEN_EXTERNAL:
658 case CRYPT_TOKEN_EXTERNAL_UNKNOWN:
659 if (crypt_token_json_get(cd_old, i, &json) != i) {
660 log_dbg("Failed to get %s token (%d).", type, i);
664 if (crypt_token_json_set(cd_new, i, json) != i) {
665 log_dbg("Failed to create %s token (%d).", type, i);
672 if ((r = crypt_persistent_flags_get(cd_old, CRYPT_FLAGS_ACTIVATION, &flags))) {
673 log_err(_("Failed to read activation flags from backup header."));
676 if ((r = crypt_persistent_flags_set(cd_new, CRYPT_FLAGS_ACTIVATION, flags))) {
677 log_err(_("Failed to write activation flags to new header."));
680 if ((r = crypt_persistent_flags_get(cd_old, CRYPT_FLAGS_REQUIREMENTS, &flags))) {
681 log_err(_("Failed to read requirements from backup header."));
684 if ((r = crypt_persistent_flags_set(cd_new, CRYPT_FLAGS_REQUIREMENTS, flags)))
685 log_err(_("Failed to read requirements from backup header."));
689 unlink(rc->header_file_tmp);
694 static int backup_luks_headers(struct reenc_ctx *rc)
696 struct crypt_device *cd = NULL;
697 struct crypt_params_luks1 params = {0};
698 struct crypt_params_luks2 params2 = {0};
700 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
703 uint64_t mdata_size = 0, keyslots_size = 0;
706 log_dbg("Creating LUKS header backup for device %s.", hdr_device(rc));
708 if ((r = crypt_init(&cd, hdr_device(rc))) ||
709 (r = crypt_load(cd, CRYPT_LUKS, NULL)))
712 if ((r = crypt_header_backup(cd, CRYPT_LUKS, rc->header_file_org)))
714 if (isLUKS2(rc->type)) {
715 if ((r = crypt_header_backup(cd, CRYPT_LUKS2, rc->header_file_tmp)))
717 if ((r = stat(rc->header_file_tmp, &st)))
719 /* coverity[toctou] */
720 if ((r = chmod(rc->header_file_tmp, st.st_mode | S_IWUSR)))
723 log_verbose(_("%s header backup of device %s created."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", rc->device);
725 /* For decrypt, new header will be fake one, so we are done here. */
726 if (rc->reencrypt_mode == DECRYPT)
729 rc->data_offset = crypt_get_data_offset(cd) + ROUND_SECTOR(opt_reduce_size);
731 if ((r = create_empty_header(rc->header_file_new)))
734 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
735 params2.data_device = params.data_device = rc->device;
736 params2.sector_size = crypt_get_sector_size(cd);
739 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
741 log_err(_("No known cipher specification pattern detected."));
746 key_size = opt_key_size ? opt_key_size / 8 : crypt_get_volume_key_size(cd);
749 log_dbg("Keeping key from old header.");
750 key_size = crypt_get_volume_key_size(cd);
751 key = crypt_safe_alloc(key_size);
756 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, key, &key_size,
757 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
758 } else if (opt_master_key_file) {
759 log_dbg("Loading new key from file.");
760 r = tools_read_mk(opt_master_key_file, &key, key_size);
766 if (isLUKS2(crypt_get_type(cd)) && crypt_get_metadata_size(cd, &mdata_size, &keyslots_size))
769 r = create_new_header(rc, cd,
770 opt_cipher ? cipher : crypt_get_cipher(cd),
771 opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
778 isLUKS2(rc->type) ? (void*)¶ms2 : (void*)¶ms);
780 if (!r && isLUKS2(rc->type))
781 r = luks2_metadata_copy(rc);
784 crypt_safe_free(key);
786 log_err(_("Creation of LUKS backup headers failed."));
790 /* Create fake header for original device */
791 static int backup_fake_header(struct reenc_ctx *rc)
793 struct crypt_device *cd_new = NULL;
794 struct crypt_params_luks1 params = {0};
795 struct crypt_params_luks2 params2 = {0};
796 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
797 const char *header_file_fake;
800 log_dbg("Creating fake (cipher_null) header for %s device.",
801 (rc->reencrypt_mode == DECRYPT) ? "new" : "original");
803 header_file_fake = (rc->reencrypt_mode == DECRYPT) ? rc->header_file_new : rc->header_file_org;
806 opt_key_size = DEFAULT_LUKS1_KEYBITS;
809 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
811 log_err(_("No known cipher specification pattern detected."));
816 r = create_empty_header(header_file_fake);
820 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
821 params2.data_alignment = params.data_alignment = 0;
822 params2.data_device = params.data_device = rc->device;
823 params2.sector_size = crypt_get_sector_size(NULL);
824 params2.pbkdf = crypt_get_pbkdf_default(CRYPT_LUKS2);
826 r = crypt_init(&cd_new, header_file_fake);
830 r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb",
831 NO_UUID, NULL, opt_key_size / 8, ¶ms);
836 r = crypt_keyslot_add_by_volume_key(cd_new, rc->keyslot, NULL, 0,
837 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
842 /* The real header is backup header created in backup_luks_headers() */
843 if (rc->reencrypt_mode == DECRYPT) {
848 r = create_empty_header(rc->header_file_new);
852 params2.data_alignment = params.data_alignment = ROUND_SECTOR(opt_reduce_size);
853 r = create_new_header(rc, NULL,
854 opt_cipher ? cipher : DEFAULT_LUKS1_CIPHER,
855 opt_cipher ? cipher_mode : DEFAULT_LUKS1_MODE,
857 (opt_key_size ? opt_key_size : DEFAULT_LUKS1_KEYBITS) / 8,
861 isLUKS2(rc->type) ? (void*)¶ms2 : (void*)¶ms);
867 static void remove_headers(struct reenc_ctx *rc)
869 struct crypt_device *cd = NULL;
871 log_dbg("Removing headers.");
873 if (crypt_init(&cd, NULL))
875 crypt_set_log_callback(cd, _quiet_log, NULL);
876 if (*rc->header_file_org)
877 (void)crypt_deactivate(cd, rc->header_file_org);
878 if (*rc->header_file_new)
879 (void)crypt_deactivate(cd, rc->header_file_new);
883 static int restore_luks_header(struct reenc_ctx *rc)
886 struct crypt_device *cd = NULL;
889 log_dbg("Restoring header for %s from %s.", hdr_device(rc), rc->header_file_new);
892 * For new encryption and new detached header in file just move it.
893 * For existing file try to ensure we have preallocated space for restore.
895 if (opt_new && rc->device_header) {
896 r = stat(rc->device_header, &st);
898 r = rename(rc->header_file_new, rc->device_header);
900 } else if ((st.st_mode & S_IFMT) == S_IFREG &&
901 stat(rc->header_file_new, &st) != -1) {
902 /* coverity[toctou] */
903 fd = open(rc->device_header, O_WRONLY);
905 if (posix_fallocate(fd, 0, st.st_size)) {};
911 r = crypt_init(&cd, hdr_device(rc));
913 r = crypt_header_restore(cd, rc->type, rc->header_file_new);
919 log_err(_("Cannot restore %s header on device %s."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", hdr_device(rc));
921 log_verbose(_("%s header on device %s restored."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", hdr_device(rc));
927 static ssize_t read_buf(int fd, void *buf, size_t count)
929 size_t read_size = 0;
933 /* This expects that partial read is aligned in buffer */
934 s = read(fd, buf, count - read_size);
935 if (s == -1 && errno != EINTR)
938 return (ssize_t)read_size;
940 if (s != (ssize_t)count)
941 log_dbg("Partial read %zd / %zu.", s, count);
942 read_size += (size_t)s;
943 buf = (uint8_t*)buf + s;
945 } while (read_size != count);
947 return (ssize_t)count;
950 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
951 size_t block_size, void *buf, uint64_t *bytes)
955 log_dbg("Reencrypting in forward direction.");
957 if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
958 lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
959 log_err(_("Cannot seek to device offset."));
963 rc->resume_bytes = *bytes = rc->device_offset;
965 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
967 if (write_log(rc) < 0)
970 while (!quit && rc->device_offset < rc->device_size) {
971 s1 = read_buf(fd_old, buf, block_size);
972 if (s1 < 0 || ((size_t)s1 != block_size &&
973 (rc->device_offset + s1) != rc->device_size)) {
974 log_dbg("Read error, expecting %zu, got %zd.",
979 /* If device_size is forced, never write more than limit */
980 if ((s1 + rc->device_offset) > rc->device_size)
981 s1 = rc->device_size - rc->device_offset;
983 s2 = write(fd_new, buf, s1);
985 log_dbg("Write error, expecting %zu, got %zd.",
990 rc->device_offset += s1;
991 if (opt_write_log && write_log(rc) < 0)
994 if (opt_fsync && fsync(fd_new) < 0) {
995 log_dbg("Write error, fsync.");
999 *bytes += (uint64_t)s2;
1001 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1004 return quit ? -EAGAIN : 0;
1007 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
1008 size_t block_size, void *buf, uint64_t *bytes)
1010 ssize_t s1, s2, working_block;
1011 off64_t working_offset;
1013 log_dbg("Reencrypting in backward direction.");
1015 if (!rc->in_progress) {
1016 rc->device_offset = rc->device_size;
1017 rc->resume_bytes = 0;
1020 rc->resume_bytes = rc->device_size - rc->device_offset;
1021 *bytes = rc->resume_bytes;
1024 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1026 if (write_log(rc) < 0)
1029 /* dirty the device during ENCRYPT mode */
1032 while (!quit && rc->device_offset) {
1033 if (rc->device_offset < block_size) {
1035 working_block = rc->device_offset;
1037 working_offset = rc->device_offset - block_size;
1038 working_block = block_size;
1041 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
1042 lseek64(fd_new, working_offset, SEEK_SET) < 0) {
1043 log_err(_("Cannot seek to device offset."));
1047 s1 = read_buf(fd_old, buf, working_block);
1048 if (s1 < 0 || (s1 != working_block)) {
1049 log_dbg("Read error, expecting %zu, got %zd.",
1054 s2 = write(fd_new, buf, working_block);
1056 log_dbg("Write error, expecting %zu, got %zd.",
1061 rc->device_offset -= s1;
1062 if (opt_write_log && write_log(rc) < 0)
1065 if (opt_fsync && fsync(fd_new) < 0) {
1066 log_dbg("Write error, fsync.");
1070 *bytes += (uint64_t)s2;
1072 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1075 return quit ? -EAGAIN : 0;
1078 static void zero_rest_of_device(int fd, size_t block_size, void *buf,
1079 uint64_t *bytes, uint64_t offset)
1083 log_dbg("Zeroing rest of device.");
1085 if (lseek64(fd, offset, SEEK_SET) < 0) {
1086 log_dbg("Cannot seek to device offset.");
1090 memset(buf, 0, block_size);
1093 while (!quit && *bytes) {
1094 if (*bytes < (uint64_t)s1)
1097 s2 = write(fd, buf, s1);
1099 log_dbg("Write error, expecting %zd, got %zd.",
1104 if (opt_fsync && fsync(fd) < 0) {
1105 log_dbg("Write error, fsync.");
1113 static int copy_data(struct reenc_ctx *rc)
1115 size_t block_size = opt_bsize * 1024 * 1024;
1116 int fd_old = -1, fd_new = -1;
1121 log_dbg("Data copy preparation.");
1123 fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
1125 log_err(_("Cannot open temporary LUKS device."));
1129 fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
1131 log_err(_("Cannot open temporary LUKS device."));
1135 if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size_org_real) < 0) {
1136 log_err(_("Cannot get device size."));
1140 if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_new_real) < 0) {
1141 log_err(_("Cannot get device size."));
1145 if (opt_device_size)
1146 rc->device_size = opt_device_size;
1147 else if (rc->reencrypt_mode == DECRYPT)
1148 rc->device_size = rc->device_size_org_real;
1150 rc->device_size = rc->device_size_new_real;
1152 if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
1153 log_err(_("Allocation of aligned memory failed."));
1160 if (rc->reencrypt_direction == FORWARD)
1161 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
1163 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
1165 /* Zero (wipe) rest of now plain-only device when decrypting.
1166 * (To not leave any sign of encryption here.) */
1167 if (!r && rc->reencrypt_mode == DECRYPT &&
1168 rc->device_size_new_real > rc->device_size_org_real) {
1169 bytes = rc->device_size_new_real - rc->device_size_org_real;
1170 zero_rest_of_device(fd_new, block_size, buf, &bytes, rc->device_size_org_real);
1175 if (r < 0 && r != -EAGAIN)
1176 log_err(_("IO error during reencryption."));
1178 (void)write_log(rc);
1188 static int initialize_uuid(struct reenc_ctx *rc)
1190 struct crypt_device *cd = NULL;
1194 log_dbg("Initialising UUID.");
1197 rc->device_uuid = strdup(NO_UUID);
1198 rc->type = luksType(opt_type);
1202 if (opt_decrypt && opt_uuid) {
1203 r = uuid_parse(opt_uuid, device_uuid);
1205 rc->device_uuid = strdup(opt_uuid);
1207 log_err(_("Provided UUID is invalid."));
1212 /* Try to load LUKS from device */
1213 if ((r = crypt_init(&cd, hdr_device(rc))))
1215 crypt_set_log_callback(cd, _quiet_log, NULL);
1216 r = crypt_load(cd, CRYPT_LUKS, NULL);
1218 rc->device_uuid = strdup(crypt_get_uuid(cd));
1220 /* Reencryption already in progress - magic header? */
1221 r = device_check(rc, hdr_device(rc), CHECK_UNUSABLE);
1224 rc->type = isLUKS2(crypt_get_type(cd)) ? CRYPT_LUKS2 : CRYPT_LUKS1;
1230 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
1231 const char *msg, int slot_to_check, int check, int verify)
1233 crypt_keyslot_info ki;
1235 int r = -EINVAL, retry_count;
1238 /* mode ENCRYPT call this without header */
1239 if (cd && slot_to_check != CRYPT_ANY_SLOT) {
1240 ki = crypt_keyslot_status(cd, slot_to_check);
1241 if (ki < CRYPT_SLOT_ACTIVE)
1244 ki = CRYPT_SLOT_ACTIVE;
1246 retry_count = opt_tries ?: 1;
1247 while (retry_count--) {
1248 r = tools_get_key(msg, &password, &passwordLen, 0, 0,
1249 NULL /*opt_key_file*/, 0, verify, 0 /*pwquality*/, cd);
1253 crypt_safe_free(password);
1260 r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
1261 password, passwordLen, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY);
1263 r = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check;
1266 crypt_safe_free(password);
1270 if (r < 0 && r != -EPERM)
1274 tools_keyslot_msg(r, UNLOCKED);
1275 rc->p[r].password = password;
1276 rc->p[r].passwordLen = passwordLen;
1277 if (ki != CRYPT_SLOT_UNBOUND)
1281 tools_passphrase_msg(r);
1290 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
1296 r = tools_get_key(NULL, &password, &passwordLen, opt_keyfile_offset,
1297 opt_keyfile_size, opt_key_file, 0, 0, 0, cd);
1301 /* mode ENCRYPT call this without header */
1303 r = crypt_activate_by_passphrase(cd, NULL, slot_check, password,
1307 * Allow keyslot only if it is last slot or if user explicitly
1308 * specify which slot to use (IOW others will be disabled).
1310 if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
1311 crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
1312 log_err(_("Key file can be used only with --key-slot or with "
1313 "exactly one key slot active."));
1317 r = slot_check == CRYPT_ANY_SLOT ? 0 : slot_check;
1321 crypt_safe_free(password);
1322 tools_passphrase_msg(r);
1325 rc->p[r].password = password;
1326 rc->p[r].passwordLen = passwordLen;
1335 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
1337 struct crypt_device *cd = NULL;
1341 log_dbg("Passphrases initialization.");
1343 if (rc->reencrypt_mode == ENCRYPT && !rc->in_progress) {
1345 r = init_keyfile(rc, NULL, opt_key_slot);
1347 r = init_passphrase1(rc, NULL, _("Enter new passphrase: "), opt_key_slot, 0, 1);
1348 return r > 0 ? 0 : r;
1351 if ((r = crypt_init_data_device(&cd, device, rc->device)) ||
1352 (r = crypt_load(cd, CRYPT_LUKS, NULL))) {
1357 if (opt_key_slot != CRYPT_ANY_SLOT)
1358 snprintf(msg, sizeof(msg),
1359 _("Enter passphrase for key slot %d: "), opt_key_slot);
1361 snprintf(msg, sizeof(msg), _("Enter any existing passphrase: "));
1364 r = init_keyfile(rc, cd, opt_key_slot);
1365 } else if (rc->in_progress ||
1366 opt_key_slot != CRYPT_ANY_SLOT ||
1367 rc->reencrypt_mode == DECRYPT) {
1368 r = init_passphrase1(rc, cd, msg, opt_key_slot, 1, 0);
1369 } else for (i = 0; i < crypt_keyslot_max(crypt_get_type(cd)); i++) {
1370 snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i);
1371 r = init_passphrase1(rc, cd, msg, i, 1, 0);
1381 return r > 0 ? 0 : r;
1384 static int initialize_context(struct reenc_ctx *rc, const char *device)
1386 log_dbg("Initialising reencryption context.");
1390 /* FIXME: replace MAX_KEYSLOT with crypt_keyslot_max(CRYPT_LUKS2) */
1391 if (crypt_keyslot_max(CRYPT_LUKS2) > MAX_SLOT) {
1392 log_dbg("Internal error");
1396 if (!(rc->device = strndup(device, PATH_MAX)))
1399 if (opt_header_device && !(rc->device_header = strndup(opt_header_device, PATH_MAX)))
1402 if (device_check(rc, rc->device, CHECK_OPEN) < 0)
1405 if (initialize_uuid(rc)) {
1406 log_err(_("Device %s is not a valid LUKS device."), device);
1410 if (opt_key_slot != CRYPT_ANY_SLOT &&
1411 opt_key_slot >= crypt_keyslot_max(rc->type)) {
1412 log_err(_("Key slot is invalid."));
1416 /* Prepare device names */
1417 if (snprintf(rc->log_file, PATH_MAX,
1418 "LUKS-%s.log", rc->device_uuid) < 0)
1420 if (snprintf(rc->header_file_org, PATH_MAX,
1421 "LUKS-%s.org", rc->device_uuid) < 0)
1423 if (snprintf(rc->header_file_new, PATH_MAX,
1424 "LUKS-%s.new", rc->device_uuid) < 0)
1426 if (snprintf(rc->header_file_tmp, PATH_MAX,
1427 "LUKS-%s.tmp", rc->device_uuid) < 0)
1430 /* Paths to encrypted devices */
1431 if (snprintf(rc->crypt_path_org, PATH_MAX,
1432 "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
1434 if (snprintf(rc->crypt_path_new, PATH_MAX,
1435 "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
1440 if (open_log(rc) < 0) {
1441 log_err(_("Cannot open reencryption log file."));
1445 if (!rc->in_progress) {
1447 log_err(_("No decryption in progress, provided UUID can "
1448 "be used only to resume suspended decryption process."));
1452 if (!opt_reduce_size)
1453 rc->reencrypt_direction = FORWARD;
1455 rc->reencrypt_direction = BACKWARD;
1456 rc->device_offset = (uint64_t)~0;
1460 rc->reencrypt_mode = ENCRYPT;
1461 else if (opt_decrypt)
1462 rc->reencrypt_mode = DECRYPT;
1464 rc->reencrypt_mode = REENCRYPT;
1470 static void destroy_context(struct reenc_ctx *rc)
1474 log_dbg("Destroying reencryption context.");
1480 unlink(rc->log_file);
1481 unlink(rc->header_file_org);
1482 unlink(rc->header_file_new);
1483 unlink(rc->header_file_tmp);
1486 for (i = 0; i < MAX_SLOT; i++)
1487 crypt_safe_free(rc->p[i].password);
1490 free(rc->device_header);
1491 free(rc->device_uuid);
1494 static int luks2_change_pbkdf_params(struct reenc_ctx *rc)
1497 struct crypt_device *cd = NULL;
1499 if ((r = initialize_passphrase(rc, hdr_device(rc))))
1502 if (crypt_init(&cd, hdr_device(rc)) ||
1503 crypt_load(cd, CRYPT_LUKS2, NULL)) {
1508 if ((r = set_pbkdf_params(cd, CRYPT_LUKS2)))
1511 log_dbg("LUKS2 keyslot pbkdf params change.");
1515 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++) {
1516 if (!rc->p[i].password)
1518 if ((r = crypt_keyslot_change_by_passphrase(cd, i, i,
1519 rc->p[i].password, rc->p[i].passwordLen,
1520 rc->p[i].password, rc->p[i].passwordLen)) < 0)
1522 log_verbose(_("Changed pbkdf parameters in keyslot %i."), r);
1529 /* see create_new_header */
1530 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++)
1531 if (!rc->p[i].password)
1532 (void)crypt_keyslot_destroy(cd, i);
1538 static int run_reencrypt(const char *device)
1541 static struct reenc_ctx rc = {
1547 if (initialize_context(&rc, device))
1550 /* short-circuit LUKS2 keyslot parameters change */
1551 if (opt_keep_key && isLUKS2(rc.type)) {
1552 r = luks2_change_pbkdf_params(&rc);
1556 log_dbg("Running reencryption.");
1558 if (!rc.in_progress) {
1559 if ((r = initialize_passphrase(&rc, hdr_device(&rc))))
1562 log_dbg("Storing backup of LUKS headers.");
1563 if (rc.reencrypt_mode == ENCRYPT) {
1564 /* Create fake header for existing device */
1565 if ((r = backup_fake_header(&rc)))
1568 if ((r = backup_luks_headers(&rc)))
1570 /* Create fake header for decrypted device */
1571 if (rc.reencrypt_mode == DECRYPT &&
1572 (r = backup_fake_header(&rc)))
1574 if ((r = device_check(&rc, hdr_device(&rc), MAKE_UNUSABLE)))
1578 if ((r = initialize_passphrase(&rc, opt_decrypt ? rc.header_file_org : rc.header_file_new)))
1582 if (!opt_keep_key) {
1583 log_dbg("Running data area reencryption.");
1584 if ((r = activate_luks_headers(&rc)))
1587 if ((r = copy_data(&rc)))
1590 log_dbg("Keeping existing key, skipping data area reencryption.");
1592 // FIXME: fix error path above to not skip this
1593 if (rc.reencrypt_mode != DECRYPT)
1594 r = restore_luks_header(&rc);
1598 destroy_context(&rc);
1602 static void help(poptContext popt_context,
1603 enum poptCallbackReason reason __attribute__((unused)),
1604 struct poptOption *key,
1605 const char *arg __attribute__((unused)),
1606 void *data __attribute__((unused)))
1608 if (key->shortName == '?') {
1609 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1610 poptPrintHelp(popt_context, stdout, 0);
1612 poptFreeContext(popt_context);
1614 } else if (key->shortName == 'V') {
1615 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1617 poptFreeContext(popt_context);
1620 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1623 int main(int argc, const char **argv)
1625 static struct poptOption popt_help_options[] = {
1626 { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL },
1627 { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL },
1628 { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL },
1629 { "version",'V', POPT_ARG_NONE, NULL, 0, N_("Print package version"), NULL },
1632 static struct poptOption popt_options[] = {
1633 { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1634 { "verbose", 'v', POPT_ARG_NONE, &opt_verbose, 0, N_("Shows more detailed error messages"), NULL },
1635 { "debug", '\0', POPT_ARG_NONE, &opt_debug, 0, N_("Show debug messages"), NULL },
1636 { "block-size", 'B', POPT_ARG_INT, &opt_bsize, 0, N_("Reencryption block size"), N_("MiB") },
1637 { "cipher", 'c', POPT_ARG_STRING, &opt_cipher, 0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1638 { "key-size", 's', POPT_ARG_INT, &opt_key_size, 0, N_("The size of the encryption key"), N_("BITS") },
1639 { "hash", 'h', POPT_ARG_STRING, &opt_hash, 0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1640 { "keep-key", '\0', POPT_ARG_NONE, &opt_keep_key, 0, N_("Do not change key, no data area reencryption"), NULL },
1641 { "key-file", 'd', POPT_ARG_STRING, &opt_key_file, 0, N_("Read the key from a file"), NULL },
1642 { "master-key-file", '\0', POPT_ARG_STRING, &opt_master_key_file, 0, N_("Read new volume (master) key from file"), NULL },
1643 { "iter-time", 'i', POPT_ARG_INT, &opt_iteration_time, 0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1644 { "batch-mode", 'q', POPT_ARG_NONE, &opt_batch_mode, 0, N_("Do not ask for confirmation"), NULL },
1645 { "progress-frequency",'\0', POPT_ARG_INT, &opt_progress_frequency, 0, N_("Progress line update (in seconds)"), N_("secs") },
1646 { "tries", 'T', POPT_ARG_INT, &opt_tries, 0, N_("How often the input of the passphrase can be retried"), NULL },
1647 { "use-random", '\0', POPT_ARG_NONE, &opt_random, 0, N_("Use /dev/random for generating volume key"), NULL },
1648 { "use-urandom", '\0', POPT_ARG_NONE, &opt_urandom, 0, N_("Use /dev/urandom for generating volume key"), NULL },
1649 { "use-directio", '\0', POPT_ARG_NONE, &opt_directio, 0, N_("Use direct-io when accessing devices"), NULL },
1650 { "use-fsync", '\0', POPT_ARG_NONE, &opt_fsync, 0, N_("Use fsync after each block"), NULL },
1651 { "write-log", '\0', POPT_ARG_NONE, &opt_write_log, 0, N_("Update log file after every block"), NULL },
1652 { "key-slot", 'S', POPT_ARG_INT, &opt_key_slot, 0, N_("Use only this slot (others will be disabled)"), NULL },
1653 { "keyfile-offset", '\0', POPT_ARG_LONG, &opt_keyfile_offset, 0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1654 { "keyfile-size", 'l', POPT_ARG_LONG, &opt_keyfile_size, 0, N_("Limits the read from keyfile"), N_("bytes") },
1655 { "reduce-device-size",'\0', POPT_ARG_STRING, &opt_reduce_size_str, 0, N_("Reduce data device size (move data offset). DANGEROUS!"), N_("bytes") },
1656 { "device-size", '\0', POPT_ARG_STRING, &opt_device_size_str, 0, N_("Use only specified device size (ignore rest of device). DANGEROUS!"), N_("bytes") },
1657 { "new", 'N', POPT_ARG_NONE, &opt_new, 0, N_("Create new header on not encrypted device"), NULL },
1658 { "decrypt", '\0', POPT_ARG_NONE, &opt_decrypt, 0, N_("Permanently decrypt device (remove encryption)"), NULL },
1659 { "uuid", '\0', POPT_ARG_STRING, &opt_uuid, 0, N_("The UUID used to resume decryption"), NULL },
1660 { "type", '\0', POPT_ARG_STRING, &opt_type, 0, N_("Type of LUKS metadata: luks1, luks2"), NULL },
1661 { "pbkdf", '\0', POPT_ARG_STRING, &opt_pbkdf, 0, N_("PBKDF algorithm (for LUKS2): argon2i, argon2id, pbkdf2"), NULL },
1662 { "pbkdf-memory", '\0', POPT_ARG_LONG, &opt_pbkdf_memory, 0, N_("PBKDF memory cost limit"), N_("kilobytes") },
1663 { "pbkdf-parallel", '\0', POPT_ARG_LONG, &opt_pbkdf_parallel, 0, N_("PBKDF parallel cost"), N_("threads") },
1664 { "pbkdf-force-iterations",'\0',POPT_ARG_LONG, &opt_pbkdf_iterations, 0, N_("PBKDF iterations cost (forced, disables benchmark)"), NULL },
1665 { "header", '\0', POPT_ARG_STRING, &opt_header_device, 0, N_("Device or file with separated LUKS header"), NULL },
1668 poptContext popt_context;
1671 crypt_set_log_callback(NULL, tool_log, NULL);
1673 setlocale(LC_ALL, "");
1674 bindtextdomain(PACKAGE, LOCALEDIR);
1675 textdomain(PACKAGE);
1677 popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1678 poptSetOtherOptionHelp(popt_context,
1679 _("[OPTION...] <device>"));
1681 while((r = poptGetNextOpt(popt_context)) > 0) ;
1683 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1684 poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1686 if (!opt_batch_mode)
1687 log_verbose(_("Reencryption will change: %s%s%s%s%s%s."),
1688 opt_keep_key ? "" : _("volume key"),
1689 (!opt_keep_key && opt_hash) ? ", " : "",
1690 opt_hash ? _("set hash to ") : "", opt_hash ?: "",
1691 opt_cipher ? _(", set cipher to "): "", opt_cipher ?: "");
1693 action_argv = poptGetArgs(popt_context);
1695 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1696 poptGetInvocationName(popt_context));
1698 if (opt_random && opt_urandom)
1699 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1700 poptGetInvocationName(popt_context));
1702 if (opt_bsize < 0 || opt_key_size < 0 || opt_iteration_time < 0 ||
1703 opt_tries < 0 || opt_keyfile_offset < 0 || opt_key_size < 0 ||
1704 opt_pbkdf_iterations < 0 || opt_pbkdf_memory < 0 ||
1705 opt_pbkdf_parallel < 0) {
1706 usage(popt_context, EXIT_FAILURE,
1707 _("Negative number for option not permitted."),
1708 poptGetInvocationName(popt_context));
1711 if (opt_pbkdf && crypt_parse_pbkdf(opt_pbkdf, &set_pbkdf))
1712 usage(popt_context, EXIT_FAILURE,
1713 _("Password-based key derivation function (PBKDF) can be only pbkdf2 or argon2i/argon2id."),
1714 poptGetInvocationName(popt_context));
1716 if (opt_pbkdf_iterations && opt_iteration_time)
1717 usage(popt_context, EXIT_FAILURE,
1718 _("PBKDF forced iterations cannot be combined with iteration time option."),
1719 poptGetInvocationName(popt_context));
1721 if (opt_bsize < 1 || opt_bsize > 64)
1722 usage(popt_context, EXIT_FAILURE,
1723 _("Only values between 1 MiB and 64 MiB allowed for reencryption block size."),
1724 poptGetInvocationName(popt_context));
1726 if (opt_key_size % 8)
1727 usage(popt_context, EXIT_FAILURE,
1728 _("Key size must be a multiple of 8 bits"),
1729 poptGetInvocationName(popt_context));
1731 if (opt_key_slot != CRYPT_ANY_SLOT &&
1732 (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS2)))
1733 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1734 poptGetInvocationName(popt_context));
1736 if (opt_random && opt_urandom)
1737 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1738 poptGetInvocationName(popt_context));
1740 if (opt_device_size_str &&
1741 tools_string_to_size(NULL, opt_device_size_str, &opt_device_size))
1742 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1743 poptGetInvocationName(popt_context));
1745 if (opt_reduce_size_str &&
1746 tools_string_to_size(NULL, opt_reduce_size_str, &opt_reduce_size))
1747 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1748 poptGetInvocationName(popt_context));
1749 if (opt_reduce_size > 64 * 1024 * 1024)
1750 usage(popt_context, EXIT_FAILURE, _("Maximum device reduce size is 64 MiB."),
1751 poptGetInvocationName(popt_context));
1752 if (opt_reduce_size % SECTOR_SIZE)
1753 usage(popt_context, EXIT_FAILURE, _("Reduce size must be multiple of 512 bytes sector."),
1754 poptGetInvocationName(popt_context));
1756 if (opt_new && (!opt_reduce_size && !opt_header_device))
1757 usage(popt_context, EXIT_FAILURE, _("Option --new must be used together with --reduce-device-size or --header."),
1758 poptGetInvocationName(popt_context));
1760 if (opt_keep_key && (opt_cipher || opt_new || opt_master_key_file))
1761 usage(popt_context, EXIT_FAILURE, _("Option --keep-key can be used only with --hash, --iter-time or --pbkdf-force-iterations."),
1762 poptGetInvocationName(popt_context));
1764 if (opt_new && opt_decrypt)
1765 usage(popt_context, EXIT_FAILURE, _("Option --new cannot be used together with --decrypt."),
1766 poptGetInvocationName(popt_context));
1768 if (opt_decrypt && (opt_cipher || opt_hash || opt_reduce_size || opt_keep_key || opt_device_size))
1769 usage(popt_context, EXIT_FAILURE, _("Option --decrypt is incompatible with specified parameters."),
1770 poptGetInvocationName(popt_context));
1772 if (opt_uuid && !opt_decrypt)
1773 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only together with --decrypt."),
1774 poptGetInvocationName(popt_context));
1776 if (!luksType(opt_type))
1777 usage(popt_context, EXIT_FAILURE, _("Invalid luks type. Use one of these: 'luks', 'luks1' or 'luks2'."),
1778 poptGetInvocationName(popt_context));
1782 crypt_set_debug_level(-1);
1783 dbg_version_and_cmd(argc, argv);
1786 r = run_reencrypt(action_argv[0]);
1788 poptFreeContext(popt_context);
1789 return translate_errno(r);