2 * cryptsetup-reencrypt - crypt utility for offline re-encryption
4 * Copyright (C) 2012-2020 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2012-2020 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 const char *opt_cipher = NULL;
33 static const char *opt_hash = NULL;
34 static const char *opt_key_file = NULL;
35 static const char *opt_master_key_file = NULL;
36 static const char *opt_uuid = NULL;
37 static const char *opt_type = "luks";
38 static long opt_keyfile_size = 0;
39 static long opt_keyfile_offset = 0;
40 static int opt_iteration_time = 0;
41 static const char *opt_pbkdf = NULL;
42 static long opt_pbkdf_memory = DEFAULT_LUKS2_MEMORY_KB;
43 static long opt_pbkdf_parallel = DEFAULT_LUKS2_PARALLEL_THREADS;
44 static long opt_pbkdf_iterations = 0;
45 static int opt_random = 0;
46 static int opt_urandom = 0;
47 static int opt_bsize = 4;
48 static int opt_directio = 0;
49 static int opt_fsync = 0;
50 static int opt_write_log = 0;
51 static int opt_tries = 3;
52 static int opt_key_slot = CRYPT_ANY_SLOT;
53 static int opt_key_size = 0;
54 static int opt_new = 0;
55 static int opt_keep_key = 0;
56 static int opt_decrypt = 0;
57 static const char *opt_header_device = NULL;
59 static const char *opt_reduce_size_str = NULL;
60 static uint64_t opt_reduce_size = 0;
62 static const char *opt_device_size_str = NULL;
63 static uint64_t opt_device_size = 0;
65 static const char **action_argv;
74 uint64_t device_size; /* overridden by parameter */
75 uint64_t device_size_new_real;
76 uint64_t device_size_org_real;
77 uint64_t device_offset;
78 uint64_t device_shift;
81 unsigned int stained:1;
82 unsigned int in_progress:1;
83 enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
84 enum { REENCRYPT = 0, ENCRYPT = 1, DECRYPT = 2 } reencrypt_mode;
86 char header_file_org[PATH_MAX];
87 char header_file_tmp[PATH_MAX];
88 char header_file_new[PATH_MAX];
89 char log_file[PATH_MAX];
91 char crypt_path_org[PATH_MAX];
92 char crypt_path_new[PATH_MAX];
94 char log_buf[SECTOR_SIZE];
102 uint64_t resume_bytes;
105 char MAGIC[] = {'L','U','K','S', 0xba, 0xbe};
106 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
116 static void _quiet_log(int level, const char *msg, void *usrptr)
120 tool_log(level, msg, usrptr);
123 static int alignment(int fd)
127 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
133 static size_t pagesize(void)
135 long r = sysconf(_SC_PAGESIZE);
136 return r < 0 ? 4096 : (size_t)r;
139 static const char *luksType(const char *type)
141 if (type && !strcmp(type, "luks2"))
144 if (type && !strcmp(type, "luks1"))
147 if (!type || !strcmp(type, "luks"))
148 return crypt_get_default_type();
153 static const char *hdr_device(const struct reenc_ctx *rc)
155 return rc->device_header ?: rc->device;
158 static int set_reencrypt_requirement(const struct reenc_ctx *rc)
162 struct crypt_device *cd = NULL;
163 struct crypt_params_integrity ip = { 0 };
165 if (crypt_init(&cd, hdr_device(rc)) ||
166 crypt_load(cd, CRYPT_LUKS2, NULL) ||
167 crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &reqs))
170 /* reencrypt already in-progress */
171 if (reqs & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) {
172 log_err(_("Reencryption already in-progress."));
176 /* raw integrity info is available since 2.0 */
177 if (crypt_get_integrity_info(cd, &ip) || ip.tag_size) {
178 log_err(_("Reencryption of device with integrity profile is not supported."));
183 r = crypt_persistent_flags_set(cd, CRYPT_FLAGS_REQUIREMENTS, reqs | CRYPT_REQUIREMENT_OFFLINE_REENCRYPT);
189 /* Depends on the first two fields of LUKS1 header format, magic and version */
190 static int device_check(struct reenc_ctx *rc, const char *device, header_magic set_magic)
196 size_t buf_size = pagesize();
199 if (stat(device, &st)) {
200 log_err(_("Cannot open device %s."), device);
204 /* coverity[toctou] */
205 devfd = open(device, O_RDWR | (S_ISBLK(st.st_mode) ? O_EXCL : 0));
207 if (errno == EBUSY) {
208 log_err(_("Cannot exclusively open %s, device in use."),
212 log_err(_("Cannot open device %s."), device);
216 if (set_magic == CHECK_OPEN) {
221 if (posix_memalign((void *)&buf, alignment(devfd), buf_size)) {
222 log_err(_("Allocation of aligned memory failed."));
227 s = read(devfd, buf, buf_size);
228 if (s < 0 || s != (ssize_t)buf_size) {
229 log_err(_("Cannot read device %s."), device);
234 /* Be sure that we do not process new version of header */
235 memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
236 version = ntohs(version);
238 if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
240 log_verbose(_("Marking LUKS1 device %s unusable."), device);
241 memcpy(buf, NOMAGIC, MAGIC_L);
243 } else if (set_magic == MAKE_UNUSABLE && version == 2) {
244 log_verbose(_("Setting LUKS2 offline reencrypt flag on device %s."), device);
245 r = set_reencrypt_requirement(rc);
248 } else if (set_magic == CHECK_UNUSABLE && version == 1) {
249 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
251 rc->device_uuid = strndup(&buf[0xa8], 40);
256 if (!r && version == 1) {
257 if (lseek(devfd, 0, SEEK_SET) == -1)
259 s = write(devfd, buf, buf_size);
260 if (s < 0 || s != (ssize_t)buf_size || fsync(devfd) < 0) {
261 log_err(_("Cannot write device %s."), device);
264 if (s > 0 && set_magic == MAKE_UNUSABLE)
268 log_dbg("LUKS signature check failed for %s.", device);
271 memset(buf, 0, buf_size);
277 static int create_empty_header(const char *new_file)
281 log_dbg("Creating empty file %s of size 4096.", new_file);
283 /* coverity[toctou] */
284 fd = open(new_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
285 if (fd == -1 || posix_fallocate(fd, 0, 4096))
293 static int write_log(struct reenc_ctx *rc)
297 memset(rc->log_buf, 0, SECTOR_SIZE);
298 snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
299 "version = %d\nUUID = %s\ndirection = %d\nmode = %d\n"
300 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
301 2, rc->device_uuid, rc->reencrypt_direction, rc->reencrypt_mode,
302 rc->device_offset, rc->device_shift);
304 if (lseek(rc->log_fd, 0, SEEK_SET) == -1)
307 r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
308 if (r < 0 || r != SECTOR_SIZE) {
309 log_err(_("Cannot write reencryption log file."));
316 static int parse_line_log(struct reenc_ctx *rc, const char *line)
322 /* whole line is comment */
326 if (sscanf(line, "version = %d", &i) == 1) {
327 if (i < 1 || i > 2) {
328 log_dbg("Log: Unexpected version = %i", i);
331 } else if (sscanf(line, "UUID = %40s", s) == 1) {
332 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
333 log_dbg("Log: Unexpected UUID %s", s);
336 } else if (sscanf(line, "direction = %d", &i) == 1) {
337 log_dbg("Log: direction = %i", i);
338 rc->reencrypt_direction = i;
339 } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
340 log_dbg("Log: offset = %" PRIu64, u64);
341 rc->device_offset = u64;
342 } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
343 log_dbg("Log: shift = %" PRIu64, u64);
344 rc->device_shift = u64;
345 } else if (sscanf(line, "mode = %d", &i) == 1) { /* added in v2 */
346 log_dbg("Log: mode = %i", i);
347 rc->reencrypt_mode = i;
348 if (rc->reencrypt_mode != REENCRYPT &&
349 rc->reencrypt_mode != ENCRYPT &&
350 rc->reencrypt_mode != DECRYPT)
358 static int parse_log(struct reenc_ctx *rc)
363 s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
365 log_err(_("Cannot read reencryption log file."));
369 rc->log_buf[SECTOR_SIZE - 1] = '\0';
372 end = strchr(start, '\n');
375 if (parse_line_log(rc, start)) {
376 log_err("Wrong log format.");
387 static void close_log(struct reenc_ctx *rc)
389 log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
390 if (rc->log_fd != -1)
394 static int open_log(struct reenc_ctx *rc)
396 int flags = opt_fsync ? O_SYNC : 0;
398 rc->log_fd = open(rc->log_file, O_RDWR|O_EXCL|O_CREAT|flags, S_IRUSR|S_IWUSR);
399 if (rc->log_fd != -1) {
400 log_dbg("Created LUKS reencryption log file %s.", rc->log_file);
402 } else if (errno == EEXIST) {
403 log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file);
404 rc->log_fd = open(rc->log_file, O_RDWR|flags);
408 if (rc->log_fd == -1)
411 if (!rc->in_progress && write_log(rc) < 0) {
416 /* Be sure it is correct format */
417 return parse_log(rc);
420 static int activate_luks_headers(struct reenc_ctx *rc)
422 struct crypt_device *cd = NULL, *cd_new = NULL;
423 const char *pwd_old, *pwd_new, pwd_empty[] = "";
424 size_t pwd_old_len, pwd_new_len;
427 log_dbg("Activating LUKS devices from headers.");
429 /* Never use real password for empty header processing */
430 if (rc->reencrypt_mode == REENCRYPT) {
431 pwd_old = rc->p[rc->keyslot].password;
432 pwd_old_len = rc->p[rc->keyslot].passwordLen;
434 pwd_new_len = pwd_old_len;
435 } else if (rc->reencrypt_mode == DECRYPT) {
436 pwd_old = rc->p[rc->keyslot].password;
437 pwd_old_len = rc->p[rc->keyslot].passwordLen;
440 } else if (rc->reencrypt_mode == ENCRYPT) {
443 pwd_new = rc->p[rc->keyslot].password;
444 pwd_new_len = rc->p[rc->keyslot].passwordLen;
448 if ((r = crypt_init_data_device(&cd, rc->header_file_org, rc->device)) ||
449 (r = crypt_load(cd, CRYPT_LUKS, NULL)))
452 log_verbose(_("Activating temporary device using old LUKS header."));
453 if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
454 opt_key_slot, pwd_old, pwd_old_len,
455 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
458 if ((r = crypt_init_data_device(&cd_new, rc->header_file_new, rc->device)) ||
459 (r = crypt_load(cd_new, CRYPT_LUKS, NULL)))
462 log_verbose(_("Activating temporary device using new LUKS header."));
463 if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
464 opt_key_slot, pwd_new, pwd_new_len,
465 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
472 log_err(_("Activation of temporary devices failed."));
476 static int set_pbkdf_params(struct crypt_device *cd, const char *dev_type)
478 const struct crypt_pbkdf_type *pbkdf_default;
479 struct crypt_pbkdf_type pbkdf = {};
481 pbkdf_default = crypt_get_pbkdf_default(dev_type);
485 pbkdf.type = opt_pbkdf ?: pbkdf_default->type;
486 pbkdf.hash = opt_hash ?: pbkdf_default->hash;
487 pbkdf.time_ms = (uint32_t)opt_iteration_time ?: pbkdf_default->time_ms;
488 if (strcmp(pbkdf.type, CRYPT_KDF_PBKDF2)) {
489 pbkdf.max_memory_kb = (uint32_t)opt_pbkdf_memory ?: pbkdf_default->max_memory_kb;
490 pbkdf.parallel_threads = (uint32_t)opt_pbkdf_parallel ?: pbkdf_default->parallel_threads;
493 if (opt_pbkdf_iterations) {
494 pbkdf.iterations = opt_pbkdf_iterations;
496 pbkdf.flags |= CRYPT_PBKDF_NO_BENCHMARK;
499 return crypt_set_pbkdf_type(cd, &pbkdf);
502 static int create_new_keyslot(struct reenc_ctx *rc, int keyslot,
503 struct crypt_device *cd_old,
504 struct crypt_device *cd_new)
510 if (cd_old && crypt_keyslot_status(cd_old, keyslot) == CRYPT_SLOT_UNBOUND) {
512 key = crypt_safe_alloc(key_size);
515 r = crypt_volume_key_get(cd_old, keyslot, key, &key_size,
516 rc->p[keyslot].password, rc->p[keyslot].passwordLen);
518 r = crypt_keyslot_add_by_key(cd_new, keyslot, key, key_size,
519 rc->p[keyslot].password, rc->p[keyslot].passwordLen,
520 CRYPT_VOLUME_KEY_NO_SEGMENT);
523 crypt_safe_free(key);
525 r = crypt_keyslot_add_by_volume_key(cd_new, keyslot, NULL, 0,
526 rc->p[keyslot].password, rc->p[keyslot].passwordLen);
531 static int create_new_header(struct reenc_ctx *rc, struct crypt_device *cd_old,
532 const char *cipher, const char *cipher_mode,
534 const char *key, int key_size,
536 uint64_t metadata_size,
537 uint64_t keyslots_size,
540 struct crypt_device *cd_new = NULL;
543 if ((r = crypt_init(&cd_new, rc->header_file_new)))
547 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
548 else if (opt_urandom)
549 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
551 r = set_pbkdf_params(cd_new, type);
553 log_err(_("Failed to set pbkdf parameters."));
557 r = crypt_set_data_offset(cd_new, rc->data_offset);
559 log_err(_("Failed to set data offset."));
563 r = crypt_set_metadata_size(cd_new, metadata_size, keyslots_size);
565 log_err(_("Failed to set metadata size."));
569 r = crypt_format(cd_new, type, cipher, cipher_mode, uuid, key, key_size, params);
573 log_verbose(_("New LUKS header for device %s created."), rc->device);
575 for (i = 0; i < crypt_keyslot_max(type); i++) {
576 if (!rc->p[i].password)
579 r = create_new_keyslot(rc, i, cd_old, cd_new);
583 tools_keyslot_msg(r, CREATED);
591 static int isLUKS2(const char *type)
593 return (type && !strcmp(type, CRYPT_LUKS2));
596 static int luks2_metadata_copy(struct reenc_ctx *rc)
598 const char *json, *type;
602 struct crypt_device *cd_old = NULL, *cd_new = NULL;
604 if (crypt_init(&cd_old, rc->header_file_tmp) ||
605 crypt_load(cd_old, CRYPT_LUKS2, NULL))
608 if (crypt_init(&cd_new, rc->header_file_new) ||
609 crypt_load(cd_new, CRYPT_LUKS2, NULL))
613 * we have to erase keyslots missing in new header so that we can
614 * transfer tokens from old header to new one
616 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++)
617 if (!rc->p[i].password && crypt_keyslot_status(cd_old, i) == CRYPT_SLOT_ACTIVE) {
618 r = crypt_keyslot_destroy(cd_old, i);
623 for (i = 0; i < MAX_TOKEN; i++) {
624 ti = crypt_token_status(cd_old, i, &type);
626 case CRYPT_TOKEN_INVALID:
627 log_dbg("Internal error.");
630 case CRYPT_TOKEN_INACTIVE:
632 case CRYPT_TOKEN_INTERNAL_UNKNOWN:
633 log_err(_("This version of cryptsetup-reencrypt can't handle new internal token type %s."), type);
636 case CRYPT_TOKEN_INTERNAL:
638 case CRYPT_TOKEN_EXTERNAL:
640 case CRYPT_TOKEN_EXTERNAL_UNKNOWN:
641 if (crypt_token_json_get(cd_old, i, &json) != i) {
642 log_dbg("Failed to get %s token (%d).", type, i);
646 if (crypt_token_json_set(cd_new, i, json) != i) {
647 log_dbg("Failed to create %s token (%d).", type, i);
654 if ((r = crypt_persistent_flags_get(cd_old, CRYPT_FLAGS_ACTIVATION, &flags))) {
655 log_err(_("Failed to read activation flags from backup header."));
658 if ((r = crypt_persistent_flags_set(cd_new, CRYPT_FLAGS_ACTIVATION, flags))) {
659 log_err(_("Failed to write activation flags to new header."));
662 if ((r = crypt_persistent_flags_get(cd_old, CRYPT_FLAGS_REQUIREMENTS, &flags))) {
663 log_err(_("Failed to read requirements from backup header."));
666 if ((r = crypt_persistent_flags_set(cd_new, CRYPT_FLAGS_REQUIREMENTS, flags)))
667 log_err(_("Failed to read requirements from backup header."));
671 unlink(rc->header_file_tmp);
676 static int backup_luks_headers(struct reenc_ctx *rc)
678 struct crypt_device *cd = NULL;
679 struct crypt_params_luks1 params = {0};
680 struct crypt_params_luks2 params2 = {0};
682 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
685 uint64_t mdata_size = 0, keyslots_size = 0;
688 log_dbg("Creating LUKS header backup for device %s.", hdr_device(rc));
690 if ((r = crypt_init(&cd, hdr_device(rc))) ||
691 (r = crypt_load(cd, CRYPT_LUKS, NULL)))
694 if ((r = crypt_header_backup(cd, CRYPT_LUKS, rc->header_file_org)))
696 if (isLUKS2(rc->type)) {
697 if ((r = crypt_header_backup(cd, CRYPT_LUKS2, rc->header_file_tmp)))
699 if ((r = stat(rc->header_file_tmp, &st)))
701 /* coverity[toctou] */
702 if ((r = chmod(rc->header_file_tmp, st.st_mode | S_IWUSR)))
705 log_verbose(_("%s header backup of device %s created."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", rc->device);
707 /* For decrypt, new header will be fake one, so we are done here. */
708 if (rc->reencrypt_mode == DECRYPT)
711 rc->data_offset = crypt_get_data_offset(cd) + ROUND_SECTOR(opt_reduce_size);
713 if ((r = create_empty_header(rc->header_file_new)))
716 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
717 params2.data_device = params.data_device = rc->device;
718 params2.sector_size = crypt_get_sector_size(cd);
721 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
723 log_err(_("No known cipher specification pattern detected."));
728 key_size = opt_key_size ? opt_key_size / 8 : crypt_get_volume_key_size(cd);
731 log_dbg("Keeping key from old header.");
732 key_size = crypt_get_volume_key_size(cd);
733 key = crypt_safe_alloc(key_size);
738 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, key, &key_size,
739 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
740 } else if (opt_master_key_file) {
741 log_dbg("Loading new key from file.");
742 r = tools_read_mk(opt_master_key_file, &key, key_size);
748 if (isLUKS2(crypt_get_type(cd)) && crypt_get_metadata_size(cd, &mdata_size, &keyslots_size))
751 r = create_new_header(rc, cd,
752 opt_cipher ? cipher : crypt_get_cipher(cd),
753 opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
760 isLUKS2(rc->type) ? (void*)¶ms2 : (void*)¶ms);
762 if (!r && isLUKS2(rc->type))
763 r = luks2_metadata_copy(rc);
766 crypt_safe_free(key);
768 log_err(_("Creation of LUKS backup headers failed."));
772 /* Create fake header for original device */
773 static int backup_fake_header(struct reenc_ctx *rc)
775 struct crypt_device *cd_new = NULL;
776 struct crypt_params_luks1 params = {0};
777 struct crypt_params_luks2 params2 = {0};
778 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
779 const char *header_file_fake;
782 log_dbg("Creating fake (cipher_null) header for %s device.",
783 (rc->reencrypt_mode == DECRYPT) ? "new" : "original");
785 header_file_fake = (rc->reencrypt_mode == DECRYPT) ? rc->header_file_new : rc->header_file_org;
788 opt_key_size = DEFAULT_LUKS1_KEYBITS;
791 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
793 log_err(_("No known cipher specification pattern detected."));
798 r = create_empty_header(header_file_fake);
802 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
803 params2.data_alignment = params.data_alignment = 0;
804 params2.data_device = params.data_device = rc->device;
805 params2.sector_size = crypt_get_sector_size(NULL);
806 params2.pbkdf = crypt_get_pbkdf_default(CRYPT_LUKS2);
808 r = crypt_init(&cd_new, header_file_fake);
812 r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb",
813 NO_UUID, NULL, opt_key_size / 8, ¶ms);
818 r = crypt_keyslot_add_by_volume_key(cd_new, rc->keyslot, NULL, 0,
819 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
824 /* The real header is backup header created in backup_luks_headers() */
825 if (rc->reencrypt_mode == DECRYPT) {
830 r = create_empty_header(rc->header_file_new);
834 params2.data_alignment = params.data_alignment = ROUND_SECTOR(opt_reduce_size);
835 r = create_new_header(rc, NULL,
836 opt_cipher ? cipher : DEFAULT_LUKS1_CIPHER,
837 opt_cipher ? cipher_mode : DEFAULT_LUKS1_MODE,
839 (opt_key_size ? opt_key_size : DEFAULT_LUKS1_KEYBITS) / 8,
843 isLUKS2(rc->type) ? (void*)¶ms2 : (void*)¶ms);
849 static void remove_headers(struct reenc_ctx *rc)
851 struct crypt_device *cd = NULL;
853 log_dbg("Removing headers.");
855 if (crypt_init(&cd, NULL))
857 crypt_set_log_callback(cd, _quiet_log, NULL);
858 if (*rc->header_file_org)
859 (void)crypt_deactivate(cd, rc->header_file_org);
860 if (*rc->header_file_new)
861 (void)crypt_deactivate(cd, rc->header_file_new);
865 static int restore_luks_header(struct reenc_ctx *rc)
868 struct crypt_device *cd = NULL;
871 log_dbg("Restoring header for %s from %s.", hdr_device(rc), rc->header_file_new);
874 * For new encryption and new detached header in file just move it.
875 * For existing file try to ensure we have preallocated space for restore.
877 if (opt_new && rc->device_header) {
878 r = stat(rc->device_header, &st);
880 r = rename(rc->header_file_new, rc->device_header);
882 } else if ((st.st_mode & S_IFMT) == S_IFREG &&
883 stat(rc->header_file_new, &st) != -1) {
884 /* coverity[toctou] */
885 fd = open(rc->device_header, O_WRONLY);
887 if (posix_fallocate(fd, 0, st.st_size)) {};
893 r = crypt_init(&cd, hdr_device(rc));
895 r = crypt_header_restore(cd, rc->type, rc->header_file_new);
901 log_err(_("Cannot restore %s header on device %s."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", hdr_device(rc));
903 log_verbose(_("%s header on device %s restored."), isLUKS2(rc->type) ? "LUKS2" : "LUKS1", hdr_device(rc));
909 static ssize_t read_buf(int fd, void *buf, size_t count)
911 size_t read_size = 0;
915 /* This expects that partial read is aligned in buffer */
916 s = read(fd, buf, count - read_size);
917 if (s == -1 && errno != EINTR)
920 return (ssize_t)read_size;
922 if (s != (ssize_t)count)
923 log_dbg("Partial read %zd / %zu.", s, count);
924 read_size += (size_t)s;
925 buf = (uint8_t*)buf + s;
927 } while (read_size != count);
929 return (ssize_t)count;
932 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
933 size_t block_size, void *buf, uint64_t *bytes)
937 log_dbg("Reencrypting in forward direction.");
939 if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
940 lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
941 log_err(_("Cannot seek to device offset."));
945 rc->resume_bytes = *bytes = rc->device_offset;
947 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
949 if (write_log(rc) < 0)
952 while (!quit && rc->device_offset < rc->device_size) {
953 s1 = read_buf(fd_old, buf, block_size);
954 if (s1 < 0 || ((size_t)s1 != block_size &&
955 (rc->device_offset + s1) != rc->device_size)) {
956 log_dbg("Read error, expecting %zu, got %zd.",
961 /* If device_size is forced, never write more than limit */
962 if ((s1 + rc->device_offset) > rc->device_size)
963 s1 = rc->device_size - rc->device_offset;
965 s2 = write(fd_new, buf, s1);
967 log_dbg("Write error, expecting %zu, got %zd.",
972 rc->device_offset += s1;
973 if (opt_write_log && write_log(rc) < 0)
976 if (opt_fsync && fsync(fd_new) < 0) {
977 log_dbg("Write error, fsync.");
981 *bytes += (uint64_t)s2;
983 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
986 return quit ? -EAGAIN : 0;
989 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
990 size_t block_size, void *buf, uint64_t *bytes)
992 ssize_t s1, s2, working_block;
993 off64_t working_offset;
995 log_dbg("Reencrypting in backward direction.");
997 if (!rc->in_progress) {
998 rc->device_offset = rc->device_size;
999 rc->resume_bytes = 0;
1002 rc->resume_bytes = rc->device_size - rc->device_offset;
1003 *bytes = rc->resume_bytes;
1006 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1008 if (write_log(rc) < 0)
1011 /* dirty the device during ENCRYPT mode */
1014 while (!quit && rc->device_offset) {
1015 if (rc->device_offset < block_size) {
1017 working_block = rc->device_offset;
1019 working_offset = rc->device_offset - block_size;
1020 working_block = block_size;
1023 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
1024 lseek64(fd_new, working_offset, SEEK_SET) < 0) {
1025 log_err(_("Cannot seek to device offset."));
1029 s1 = read_buf(fd_old, buf, working_block);
1030 if (s1 < 0 || (s1 != working_block)) {
1031 log_dbg("Read error, expecting %zu, got %zd.",
1036 s2 = write(fd_new, buf, working_block);
1038 log_dbg("Write error, expecting %zu, got %zd.",
1043 rc->device_offset -= s1;
1044 if (opt_write_log && write_log(rc) < 0)
1047 if (opt_fsync && fsync(fd_new) < 0) {
1048 log_dbg("Write error, fsync.");
1052 *bytes += (uint64_t)s2;
1054 tools_reencrypt_progress(rc->device_size, *bytes, NULL);
1057 return quit ? -EAGAIN : 0;
1060 static void zero_rest_of_device(int fd, size_t block_size, void *buf,
1061 uint64_t *bytes, uint64_t offset)
1065 log_dbg("Zeroing rest of device.");
1067 if (lseek64(fd, offset, SEEK_SET) < 0) {
1068 log_dbg("Cannot seek to device offset.");
1072 memset(buf, 0, block_size);
1075 while (!quit && *bytes) {
1076 if (*bytes < (uint64_t)s1)
1079 s2 = write(fd, buf, s1);
1081 log_dbg("Write error, expecting %zd, got %zd.",
1086 if (opt_fsync && fsync(fd) < 0) {
1087 log_dbg("Write error, fsync.");
1095 static int copy_data(struct reenc_ctx *rc)
1097 size_t block_size = opt_bsize * 1024 * 1024;
1098 int fd_old = -1, fd_new = -1;
1103 log_dbg("Data copy preparation.");
1105 fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
1107 log_err(_("Cannot open temporary LUKS device."));
1111 fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
1113 log_err(_("Cannot open temporary LUKS device."));
1117 if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size_org_real) < 0) {
1118 log_err(_("Cannot get device size."));
1122 if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_new_real) < 0) {
1123 log_err(_("Cannot get device size."));
1127 if (opt_device_size)
1128 rc->device_size = opt_device_size;
1129 else if (rc->reencrypt_mode == DECRYPT)
1130 rc->device_size = rc->device_size_org_real;
1132 rc->device_size = rc->device_size_new_real;
1134 if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
1135 log_err(_("Allocation of aligned memory failed."));
1142 if (rc->reencrypt_direction == FORWARD)
1143 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
1145 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
1147 /* Zero (wipe) rest of now plain-only device when decrypting.
1148 * (To not leave any sign of encryption here.) */
1149 if (!r && rc->reencrypt_mode == DECRYPT &&
1150 rc->device_size_new_real > rc->device_size_org_real) {
1151 bytes = rc->device_size_new_real - rc->device_size_org_real;
1152 zero_rest_of_device(fd_new, block_size, buf, &bytes, rc->device_size_org_real);
1157 if (r < 0 && r != -EAGAIN)
1158 log_err(_("IO error during reencryption."));
1160 (void)write_log(rc);
1170 static int initialize_uuid(struct reenc_ctx *rc)
1172 struct crypt_device *cd = NULL;
1176 log_dbg("Initialising UUID.");
1179 rc->device_uuid = strdup(NO_UUID);
1180 rc->type = luksType(opt_type);
1184 if (opt_decrypt && opt_uuid) {
1185 r = uuid_parse(opt_uuid, device_uuid);
1187 rc->device_uuid = strdup(opt_uuid);
1189 log_err(_("Provided UUID is invalid."));
1194 /* Try to load LUKS from device */
1195 if ((r = crypt_init(&cd, hdr_device(rc))))
1197 crypt_set_log_callback(cd, _quiet_log, NULL);
1198 r = crypt_load(cd, CRYPT_LUKS, NULL);
1200 rc->device_uuid = strdup(crypt_get_uuid(cd));
1202 /* Reencryption already in progress - magic header? */
1203 r = device_check(rc, hdr_device(rc), CHECK_UNUSABLE);
1206 rc->type = isLUKS2(crypt_get_type(cd)) ? CRYPT_LUKS2 : CRYPT_LUKS1;
1212 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
1213 const char *msg, int slot_to_check, int check, int verify)
1215 crypt_keyslot_info ki;
1217 int r = -EINVAL, retry_count;
1220 /* mode ENCRYPT call this without header */
1221 if (cd && slot_to_check != CRYPT_ANY_SLOT) {
1222 ki = crypt_keyslot_status(cd, slot_to_check);
1223 if (ki < CRYPT_SLOT_ACTIVE)
1226 ki = CRYPT_SLOT_ACTIVE;
1228 retry_count = opt_tries ?: 1;
1229 while (retry_count--) {
1230 r = tools_get_key(msg, &password, &passwordLen, 0, 0,
1231 NULL /*opt_key_file*/, 0, verify, 0 /*pwquality*/, cd);
1235 crypt_safe_free(password);
1242 r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
1243 password, passwordLen, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY);
1245 r = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check;
1248 crypt_safe_free(password);
1252 if (r < 0 && r != -EPERM)
1256 tools_keyslot_msg(r, UNLOCKED);
1257 rc->p[r].password = password;
1258 rc->p[r].passwordLen = passwordLen;
1259 if (ki != CRYPT_SLOT_UNBOUND)
1263 tools_passphrase_msg(r);
1272 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
1278 r = tools_get_key(NULL, &password, &passwordLen, opt_keyfile_offset,
1279 opt_keyfile_size, opt_key_file, 0, 0, 0, cd);
1283 /* mode ENCRYPT call this without header */
1285 r = crypt_activate_by_passphrase(cd, NULL, slot_check, password,
1289 * Allow keyslot only if it is last slot or if user explicitly
1290 * specify which slot to use (IOW others will be disabled).
1292 if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
1293 crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
1294 log_err(_("Key file can be used only with --key-slot or with "
1295 "exactly one key slot active."));
1299 r = slot_check == CRYPT_ANY_SLOT ? 0 : slot_check;
1303 crypt_safe_free(password);
1304 tools_passphrase_msg(r);
1307 rc->p[r].password = password;
1308 rc->p[r].passwordLen = passwordLen;
1317 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
1319 struct crypt_device *cd = NULL;
1323 log_dbg("Passphrases initialization.");
1325 if (rc->reencrypt_mode == ENCRYPT && !rc->in_progress) {
1327 r = init_keyfile(rc, NULL, opt_key_slot);
1329 r = init_passphrase1(rc, NULL, _("Enter new passphrase: "), opt_key_slot, 0, 1);
1330 return r > 0 ? 0 : r;
1333 if ((r = crypt_init_data_device(&cd, device, rc->device)) ||
1334 (r = crypt_load(cd, CRYPT_LUKS, NULL))) {
1339 if (opt_key_slot != CRYPT_ANY_SLOT)
1340 snprintf(msg, sizeof(msg),
1341 _("Enter passphrase for key slot %d: "), opt_key_slot);
1343 snprintf(msg, sizeof(msg), _("Enter any existing passphrase: "));
1346 r = init_keyfile(rc, cd, opt_key_slot);
1347 } else if (rc->in_progress ||
1348 opt_key_slot != CRYPT_ANY_SLOT ||
1349 rc->reencrypt_mode == DECRYPT) {
1350 r = init_passphrase1(rc, cd, msg, opt_key_slot, 1, 0);
1351 } else for (i = 0; i < crypt_keyslot_max(crypt_get_type(cd)); i++) {
1352 snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i);
1353 r = init_passphrase1(rc, cd, msg, i, 1, 0);
1363 return r > 0 ? 0 : r;
1366 static int initialize_context(struct reenc_ctx *rc, const char *device)
1368 log_dbg("Initialising reencryption context.");
1372 /* FIXME: replace MAX_KEYSLOT with crypt_keyslot_max(CRYPT_LUKS2) */
1373 if (crypt_keyslot_max(CRYPT_LUKS2) > MAX_SLOT) {
1374 log_dbg("Internal error");
1378 if (!(rc->device = strndup(device, PATH_MAX)))
1381 if (opt_header_device && !(rc->device_header = strndup(opt_header_device, PATH_MAX)))
1384 if (device_check(rc, rc->device, CHECK_OPEN) < 0)
1387 if (initialize_uuid(rc)) {
1388 log_err(_("Device %s is not a valid LUKS device."), device);
1392 if (opt_key_slot != CRYPT_ANY_SLOT &&
1393 opt_key_slot >= crypt_keyslot_max(rc->type)) {
1394 log_err(_("Key slot is invalid."));
1398 /* Prepare device names */
1399 if (snprintf(rc->log_file, PATH_MAX,
1400 "LUKS-%s.log", rc->device_uuid) < 0)
1402 if (snprintf(rc->header_file_org, PATH_MAX,
1403 "LUKS-%s.org", rc->device_uuid) < 0)
1405 if (snprintf(rc->header_file_new, PATH_MAX,
1406 "LUKS-%s.new", rc->device_uuid) < 0)
1408 if (snprintf(rc->header_file_tmp, PATH_MAX,
1409 "LUKS-%s.tmp", rc->device_uuid) < 0)
1412 /* Paths to encrypted devices */
1413 if (snprintf(rc->crypt_path_org, PATH_MAX,
1414 "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
1416 if (snprintf(rc->crypt_path_new, PATH_MAX,
1417 "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
1422 if (open_log(rc) < 0) {
1423 log_err(_("Cannot open reencryption log file."));
1427 if (!rc->in_progress) {
1429 log_err(_("No decryption in progress, provided UUID can "
1430 "be used only to resume suspended decryption process."));
1434 if (!opt_reduce_size)
1435 rc->reencrypt_direction = FORWARD;
1437 rc->reencrypt_direction = BACKWARD;
1438 rc->device_offset = (uint64_t)~0;
1442 rc->reencrypt_mode = ENCRYPT;
1443 else if (opt_decrypt)
1444 rc->reencrypt_mode = DECRYPT;
1446 rc->reencrypt_mode = REENCRYPT;
1452 static void destroy_context(struct reenc_ctx *rc)
1456 log_dbg("Destroying reencryption context.");
1462 unlink(rc->log_file);
1463 unlink(rc->header_file_org);
1464 unlink(rc->header_file_new);
1465 unlink(rc->header_file_tmp);
1468 for (i = 0; i < MAX_SLOT; i++)
1469 crypt_safe_free(rc->p[i].password);
1472 free(rc->device_header);
1473 free(rc->device_uuid);
1476 static int luks2_change_pbkdf_params(struct reenc_ctx *rc)
1479 struct crypt_device *cd = NULL;
1481 if ((r = initialize_passphrase(rc, hdr_device(rc))))
1484 if (crypt_init(&cd, hdr_device(rc)) ||
1485 crypt_load(cd, CRYPT_LUKS2, NULL)) {
1490 if ((r = set_pbkdf_params(cd, CRYPT_LUKS2)))
1493 log_dbg("LUKS2 keyslot pbkdf params change.");
1497 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++) {
1498 if (!rc->p[i].password)
1500 if ((r = crypt_keyslot_change_by_passphrase(cd, i, i,
1501 rc->p[i].password, rc->p[i].passwordLen,
1502 rc->p[i].password, rc->p[i].passwordLen)) < 0)
1504 log_verbose(_("Changed pbkdf parameters in keyslot %i."), r);
1511 /* see create_new_header */
1512 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS2); i++)
1513 if (!rc->p[i].password)
1514 (void)crypt_keyslot_destroy(cd, i);
1520 static int run_reencrypt(const char *device)
1523 static struct reenc_ctx rc = {
1529 if (initialize_context(&rc, device))
1532 /* short-circuit LUKS2 keyslot parameters change */
1533 if (opt_keep_key && isLUKS2(rc.type)) {
1534 r = luks2_change_pbkdf_params(&rc);
1538 log_dbg("Running reencryption.");
1540 if (!rc.in_progress) {
1541 if ((r = initialize_passphrase(&rc, hdr_device(&rc))))
1544 log_dbg("Storing backup of LUKS headers.");
1545 if (rc.reencrypt_mode == ENCRYPT) {
1546 /* Create fake header for existing device */
1547 if ((r = backup_fake_header(&rc)))
1550 if ((r = backup_luks_headers(&rc)))
1552 /* Create fake header for decrypted device */
1553 if (rc.reencrypt_mode == DECRYPT &&
1554 (r = backup_fake_header(&rc)))
1556 if ((r = device_check(&rc, hdr_device(&rc), MAKE_UNUSABLE)))
1560 if ((r = initialize_passphrase(&rc, opt_decrypt ? rc.header_file_org : rc.header_file_new)))
1564 if (!opt_keep_key) {
1565 log_dbg("Running data area reencryption.");
1566 if ((r = activate_luks_headers(&rc)))
1569 if ((r = copy_data(&rc)))
1572 log_dbg("Keeping existing key, skipping data area reencryption.");
1574 // FIXME: fix error path above to not skip this
1575 if (rc.reencrypt_mode != DECRYPT)
1576 r = restore_luks_header(&rc);
1580 destroy_context(&rc);
1584 static void help(poptContext popt_context,
1585 enum poptCallbackReason reason __attribute__((unused)),
1586 struct poptOption *key,
1587 const char *arg __attribute__((unused)),
1588 void *data __attribute__((unused)))
1590 if (key->shortName == '?') {
1591 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1592 poptPrintHelp(popt_context, stdout, 0);
1593 poptFreeContext(popt_context);
1595 } else if (key->shortName == 'V') {
1596 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1597 poptFreeContext(popt_context);
1600 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1603 int main(int argc, const char **argv)
1605 static struct poptOption popt_help_options[] = {
1606 { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL },
1607 { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL },
1608 { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL },
1609 { "version",'V', POPT_ARG_NONE, NULL, 0, N_("Print package version"), NULL },
1612 static struct poptOption popt_options[] = {
1613 { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1614 { "verbose", 'v', POPT_ARG_NONE, &opt_verbose, 0, N_("Shows more detailed error messages"), NULL },
1615 { "debug", '\0', POPT_ARG_NONE, &opt_debug, 0, N_("Show debug messages"), NULL },
1616 { "block-size", 'B', POPT_ARG_INT, &opt_bsize, 0, N_("Reencryption block size"), N_("MiB") },
1617 { "cipher", 'c', POPT_ARG_STRING, &opt_cipher, 0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1618 { "key-size", 's', POPT_ARG_INT, &opt_key_size, 0, N_("The size of the encryption key"), N_("BITS") },
1619 { "hash", 'h', POPT_ARG_STRING, &opt_hash, 0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1620 { "keep-key", '\0', POPT_ARG_NONE, &opt_keep_key, 0, N_("Do not change key, no data area reencryption"), NULL },
1621 { "key-file", 'd', POPT_ARG_STRING, &opt_key_file, 0, N_("Read the key from a file"), NULL },
1622 { "master-key-file", '\0', POPT_ARG_STRING, &opt_master_key_file, 0, N_("Read new volume (master) key from file"), NULL },
1623 { "iter-time", 'i', POPT_ARG_INT, &opt_iteration_time, 0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1624 { "batch-mode", 'q', POPT_ARG_NONE, &opt_batch_mode, 0, N_("Do not ask for confirmation"), NULL },
1625 { "progress-frequency",'\0', POPT_ARG_INT, &opt_progress_frequency, 0, N_("Progress line update (in seconds)"), N_("secs") },
1626 { "tries", 'T', POPT_ARG_INT, &opt_tries, 0, N_("How often the input of the passphrase can be retried"), NULL },
1627 { "use-random", '\0', POPT_ARG_NONE, &opt_random, 0, N_("Use /dev/random for generating volume key"), NULL },
1628 { "use-urandom", '\0', POPT_ARG_NONE, &opt_urandom, 0, N_("Use /dev/urandom for generating volume key"), NULL },
1629 { "use-directio", '\0', POPT_ARG_NONE, &opt_directio, 0, N_("Use direct-io when accessing devices"), NULL },
1630 { "use-fsync", '\0', POPT_ARG_NONE, &opt_fsync, 0, N_("Use fsync after each block"), NULL },
1631 { "write-log", '\0', POPT_ARG_NONE, &opt_write_log, 0, N_("Update log file after every block"), NULL },
1632 { "key-slot", 'S', POPT_ARG_INT, &opt_key_slot, 0, N_("Use only this slot (others will be disabled)"), NULL },
1633 { "keyfile-offset", '\0', POPT_ARG_LONG, &opt_keyfile_offset, 0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1634 { "keyfile-size", 'l', POPT_ARG_LONG, &opt_keyfile_size, 0, N_("Limits the read from keyfile"), N_("bytes") },
1635 { "reduce-device-size",'\0', POPT_ARG_STRING, &opt_reduce_size_str, 0, N_("Reduce data device size (move data offset). DANGEROUS!"), N_("bytes") },
1636 { "device-size", '\0', POPT_ARG_STRING, &opt_device_size_str, 0, N_("Use only specified device size (ignore rest of device). DANGEROUS!"), N_("bytes") },
1637 { "new", 'N', POPT_ARG_NONE, &opt_new, 0, N_("Create new header on not encrypted device"), NULL },
1638 { "decrypt", '\0', POPT_ARG_NONE, &opt_decrypt, 0, N_("Permanently decrypt device (remove encryption)"), NULL },
1639 { "uuid", '\0', POPT_ARG_STRING, &opt_uuid, 0, N_("The UUID used to resume decryption"), NULL },
1640 { "type", '\0', POPT_ARG_STRING, &opt_type, 0, N_("Type of LUKS metadata: luks1, luks2"), NULL },
1641 { "pbkdf", '\0', POPT_ARG_STRING, &opt_pbkdf, 0, N_("PBKDF algorithm (for LUKS2): argon2i, argon2id, pbkdf2"), NULL },
1642 { "pbkdf-memory", '\0', POPT_ARG_LONG, &opt_pbkdf_memory, 0, N_("PBKDF memory cost limit"), N_("kilobytes") },
1643 { "pbkdf-parallel", '\0', POPT_ARG_LONG, &opt_pbkdf_parallel, 0, N_("PBKDF parallel cost"), N_("threads") },
1644 { "pbkdf-force-iterations",'\0',POPT_ARG_LONG, &opt_pbkdf_iterations, 0, N_("PBKDF iterations cost (forced, disables benchmark)"), NULL },
1645 { "header", '\0', POPT_ARG_STRING, &opt_header_device, 0, N_("Device or file with separated LUKS header"), NULL },
1648 poptContext popt_context;
1651 crypt_set_log_callback(NULL, tool_log, NULL);
1653 setlocale(LC_ALL, "");
1654 bindtextdomain(PACKAGE, LOCALEDIR);
1655 textdomain(PACKAGE);
1657 popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1658 poptSetOtherOptionHelp(popt_context,
1659 _("[OPTION...] <device>"));
1661 while((r = poptGetNextOpt(popt_context)) > 0) ;
1663 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1664 poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1666 if (!opt_batch_mode)
1667 log_verbose(_("Reencryption will change: %s%s%s%s%s%s."),
1668 opt_keep_key ? "" : _("volume key"),
1669 (!opt_keep_key && opt_hash) ? ", " : "",
1670 opt_hash ? _("set hash to ") : "", opt_hash ?: "",
1671 opt_cipher ? _(", set cipher to "): "", opt_cipher ?: "");
1673 action_argv = poptGetArgs(popt_context);
1675 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1676 poptGetInvocationName(popt_context));
1678 if (opt_random && opt_urandom)
1679 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1680 poptGetInvocationName(popt_context));
1682 if (opt_bsize < 0 || opt_key_size < 0 || opt_iteration_time < 0 ||
1683 opt_tries < 0 || opt_keyfile_offset < 0 || opt_key_size < 0 ||
1684 opt_pbkdf_iterations < 0 || opt_pbkdf_memory < 0 ||
1685 opt_pbkdf_parallel < 0) {
1686 usage(popt_context, EXIT_FAILURE,
1687 _("Negative number for option not permitted."),
1688 poptGetInvocationName(popt_context));
1691 if (opt_pbkdf && crypt_parse_pbkdf(opt_pbkdf, &opt_pbkdf))
1692 usage(popt_context, EXIT_FAILURE,
1693 _("Password-based key derivation function (PBKDF) can be only pbkdf2 or argon2i/argon2id."),
1694 poptGetInvocationName(popt_context));
1696 if (opt_pbkdf_iterations && opt_iteration_time)
1697 usage(popt_context, EXIT_FAILURE,
1698 _("PBKDF forced iterations cannot be combined with iteration time option."),
1699 poptGetInvocationName(popt_context));
1701 if (opt_bsize < 1 || opt_bsize > 64)
1702 usage(popt_context, EXIT_FAILURE,
1703 _("Only values between 1 MiB and 64 MiB allowed for reencryption block size."),
1704 poptGetInvocationName(popt_context));
1706 if (opt_key_size % 8)
1707 usage(popt_context, EXIT_FAILURE,
1708 _("Key size must be a multiple of 8 bits"),
1709 poptGetInvocationName(popt_context));
1711 if (opt_key_slot != CRYPT_ANY_SLOT &&
1712 (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS2)))
1713 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1714 poptGetInvocationName(popt_context));
1716 if (opt_random && opt_urandom)
1717 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1718 poptGetInvocationName(popt_context));
1720 if (opt_device_size_str &&
1721 tools_string_to_size(NULL, opt_device_size_str, &opt_device_size))
1722 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1723 poptGetInvocationName(popt_context));
1725 if (opt_reduce_size_str &&
1726 tools_string_to_size(NULL, opt_reduce_size_str, &opt_reduce_size))
1727 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1728 poptGetInvocationName(popt_context));
1729 if (opt_reduce_size > 64 * 1024 * 1024)
1730 usage(popt_context, EXIT_FAILURE, _("Maximum device reduce size is 64 MiB."),
1731 poptGetInvocationName(popt_context));
1732 if (opt_reduce_size % SECTOR_SIZE)
1733 usage(popt_context, EXIT_FAILURE, _("Reduce size must be multiple of 512 bytes sector."),
1734 poptGetInvocationName(popt_context));
1736 if (opt_new && (!opt_reduce_size && !opt_header_device))
1737 usage(popt_context, EXIT_FAILURE, _("Option --new must be used together with --reduce-device-size or --header."),
1738 poptGetInvocationName(popt_context));
1740 if (opt_keep_key && (opt_cipher || opt_new || opt_master_key_file))
1741 usage(popt_context, EXIT_FAILURE, _("Option --keep-key can be used only with --hash, --iter-time or --pbkdf-force-iterations."),
1742 poptGetInvocationName(popt_context));
1744 if (opt_new && opt_decrypt)
1745 usage(popt_context, EXIT_FAILURE, _("Option --new cannot be used together with --decrypt."),
1746 poptGetInvocationName(popt_context));
1748 if (opt_decrypt && (opt_cipher || opt_hash || opt_reduce_size || opt_keep_key || opt_device_size))
1749 usage(popt_context, EXIT_FAILURE, _("Option --decrypt is incompatible with specified parameters."),
1750 poptGetInvocationName(popt_context));
1752 if (opt_uuid && !opt_decrypt)
1753 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only together with --decrypt."),
1754 poptGetInvocationName(popt_context));
1756 if (!luksType(opt_type))
1757 usage(popt_context, EXIT_FAILURE, _("Invalid luks type. Use one of these: 'luks', 'luks1' or 'luks2'."),
1758 poptGetInvocationName(popt_context));
1762 crypt_set_debug_level(-1);
1763 dbg_version_and_cmd(argc, argv);
1766 r = run_reencrypt(action_argv[0]);
1768 poptFreeContext(popt_context);
1770 return translate_errno(r);