2 * cryptsetup - LUKS1 utility for offline re-encryption
4 * Copyright (C) 2012-2023 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2012-2023 Milan Broz
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 <sys/ioctl.h>
24 #include <uuid/uuid.h>
26 #include "cryptsetup.h"
27 #include "cryptsetup_args.h"
28 #include "utils_luks.h"
30 #define NO_UUID "cafecafe-cafe-cafe-cafe-cafecafeeeee"
32 extern int64_t data_shift;
41 uint64_t device_size; /* overridden by parameter */
42 uint64_t device_size_new_real;
43 uint64_t device_size_org_real;
44 uint64_t device_offset;
45 uint64_t device_shift;
50 enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
51 enum { REENCRYPT = 0, ENCRYPT = 1, DECRYPT = 2 } reencrypt_mode;
53 char header_file_org[PATH_MAX];
54 char header_file_new[PATH_MAX];
55 char log_file[PATH_MAX];
57 char crypt_path_org[PATH_MAX];
58 char crypt_path_new[PATH_MAX];
60 char log_buf[SECTOR_SIZE];
68 uint64_t resume_bytes;
71 char MAGIC[] = {'L','U','K','S', 0xba, 0xbe};
72 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
82 static void _quiet_log(int level, const char *msg, void *usrptr)
84 if (!ARG_SET(OPT_DEBUG_ID))
86 tool_log(level, msg, usrptr);
89 static int alignment(int fd)
93 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
99 static size_t pagesize(void)
101 long r = sysconf(_SC_PAGESIZE);
102 return r < 0 ? 4096 : (size_t)r;
105 static const char *hdr_device(const struct reenc_ctx *rc)
107 return rc->device_header ?: rc->device;
110 /* Depends on the first two fields of LUKS1 header format, magic and version */
111 static int device_check(struct reenc_ctx *rc, const char *device, header_magic set_magic, bool exclusive)
117 size_t buf_size = pagesize();
120 if (stat(device, &st)) {
121 log_err(_("Cannot open device %s."), device);
125 /* coverity[toctou] */
126 devfd = open(device, O_RDWR | ((S_ISBLK(st.st_mode) && exclusive) ? O_EXCL : 0)); /* lgtm[cpp/toctou-race-condition] */
128 if (errno == EBUSY) {
129 log_err(_("Cannot exclusively open %s, device in use."),
133 log_err(_("Cannot open device %s."), device);
137 if (set_magic == CHECK_OPEN) {
142 if (posix_memalign((void *)&buf, alignment(devfd), buf_size)) {
143 log_err(_("Allocation of aligned memory failed."));
148 s = read(devfd, buf, buf_size);
149 if (s < 0 || s != (ssize_t)buf_size) {
150 log_err(_("Cannot read device %s."), device);
155 /* Be sure that we do not process new version of header */
156 memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
157 version = be16_to_cpu(version);
159 if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
161 log_verbose(_("Marking LUKS1 device %s unusable."), device);
162 memcpy(buf, NOMAGIC, MAGIC_L);
164 } else if (set_magic == CHECK_UNUSABLE && version == 1) {
165 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
167 rc->device_uuid = strndup(&buf[0xa8], 40);
172 if (!r && version == 1) {
173 if (lseek(devfd, 0, SEEK_SET) == -1)
175 s = write(devfd, buf, buf_size);
176 if (s < 0 || s != (ssize_t)buf_size || fsync(devfd) < 0) {
177 log_err(_("Cannot write device %s."), device);
180 if (rc && s > 0 && set_magic == MAKE_UNUSABLE)
184 log_dbg("LUKS signature check failed for %s.", device);
187 memset(buf, 0, buf_size);
193 static int create_empty_header(const char *new_file)
197 log_dbg("Creating empty file %s of size 4096.", new_file);
199 /* coverity[toctou] */
200 fd = open(new_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
201 if (fd == -1 || posix_fallocate(fd, 0, 4096))
209 static int write_log(struct reenc_ctx *rc)
213 memset(rc->log_buf, 0, SECTOR_SIZE);
214 if (snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
215 "version = %d\nUUID = %s\ndirection = %d\nmode = %d\n"
216 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
217 2, rc->device_uuid, rc->reencrypt_direction, rc->reencrypt_mode,
218 rc->device_offset, rc->device_shift) < 0)
221 if (lseek(rc->log_fd, 0, SEEK_SET) == -1)
224 r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
225 if (r < 0 || r != SECTOR_SIZE) {
226 log_err(_("Cannot write reencryption log file."));
233 static int parse_line_log(struct reenc_ctx *rc, const char *line)
239 /* whole line is comment */
243 if (sscanf(line, "version = %d", &i) == 1) {
244 if (i < 1 || i > 2) {
245 log_dbg("Log: Unexpected version = %i", i);
248 } else if (sscanf(line, "UUID = %40s", s) == 1) {
249 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
250 log_dbg("Log: Unexpected UUID %s", s);
253 } else if (sscanf(line, "direction = %d", &i) == 1) {
254 log_dbg("Log: direction = %i", i);
255 rc->reencrypt_direction = i;
256 } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
257 log_dbg("Log: offset = %" PRIu64, u64);
258 rc->device_offset = u64;
259 } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
260 log_dbg("Log: shift = %" PRIu64, u64);
261 rc->device_shift = u64;
262 } else if (sscanf(line, "mode = %d", &i) == 1) { /* added in v2 */
263 log_dbg("Log: mode = %i", i);
264 rc->reencrypt_mode = i;
265 if (rc->reencrypt_mode != REENCRYPT &&
266 rc->reencrypt_mode != ENCRYPT &&
267 rc->reencrypt_mode != DECRYPT)
275 static int parse_log(struct reenc_ctx *rc)
280 s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
282 log_err(_("Cannot read reencryption log file."));
286 rc->log_buf[SECTOR_SIZE - 1] = '\0';
289 end = strchr(start, '\n');
292 if (parse_line_log(rc, start)) {
293 log_err(_("Wrong log format."));
304 static void close_log(struct reenc_ctx *rc)
306 log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
307 if (rc->log_fd != -1)
311 static int open_log(struct reenc_ctx *rc)
313 int flags = ARG_SET(OPT_USE_FSYNC_ID) ? O_SYNC : 0;
315 rc->log_fd = open(rc->log_file, O_RDWR|O_EXCL|O_CREAT|flags, S_IRUSR|S_IWUSR);
316 if (rc->log_fd != -1) {
317 log_dbg("Created LUKS reencryption log file %s.", rc->log_file);
319 } else if (errno == EEXIST) {
320 log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file);
321 rc->log_fd = open(rc->log_file, O_RDWR|flags);
322 rc->in_progress = true;
325 if (rc->log_fd == -1)
328 if (!rc->in_progress && write_log(rc) < 0) {
333 /* Be sure it is correct format */
334 return parse_log(rc);
337 static int activate_luks_headers(struct reenc_ctx *rc)
339 struct crypt_device *cd = NULL, *cd_new = NULL;
340 const char *pwd_old, *pwd_new, pwd_empty[] = "";
341 size_t pwd_old_len, pwd_new_len;
344 log_dbg("Activating LUKS devices from headers.");
346 /* Never use real password for empty header processing */
347 if (rc->reencrypt_mode == REENCRYPT) {
348 pwd_old = rc->p[rc->keyslot].password;
349 pwd_old_len = rc->p[rc->keyslot].passwordLen;
351 pwd_new_len = pwd_old_len;
352 } else if (rc->reencrypt_mode == DECRYPT) {
353 pwd_old = rc->p[rc->keyslot].password;
354 pwd_old_len = rc->p[rc->keyslot].passwordLen;
357 } else if (rc->reencrypt_mode == ENCRYPT) {
360 pwd_new = rc->p[rc->keyslot].password;
361 pwd_new_len = rc->p[rc->keyslot].passwordLen;
365 if ((r = crypt_init_data_device(&cd, rc->header_file_org, rc->device)) ||
366 (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
369 log_verbose(_("Activating temporary device using old LUKS header."));
370 if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
371 ARG_INT32(OPT_KEY_SLOT_ID), pwd_old, pwd_old_len,
372 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
375 if ((r = crypt_init_data_device(&cd_new, rc->header_file_new, rc->device)) ||
376 (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)))
379 log_verbose(_("Activating temporary device using new LUKS header."));
380 if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
381 ARG_INT32(OPT_KEY_SLOT_ID), pwd_new, pwd_new_len,
382 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
389 log_err(_("Activation of temporary devices failed."));
393 static int create_new_keyslot(struct reenc_ctx *rc, int keyslot,
394 struct crypt_device *cd_old,
395 struct crypt_device *cd_new)
401 if (cd_old && crypt_keyslot_status(cd_old, keyslot) == CRYPT_SLOT_UNBOUND) {
403 key = crypt_safe_alloc(key_size);
406 r = crypt_volume_key_get(cd_old, keyslot, key, &key_size,
407 rc->p[keyslot].password, rc->p[keyslot].passwordLen);
409 r = crypt_keyslot_add_by_key(cd_new, keyslot, key, key_size,
410 rc->p[keyslot].password, rc->p[keyslot].passwordLen,
411 CRYPT_VOLUME_KEY_NO_SEGMENT);
414 crypt_safe_free(key);
416 r = crypt_keyslot_add_by_volume_key(cd_new, keyslot, NULL, 0,
417 rc->p[keyslot].password, rc->p[keyslot].passwordLen);
422 static int create_new_header(struct reenc_ctx *rc, struct crypt_device *cd_old,
423 const char *cipher, const char *cipher_mode,
425 const char *key, int key_size,
426 uint64_t metadata_size,
427 uint64_t keyslots_size,
430 struct crypt_device *cd_new = NULL;
433 if ((r = crypt_init(&cd_new, rc->header_file_new)))
436 if (ARG_SET(OPT_USE_RANDOM_ID))
437 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
438 else if (ARG_SET(OPT_USE_URANDOM_ID))
439 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
441 r = set_pbkdf_params(cd_new, CRYPT_LUKS1);
443 log_err(_("Failed to set pbkdf parameters."));
447 r = crypt_set_data_offset(cd_new, rc->data_offset);
449 log_err(_("Failed to set data offset."));
453 r = crypt_set_metadata_size(cd_new, metadata_size, keyslots_size);
455 log_err(_("Failed to set metadata size."));
459 r = crypt_format(cd_new, CRYPT_LUKS1, cipher, cipher_mode, uuid, key, key_size, params);
463 log_verbose(_("New LUKS header for device %s created."), rc->device);
465 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
466 if (!rc->p[i].password)
469 r = create_new_keyslot(rc, i, cd_old, cd_new);
473 tools_keyslot_msg(r, CREATED);
481 static int backup_luks_headers(struct reenc_ctx *rc)
483 struct crypt_device *cd = NULL;
484 struct crypt_params_luks1 params = {0};
485 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
488 uint64_t mdata_size = 0, keyslots_size = 0;
491 log_dbg("Creating LUKS header backup for device %s.", hdr_device(rc));
493 if ((r = crypt_init(&cd, hdr_device(rc))) ||
494 (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
497 if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org)))
500 log_verbose(_("%s header backup of device %s created."), "LUKS1", rc->device);
502 /* For decrypt, new header will be fake one, so we are done here. */
503 if (rc->reencrypt_mode == DECRYPT)
506 rc->data_offset = crypt_get_data_offset(cd) + ROUND_SECTOR(ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID));
508 if ((r = create_empty_header(rc->header_file_new)))
511 params.hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH;
512 params.data_device = rc->device;
514 if (ARG_SET(OPT_CIPHER_ID)) {
515 r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode);
517 log_err(_("No known cipher specification pattern detected."));
522 key_size = ARG_SET(OPT_KEY_SIZE_ID) ? ARG_UINT32(OPT_KEY_SIZE_ID) / 8 : (uint32_t)crypt_get_volume_key_size(cd);
524 if (ARG_SET(OPT_KEEP_KEY_ID)) {
525 log_dbg("Keeping key from old header.");
526 key_size = crypt_get_volume_key_size(cd);
527 key = crypt_safe_alloc(key_size);
532 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, key, &key_size,
533 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
534 } else if (ARG_SET(OPT_VOLUME_KEY_FILE_ID)) {
535 log_dbg("Loading new key from file.");
536 r = tools_read_vk(ARG_STR(OPT_VOLUME_KEY_FILE_ID), &key, key_size);
542 r = create_new_header(rc, cd,
543 ARG_SET(OPT_CIPHER_ID) ? cipher : crypt_get_cipher(cd),
544 ARG_SET(OPT_CIPHER_ID) ? cipher_mode : crypt_get_cipher_mode(cd),
554 crypt_safe_free(key);
556 log_err(_("Creation of LUKS backup headers failed."));
560 /* Create fake header for original device */
561 static int backup_fake_header(struct reenc_ctx *rc)
563 struct crypt_device *cd_new = NULL;
564 struct crypt_params_luks1 params = {0};
565 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
566 const char *header_file_fake;
569 log_dbg("Creating fake (cipher_null) header for %s device.",
570 (rc->reencrypt_mode == DECRYPT) ? "new" : "original");
572 header_file_fake = (rc->reencrypt_mode == DECRYPT) ? rc->header_file_new : rc->header_file_org;
574 if (!ARG_SET(OPT_KEY_SIZE_ID))
575 ARG_SET_UINT32(OPT_KEY_SIZE_ID, DEFAULT_LUKS1_KEYBITS);
577 if (ARG_SET(OPT_CIPHER_ID)) {
578 r = crypt_parse_name_and_mode(ARG_STR(OPT_CIPHER_ID), cipher, NULL, cipher_mode);
580 log_err(_("No known cipher specification pattern detected."));
585 r = create_empty_header(header_file_fake);
589 params.hash = ARG_STR(OPT_HASH_ID) ?: DEFAULT_LUKS1_HASH;
590 params.data_alignment = 0;
591 params.data_device = rc->device;
593 r = crypt_init(&cd_new, header_file_fake);
597 r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb",
598 NO_UUID, NULL, ARG_UINT32(OPT_KEY_SIZE_ID) / 8, ¶ms);
603 r = crypt_keyslot_add_by_volume_key(cd_new, rc->keyslot, NULL, 0,
604 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
609 /* The real header is backup header created in backup_luks_headers() */
610 if (rc->reencrypt_mode == DECRYPT) {
615 r = create_empty_header(rc->header_file_new);
619 params.data_alignment = ROUND_SECTOR(ARG_UINT64(OPT_REDUCE_DEVICE_SIZE_ID));
620 r = create_new_header(rc, NULL,
621 ARG_SET(OPT_CIPHER_ID) ? cipher : DEFAULT_LUKS1_CIPHER,
622 ARG_SET(OPT_CIPHER_ID) ? cipher_mode : DEFAULT_LUKS1_MODE,
624 ARG_UINT32(OPT_KEY_SIZE_ID) / 8,
633 static void remove_headers(struct reenc_ctx *rc)
635 struct crypt_device *cd = NULL;
637 log_dbg("Removing headers.");
639 if (crypt_init(&cd, NULL))
641 crypt_set_log_callback(cd, _quiet_log, NULL);
642 if (*rc->header_file_org)
643 (void)crypt_deactivate(cd, rc->header_file_org);
644 if (*rc->header_file_new)
645 (void)crypt_deactivate(cd, rc->header_file_new);
649 static int restore_luks_header(struct reenc_ctx *rc)
652 struct crypt_device *cd = NULL;
655 log_dbg("Restoring header for %s from %s.", hdr_device(rc), rc->header_file_new);
658 * For new encryption and new detached header in file just move it.
659 * For existing file try to ensure we have preallocated space for restore.
661 if (ARG_SET(OPT_ENCRYPT_ID) && rc->device_header) {
662 r = stat(rc->device_header, &st);
664 r = rename(rc->header_file_new, rc->device_header);
666 } else if ((st.st_mode & S_IFMT) == S_IFREG &&
667 stat(rc->header_file_new, &st) != -1) {
668 /* coverity[toctou] */
669 fd = open(rc->device_header, O_WRONLY);
671 if (posix_fallocate(fd, 0, st.st_size)) {};
677 r = crypt_init(&cd, hdr_device(rc));
679 r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new);
685 log_err(_("Cannot restore %s header on device %s."), "LUKS1", hdr_device(rc));
687 log_verbose(_("%s header on device %s restored."), "LUKS1", hdr_device(rc));
693 static ssize_t read_buf(int fd, void *buf, size_t count)
695 size_t read_size = 0;
699 /* This expects that partial read is aligned in buffer */
700 s = read(fd, buf, count - read_size);
701 if (s == -1 && errno != EINTR)
704 return (ssize_t)read_size;
706 if (s != (ssize_t)count)
707 log_dbg("Partial read %zd / %zu.", s, count);
708 read_size += (size_t)s;
709 buf = (uint8_t*)buf + s;
711 } while (read_size != count);
713 return (ssize_t)count;
716 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
717 size_t block_size, void *buf, uint64_t *bytes)
721 char *backing_file = NULL;
722 struct tools_progress_params prog_parms = {
723 .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
724 .batch_mode = ARG_SET(OPT_BATCH_MODE_ID),
725 .json_output = ARG_SET(OPT_PROGRESS_JSON_ID),
726 .interrupt_message = _("\nReencryption interrupted."),
727 .device = tools_get_device_name(rc->device, &backing_file)
730 log_dbg("Reencrypting in forward direction.");
732 if (lseek(fd_old, rc->device_offset, SEEK_SET) < 0 ||
733 lseek(fd_new, rc->device_offset, SEEK_SET) < 0) {
734 log_err(_("Cannot seek to device offset."));
738 rc->resume_bytes = *bytes = rc->device_offset;
740 tools_progress(rc->device_size, *bytes, &prog_parms);
742 if (write_log(rc) < 0)
745 while (!quit && rc->device_offset < rc->device_size) {
746 if ((rc->device_size - rc->device_offset) < (uint64_t)block_size)
747 block_size = rc->device_size - rc->device_offset;
748 s1 = read_buf(fd_old, buf, block_size);
749 if (s1 < 0 || ((size_t)s1 != block_size &&
750 (rc->device_offset + s1) != rc->device_size)) {
751 log_dbg("Read error, expecting %zu, got %zd.",
756 /* If device_size is forced, never write more than limit */
757 if ((s1 + rc->device_offset) > rc->device_size)
758 s1 = rc->device_size - rc->device_offset;
760 s2 = write(fd_new, buf, s1);
762 log_dbg("Write error, expecting %zu, got %zd.",
767 rc->device_offset += s1;
768 if (ARG_SET(OPT_WRITE_LOG_ID) && write_log(rc) < 0)
771 if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd_new) < 0) {
772 log_dbg("Write error, fsync.");
776 *bytes += (uint64_t)s2;
778 tools_progress(rc->device_size, *bytes, &prog_parms);
784 return quit ? -EAGAIN : r;
787 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
788 size_t block_size, void *buf, uint64_t *bytes)
790 ssize_t s1, s2, working_block;
791 off_t working_offset;
793 char *backing_file = NULL;
794 struct tools_progress_params prog_parms = {
795 .frequency = ARG_UINT32(OPT_PROGRESS_FREQUENCY_ID),
796 .batch_mode = ARG_SET(OPT_BATCH_MODE_ID),
797 .json_output = ARG_SET(OPT_PROGRESS_JSON_ID),
798 .interrupt_message = _("\nReencryption interrupted."),
799 .device = tools_get_device_name(rc->device, &backing_file)
802 log_dbg("Reencrypting in backward direction.");
804 if (!rc->in_progress) {
805 rc->device_offset = rc->device_size;
806 rc->resume_bytes = 0;
809 rc->resume_bytes = rc->device_size - rc->device_offset;
810 *bytes = rc->resume_bytes;
813 tools_progress(rc->device_size, *bytes, &prog_parms);
815 if (write_log(rc) < 0)
818 /* dirty the device during ENCRYPT mode */
821 while (!quit && rc->device_offset) {
822 if (rc->device_offset < block_size) {
824 working_block = rc->device_offset;
826 working_offset = rc->device_offset - block_size;
827 working_block = block_size;
830 if (lseek(fd_old, working_offset, SEEK_SET) < 0 ||
831 lseek(fd_new, working_offset, SEEK_SET) < 0) {
832 log_err(_("Cannot seek to device offset."));
836 s1 = read_buf(fd_old, buf, working_block);
837 if (s1 < 0 || (s1 != working_block)) {
838 log_dbg("Read error, expecting %zu, got %zd.",
843 s2 = write(fd_new, buf, working_block);
845 log_dbg("Write error, expecting %zu, got %zd.",
850 rc->device_offset -= s1;
851 if (ARG_SET(OPT_WRITE_LOG_ID) && write_log(rc) < 0)
854 if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd_new) < 0) {
855 log_dbg("Write error, fsync.");
859 *bytes += (uint64_t)s2;
861 tools_progress(rc->device_size, *bytes, &prog_parms);
867 return quit ? -EAGAIN : r;
870 static void zero_rest_of_device(int fd, size_t block_size, void *buf,
871 uint64_t *bytes, uint64_t offset)
875 log_dbg("Zeroing rest of device.");
877 if (lseek(fd, offset, SEEK_SET) < 0) {
878 log_dbg("Cannot seek to device offset.");
882 memset(buf, 0, block_size);
885 while (!quit && *bytes) {
886 if (*bytes < (uint64_t)s1)
889 s2 = write(fd, buf, s1);
891 log_dbg("Write error, expecting %zd, got %zd.",
896 if (ARG_SET(OPT_USE_FSYNC_ID) && fsync(fd) < 0) {
897 log_dbg("Write error, fsync.");
905 static int copy_data(struct reenc_ctx *rc)
907 size_t block_size = ARG_UINT32(OPT_BLOCK_SIZE_ID) * 1024 * 1024;
908 int fd_old = -1, fd_new = -1;
913 log_dbg("Data copy preparation.");
915 fd_old = open(rc->crypt_path_org, O_RDONLY | (ARG_SET(OPT_USE_DIRECTIO_ID) ? O_DIRECT : 0));
917 log_err(_("Cannot open temporary LUKS device."));
921 fd_new = open(rc->crypt_path_new, O_WRONLY | (ARG_SET(OPT_USE_DIRECTIO_ID) ? O_DIRECT : 0));
923 log_err(_("Cannot open temporary LUKS device."));
927 if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size_org_real) < 0) {
928 log_err(_("Cannot get device size."));
932 if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_new_real) < 0) {
933 log_err(_("Cannot get device size."));
937 if (ARG_SET(OPT_DEVICE_SIZE_ID))
938 rc->device_size = ARG_UINT64(OPT_DEVICE_SIZE_ID);
939 else if (rc->reencrypt_mode == DECRYPT)
940 rc->device_size = rc->device_size_org_real;
942 rc->device_size = rc->device_size_new_real;
944 if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
945 log_err(_("Allocation of aligned memory failed."));
952 if (rc->reencrypt_direction == FORWARD)
953 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
955 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
957 /* Zero (wipe) rest of now plain-only device when decrypting.
958 * (To not leave any sign of encryption here.) */
959 if (!r && rc->reencrypt_mode == DECRYPT &&
960 rc->device_size_new_real > rc->device_size_org_real) {
961 bytes = rc->device_size_new_real - rc->device_size_org_real;
962 zero_rest_of_device(fd_new, block_size, buf, &bytes, rc->device_size_org_real);
967 if (r < 0 && r != -EAGAIN)
968 log_err(_("IO error during reencryption."));
980 static int initialize_uuid(struct reenc_ctx *rc)
982 struct crypt_device *cd = NULL;
986 log_dbg("Initialising UUID.");
988 if (ARG_SET(OPT_ENCRYPT_ID)) {
989 rc->device_uuid = strdup(NO_UUID);
993 if (ARG_SET(OPT_DECRYPT_ID) && ARG_SET(OPT_UUID_ID)) {
994 r = uuid_parse(ARG_STR(OPT_UUID_ID), device_uuid);
996 rc->device_uuid = strdup(ARG_STR(OPT_UUID_ID));
998 log_err(_("Provided UUID is invalid."));
1003 /* Try to load LUKS from device */
1004 if ((r = crypt_init(&cd, hdr_device(rc))))
1006 crypt_set_log_callback(cd, _quiet_log, NULL);
1007 r = crypt_load(cd, CRYPT_LUKS1, NULL);
1009 rc->device_uuid = strdup(crypt_get_uuid(cd));
1011 /* Reencryption already in progress - magic header? */
1012 r = device_check(rc, hdr_device(rc), CHECK_UNUSABLE, true);
1018 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
1019 const char *msg, int slot_to_check, int check, int verify)
1021 crypt_keyslot_info ki;
1023 int r = -EINVAL, retry_count;
1026 /* mode ENCRYPT call this without header */
1027 if (cd && slot_to_check != CRYPT_ANY_SLOT) {
1028 ki = crypt_keyslot_status(cd, slot_to_check);
1029 if (ki < CRYPT_SLOT_ACTIVE)
1032 ki = CRYPT_SLOT_ACTIVE;
1034 retry_count = ARG_UINT32(OPT_TRIES_ID) ?: 1;
1035 while (retry_count--) {
1036 r = tools_get_key(msg, &password, &passwordLen, 0, 0,
1037 NULL /*opt_key_file*/, 0, verify, 0 /*pwquality*/, cd);
1041 crypt_safe_free(password);
1048 r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
1049 password, passwordLen, CRYPT_ACTIVATE_ALLOW_UNBOUND_KEY);
1051 r = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check;
1054 crypt_safe_free(password);
1058 if (r < 0 && r != -EPERM)
1062 tools_keyslot_msg(r, UNLOCKED);
1063 rc->p[r].password = password;
1064 rc->p[r].passwordLen = passwordLen;
1065 if (ki != CRYPT_SLOT_UNBOUND)
1069 tools_passphrase_msg(r);
1078 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
1084 r = tools_get_key(NULL, &password, &passwordLen, ARG_UINT64(OPT_KEYFILE_OFFSET_ID),
1085 ARG_UINT32(OPT_KEYFILE_SIZE_ID), ARG_STR(OPT_KEY_FILE_ID), 0, 0, 0, cd);
1089 /* mode ENCRYPT call this without header */
1091 r = crypt_activate_by_passphrase(cd, NULL, slot_check, password,
1095 * Allow keyslot only if it is last slot or if user explicitly
1096 * specify which slot to use (IOW others will be disabled).
1098 if (r >= 0 && ARG_INT32(OPT_KEY_SLOT_ID) == CRYPT_ANY_SLOT &&
1099 crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
1100 log_err(_("Key file can be used only with --key-slot or with "
1101 "exactly one key slot active."));
1105 r = slot_check == CRYPT_ANY_SLOT ? 0 : slot_check;
1109 crypt_safe_free(password);
1110 tools_passphrase_msg(r);
1113 rc->p[r].password = password;
1114 rc->p[r].passwordLen = passwordLen;
1123 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
1125 struct crypt_device *cd = NULL;
1129 log_dbg("Passphrases initialization.");
1131 if (rc->reencrypt_mode == ENCRYPT && !rc->in_progress) {
1132 if (ARG_SET(OPT_KEY_FILE_ID))
1133 r = init_keyfile(rc, NULL, ARG_INT32(OPT_KEY_SLOT_ID));
1135 r = init_passphrase1(rc, NULL, _("Enter new passphrase: "), ARG_INT32(OPT_KEY_SLOT_ID), 0, 1);
1136 return r > 0 ? 0 : r;
1139 if ((r = crypt_init_data_device(&cd, device, rc->device)) ||
1140 (r = crypt_load(cd, CRYPT_LUKS1, NULL))) {
1145 if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT)
1146 snprintf(msg, sizeof(msg),
1147 _("Enter passphrase for key slot %d: "), ARG_INT32(OPT_KEY_SLOT_ID));
1149 snprintf(msg, sizeof(msg), _("Enter any existing passphrase: "));
1151 if (ARG_SET(OPT_KEY_FILE_ID)) {
1152 r = init_keyfile(rc, cd, ARG_INT32(OPT_KEY_SLOT_ID));
1153 } else if (rc->in_progress ||
1154 ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT ||
1155 rc->reencrypt_mode == DECRYPT) {
1156 r = init_passphrase1(rc, cd, msg, ARG_INT32(OPT_KEY_SLOT_ID), 1, 0);
1157 } else for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
1158 snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %d: "), i);
1159 r = init_passphrase1(rc, cd, msg, i, 1, 0);
1169 return r > 0 ? 0 : r;
1172 static int initialize_context(struct reenc_ctx *rc, const char *device)
1174 log_dbg("Initialising reencryption context.");
1176 memset(rc, 0, sizeof(*rc));
1178 rc->in_progress = false;
1182 if (!(rc->device = strndup(device, PATH_MAX)))
1185 if (ARG_SET(OPT_HEADER_ID) && !(rc->device_header = strndup(ARG_STR(OPT_HEADER_ID), PATH_MAX)))
1188 if (device_check(rc, rc->device, CHECK_OPEN, true) < 0)
1191 if (initialize_uuid(rc)) {
1192 log_err(_("Device %s is not a valid LUKS device."), device);
1196 if (ARG_INT32(OPT_KEY_SLOT_ID) != CRYPT_ANY_SLOT &&
1197 ARG_INT32(OPT_KEY_SLOT_ID) >= crypt_keyslot_max(CRYPT_LUKS1)) {
1198 log_err(_("Key slot is invalid."));
1202 /* Prepare device names */
1203 if (snprintf(rc->log_file, PATH_MAX,
1204 "LUKS-%s.log", rc->device_uuid) < 0)
1206 if (snprintf(rc->header_file_org, PATH_MAX,
1207 "LUKS-%s.org", rc->device_uuid) < 0)
1209 if (snprintf(rc->header_file_new, PATH_MAX,
1210 "LUKS-%s.new", rc->device_uuid) < 0)
1213 /* Paths to encrypted devices */
1214 if (snprintf(rc->crypt_path_org, PATH_MAX,
1215 "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
1217 if (snprintf(rc->crypt_path_new, PATH_MAX,
1218 "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
1223 if (open_log(rc) < 0) {
1224 log_err(_("Cannot open reencryption log file."));
1228 if (!rc->in_progress) {
1229 if (ARG_SET(OPT_UUID_ID)) {
1230 log_err(_("No decryption in progress, provided UUID can "
1231 "be used only to resume suspended decryption process."));
1235 if (!ARG_SET(OPT_REDUCE_DEVICE_SIZE_ID))
1236 rc->reencrypt_direction = FORWARD;
1238 rc->reencrypt_direction = BACKWARD;
1239 rc->device_offset = (uint64_t)~0;
1242 if (ARG_SET(OPT_ENCRYPT_ID))
1243 rc->reencrypt_mode = ENCRYPT;
1244 else if (ARG_SET(OPT_DECRYPT_ID))
1245 rc->reencrypt_mode = DECRYPT;
1247 rc->reencrypt_mode = REENCRYPT;
1253 static void destroy_context(struct reenc_ctx *rc)
1257 log_dbg("Destroying reencryption context.");
1263 unlink(rc->log_file);
1264 unlink(rc->header_file_org);
1265 unlink(rc->header_file_new);
1268 for (i = 0; i < MAX_SLOT; i++)
1269 crypt_safe_free(rc->p[i].password);
1272 free(rc->device_header);
1273 free(rc->device_uuid);
1276 int reencrypt_luks1(const char *device)
1279 struct reenc_ctx *rc;
1281 rc = malloc(sizeof(*rc));
1285 if (!ARG_SET(OPT_BATCH_MODE_ID))
1286 log_verbose(_("Reencryption will change: %s%s%s%s%s%s."),
1287 ARG_SET(OPT_KEEP_KEY_ID) ? "" : _("volume key"),
1288 (!ARG_SET(OPT_KEEP_KEY_ID) && ARG_SET(OPT_HASH_ID)) ? ", " : "",
1289 ARG_SET(OPT_HASH_ID) ? _("set hash to ") : "", ARG_STR(OPT_HASH_ID) ?: "",
1290 ARG_SET(OPT_CIPHER_ID) ? _(", set cipher to "): "", ARG_STR(OPT_CIPHER_ID) ?: "");
1291 /* FIXME: block all non pbkdf2 pkdfs */
1295 if (initialize_context(rc, device))
1298 log_dbg("Running reencryption.");
1300 if (!rc->in_progress) {
1301 if ((r = initialize_passphrase(rc, hdr_device(rc))))
1304 log_dbg("Storing backup of LUKS headers.");
1305 if (rc->reencrypt_mode == ENCRYPT) {
1306 /* Create fake header for existing device */
1307 if ((r = backup_fake_header(rc)))
1310 if ((r = backup_luks_headers(rc)))
1312 /* Create fake header for decrypted device */
1313 if (rc->reencrypt_mode == DECRYPT &&
1314 (r = backup_fake_header(rc)))
1316 if ((r = device_check(rc, hdr_device(rc), MAKE_UNUSABLE, true)))
1320 if ((r = initialize_passphrase(rc, ARG_SET(OPT_DECRYPT_ID) ? rc->header_file_org : rc->header_file_new)))
1324 if (!ARG_SET(OPT_KEEP_KEY_ID)) {
1325 log_dbg("Running data area reencryption.");
1326 if ((r = activate_luks_headers(rc)))
1329 if ((r = copy_data(rc)))
1332 log_dbg("Keeping existing key, skipping data area reencryption.");
1334 // FIXME: fix error path above to not skip this
1335 if (rc->reencrypt_mode != DECRYPT)
1336 r = restore_luks_header(rc);
1338 rc->stained = false;
1340 destroy_context(rc);
1346 int reencrypt_luks1_in_progress(const char *device)
1350 if (stat(device, &st) || (size_t)st.st_size < pagesize())
1353 return device_check(NULL, device, CHECK_UNUSABLE, false);