2 * cryptsetup-reencrypt - crypt utility for offline re-encryption
4 * Copyright (C) 2012, Milan Broz All rights reserved.
5 * Copyright (C) 2012, Red Hat, Inc. 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 * version 2 as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "cryptsetup.h"
22 #include <sys/ioctl.h>
25 #include <arpa/inet.h>
27 #define PACKAGE_REENC "crypt_reencrypt"
29 #define NO_UUID "cafecafe-cafe-cafe-cafe-cafecafeeeee"
30 #define MAX_BCK_SECTORS 8192
32 static const char *opt_cipher = NULL;
33 static const char *opt_hash = NULL;
34 static const char *opt_key_file = NULL;
35 static long opt_keyfile_size = 0;
36 static long opt_keyfile_offset = 0;
37 static int opt_iteration_time = 1000;
38 static int opt_version_mode = 0;
39 static int opt_random = 0;
40 static int opt_urandom = 0;
41 static int opt_bsize = 4;
42 static int opt_directio = 0;
43 static int opt_fsync = 0;
44 static int opt_write_log = 0;
45 static int opt_tries = 3;
46 static int opt_key_slot = CRYPT_ANY_SLOT;
47 static int opt_key_size = 0;
48 static int opt_new = 0;
50 static const char *opt_reduce_size_str = NULL;
51 static uint64_t opt_reduce_size = 0;
53 static const char *opt_device_size_str = NULL;
54 static uint64_t opt_device_size = 0;
56 static const char **action_argv;
62 uint64_t device_size; /* overrided by parameter */
63 uint64_t device_size_real;
64 uint64_t device_offset;
65 uint64_t device_shift;
68 enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
70 char header_file_org[PATH_MAX];
71 char header_file_new[PATH_MAX];
72 char log_file[PATH_MAX];
74 char crypt_path_org[PATH_MAX];
75 char crypt_path_new[PATH_MAX];
85 struct timeval start_time, end_time;
86 uint64_t resume_bytes;
89 char MAGIC[] = {'L','U','K','S', 0xba, 0xbe};
90 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
100 static void _quiet_log(int level, const char *msg, void *usrptr)
104 tool_log(level, msg, usrptr);
107 /* The difference in seconds between two times in "timeval" format. */
108 static double time_diff(struct timeval start, struct timeval end)
110 return (end.tv_sec - start.tv_sec)
111 + (end.tv_usec - start.tv_usec) / 1E6;
114 static int alignment(int fd)
118 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
124 /* Depends on the first two fields of LUKS1 header format, magic and version */
125 static int device_check(struct reenc_ctx *rc, header_magic set_magic)
132 devfd = open(rc->device, O_RDWR | O_EXCL | O_DIRECT);
134 if (errno == EBUSY) {
135 log_err(_("Cannot exclusively open %s, device in use.\n"),
139 log_err(_("Cannot open device %s\n"), rc->device);
143 if (set_magic == CHECK_OPEN) {
148 if (posix_memalign((void *)&buf, alignment(devfd), SECTOR_SIZE)) {
149 log_err(_("Allocation of aligned memory failed.\n"));
154 s = read(devfd, buf, SECTOR_SIZE);
155 if (s < 0 || s != SECTOR_SIZE) {
156 log_err(_("Cannot read device %s.\n"), rc->device);
161 /* Be sure that we do not process new version of header */
162 memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
163 version = ntohs(version);
165 if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
167 log_verbose(_("Marking LUKS device %s unusable.\n"), rc->device);
168 memcpy(buf, NOMAGIC, MAGIC_L);
170 } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L) &&
172 log_verbose(_("Marking LUKS device %s usable.\n"), rc->device);
173 memcpy(buf, MAGIC, MAGIC_L);
175 } else if (set_magic == CHECK_UNUSABLE && version == 1) {
176 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
178 rc->device_uuid = strndup(&buf[0xa8], 40);
184 if (lseek(devfd, 0, SEEK_SET) == -1)
186 s = write(devfd, buf, SECTOR_SIZE);
187 if (s < 0 || s != SECTOR_SIZE) {
188 log_err(_("Cannot write device %s.\n"), rc->device);
192 log_dbg("LUKS signature check failed for %s.", rc->device);
195 memset(buf, 0, SECTOR_SIZE);
201 static int create_empty_header(const char *new_file, const char *old_file,
202 uint64_t data_sector)
209 /* Never create header > 4MiB */
210 if (data_sector > MAX_BCK_SECTORS)
211 data_sector = MAX_BCK_SECTORS;
213 /* new header file of the same size as old backup */
215 if (stat(old_file, &st) == -1 ||
216 (st.st_mode & S_IFMT) != S_IFREG ||
217 (st.st_size > 16 * 1024 * 1024))
223 * if requesting key size change, try to use offset
224 * here can be enough space to fit new key.
227 size = data_sector * SECTOR_SIZE;
229 /* if reducing size, be sure we have enough space */
231 size += opt_reduce_size;
233 log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
235 if (!size || !(buf = malloc(size)))
237 memset(buf, 0, size);
239 fd = creat(new_file, S_IRUSR|S_IWUSR);
245 if (write(fd, buf, size) < size)
253 static int write_log(struct reenc_ctx *rc)
257 memset(rc->log_buf, 0, SECTOR_SIZE);
258 snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
259 "version = %d\nUUID = %s\ndirection = %d\n"
260 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
261 1, rc->device_uuid, rc->reencrypt_direction,
262 rc->device_offset, rc->device_shift);
264 if (lseek(rc->log_fd, 0, SEEK_SET) == -1)
267 r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
268 if (r < 0 || r != SECTOR_SIZE) {
269 log_err(_("Cannot write reencryption log file.\n"));
276 static int parse_line_log(struct reenc_ctx *rc, const char *line)
282 /* whole line is comment */
286 if (sscanf(line, "version = %d", &i) == 1) {
288 log_dbg("Log: Unexpected version = %i", i);
291 } else if (sscanf(line, "UUID = %40s", s) == 1) {
292 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
293 log_dbg("Log: Unexpected UUID %s", s);
296 } else if (sscanf(line, "direction = %d", &i) == 1) {
297 log_dbg("Log: direction = %i", i);
298 rc->reencrypt_direction = i;
299 } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
300 log_dbg("Log: offset = %" PRIu64, u64);
301 rc->device_offset = u64;
302 } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
303 log_dbg("Log: shift = %" PRIu64, u64);
304 rc->device_shift = u64;
311 static int parse_log(struct reenc_ctx *rc)
316 s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
318 log_err(_("Cannot read reencryption log file.\n"));
322 rc->log_buf[SECTOR_SIZE - 1] = '\0';
325 end = strchr(start, '\n');
328 if (parse_line_log(rc, start)) {
329 log_err("Wrong log format.\n");
340 static void close_log(struct reenc_ctx *rc)
342 log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
343 if (rc->log_fd != -1)
349 static int open_log(struct reenc_ctx *rc)
351 int flags, create_new;
354 if (!stat(rc->log_file, &st))
356 else if (errno == ENOENT)
362 log_dbg("Creating LUKS reencryption log file %s.", rc->log_file);
363 flags = opt_directio ? O_RDWR|O_CREAT|O_DIRECT : O_RDWR|O_CREAT;
364 rc->log_fd = open(rc->log_file, flags, S_IRUSR|S_IWUSR);
365 if (rc->log_fd == -1)
368 log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file);
369 flags = opt_directio ? O_RDWR|O_DIRECT : O_RDWR;
370 rc->log_fd = open(rc->log_file, flags);
371 if (rc->log_fd == -1)
376 if (posix_memalign((void *)&rc->log_buf, alignment(rc->log_fd), SECTOR_SIZE)) {
377 log_err(_("Allocation of aligned memory failed.\n"));
382 if (create_new && write_log(rc) < 0) {
387 /* Be sure it is correct format */
388 return parse_log(rc);
391 static int activate_luks_headers(struct reenc_ctx *rc)
393 struct crypt_device *cd = NULL, *cd_new = NULL;
396 log_dbg("Activating LUKS devices from headers.");
398 if ((r = crypt_init(&cd, rc->header_file_org)) ||
399 (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
400 (r = crypt_set_data_device(cd, rc->device)))
403 if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
404 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
405 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
408 if ((r = crypt_init(&cd_new, rc->header_file_new)) ||
409 (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)) ||
410 (r = crypt_set_data_device(cd_new, rc->device)))
413 if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
414 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
415 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
422 log_err(_("Activation of temporary devices failed.\n"));
426 static int create_new_header(struct reenc_ctx *rc, const char *cipher,
427 const char *cipher_mode, const char *uuid,
428 int key_size, struct crypt_params_luks1 *params)
430 struct crypt_device *cd_new = NULL;
433 if ((r = crypt_init(&cd_new, rc->header_file_new)))
437 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
438 else if (opt_urandom)
439 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
441 if (opt_iteration_time)
442 crypt_set_iteration_time(cd_new, opt_iteration_time);
444 if ((r = crypt_format(cd_new, CRYPT_LUKS1, cipher, cipher_mode,
445 uuid, NULL, key_size, params)))
447 log_verbose(_("New LUKS header for device %s created.\n"), rc->device);
449 for (i = 0; i < MAX_SLOT; i++) {
450 if (!rc->p[i].password)
452 if ((r = crypt_keyslot_add_by_volume_key(cd_new, i,
453 NULL, 0, rc->p[i].password, rc->p[i].passwordLen)) < 0)
455 log_verbose(_("Activated keyslot %i.\n"), r);
463 static int backup_luks_headers(struct reenc_ctx *rc)
465 struct crypt_device *cd = NULL;
466 struct crypt_params_luks1 params = {0};
467 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
470 log_dbg("Creating LUKS header backup for device %s.", rc->device);
472 if ((r = crypt_init(&cd, rc->device)) ||
473 (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
476 crypt_set_confirm_callback(cd, NULL, NULL);
477 if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org)))
479 log_verbose(_("LUKS header backup of device %s created.\n"), rc->device);
481 if ((r = create_empty_header(rc->header_file_new, rc->header_file_org,
482 crypt_get_data_offset(cd))))
485 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
486 params.data_alignment = crypt_get_data_offset(cd);
487 params.data_alignment += ROUND_SECTOR(opt_reduce_size);
488 params.data_device = rc->device;
491 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
493 log_err(_("No known cipher specification pattern detected.\n"));
498 r = create_new_header(rc,
499 opt_cipher ? cipher : crypt_get_cipher(cd),
500 opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
502 opt_key_size ? opt_key_size / 8 : crypt_get_volume_key_size(cd),
507 log_err(_("Creation of LUKS backup headers failed.\n"));
511 /* Create fake header for original device */
512 static int backup_fake_header(struct reenc_ctx *rc)
514 struct crypt_device *cd_new = NULL;
515 struct crypt_params_luks1 params = {0};
516 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
520 log_dbg("Creating fake (cipher_null) header for original device.");
523 opt_key_size = DEFAULT_LUKS1_KEYBITS;
526 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
528 log_err(_("No known cipher specification pattern detected.\n"));
533 r = create_empty_header(rc->header_file_org, NULL, 0);
537 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
538 params.data_alignment = 0;
539 params.data_device = rc->device;
541 r = crypt_init(&cd_new, rc->header_file_org);
545 r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb",
546 NO_UUID, NULL, opt_key_size / 8, ¶ms);
550 r = crypt_keyslot_add_by_volume_key(cd_new, 0, NULL, 0,
551 rc->p[0].password, rc->p[0].passwordLen);
555 r = create_empty_header(rc->header_file_new, rc->header_file_org, 0);
559 params.data_alignment = ROUND_SECTOR(opt_reduce_size);
560 r = create_new_header(rc,
561 opt_cipher ? cipher : DEFAULT_LUKS1_CIPHER,
562 opt_cipher ? cipher_mode : DEFAULT_LUKS1_MODE,
564 (opt_key_size ? opt_key_size : DEFAULT_LUKS1_KEYBITS) / 8,
571 static void remove_headers(struct reenc_ctx *rc)
573 struct crypt_device *cd = NULL;
575 log_dbg("Removing headers.");
577 if (crypt_init(&cd, NULL))
579 crypt_set_log_callback(cd, _quiet_log, NULL);
580 if (*rc->header_file_org)
581 (void)crypt_deactivate(cd, rc->header_file_org);
582 if (*rc->header_file_new)
583 (void)crypt_deactivate(cd, rc->header_file_new);
587 static int restore_luks_header(struct reenc_ctx *rc)
589 struct crypt_device *cd = NULL;
592 log_dbg("Restoring header for %s from %s.", rc->device, rc->header_file_new);
594 r = crypt_init(&cd, rc->device);
596 crypt_set_confirm_callback(cd, NULL, NULL);
597 r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new);
602 log_err(_("Cannot restore LUKS header on device %s.\n"), rc->device);
604 log_verbose(_("LUKS header on device %s restored.\n"), rc->device);
608 static void print_progress(struct reenc_ctx *rc, uint64_t bytes, int final)
610 unsigned long long mbytes, eta;
611 struct timeval now_time;
614 gettimeofday(&now_time, NULL);
615 if (!final && time_diff(rc->end_time, now_time) < 0.5)
618 rc->end_time = now_time;
623 tdiff = time_diff(rc->start_time, rc->end_time);
627 mbytes = (bytes - rc->resume_bytes) / 1024 / 1024;
628 mib = (double)(mbytes) / tdiff;
632 eta = (unsigned long long)(rc->device_size / 1024 / 1024 / mib - tdiff);
634 /* vt100 code clear line */
636 log_err(_("Progress: %5.1f%%, ETA %02llu:%02llu, "
637 "%4llu MiB written, speed %5.1f MiB/s%s"),
638 (double)bytes / rc->device_size * 100,
639 eta / 60, eta % 60, mbytes, mib,
643 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
644 size_t block_size, void *buf, uint64_t *bytes)
648 log_dbg("Reencrypting in forward direction.");
650 if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
651 lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
652 log_err(_("Cannot seek to device offset.\n"));
656 rc->resume_bytes = *bytes = rc->device_offset;
658 if (write_log(rc) < 0)
661 while (!quit && rc->device_offset < rc->device_size) {
662 s1 = read(fd_old, buf, block_size);
663 if (s1 < 0 || ((size_t)s1 != block_size &&
664 (rc->device_offset + s1) != rc->device_size)) {
665 log_dbg("Read error, expecting %d, got %d.",
666 (int)block_size, (int)s1);
670 /* If device_size is forced, never write more than limit */
671 if ((s1 + rc->device_offset) > rc->device_size)
672 s1 = rc->device_size - rc->device_offset;
674 s2 = write(fd_new, buf, s1);
676 log_dbg("Write error, expecting %d, got %d.",
677 (int)block_size, (int)s2);
681 rc->device_offset += s1;
682 if (opt_write_log && write_log(rc) < 0)
685 if (opt_fsync && fsync(fd_new) < 0) {
686 log_dbg("Write error, fsync.");
690 *bytes += (uint64_t)s2;
691 print_progress(rc, *bytes, 0);
694 return quit ? -EAGAIN : 0;
697 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
698 size_t block_size, void *buf, uint64_t *bytes)
700 ssize_t s1, s2, working_block;
701 off64_t working_offset;
703 log_dbg("Reencrypting in backward direction.");
705 if (!rc->in_progress) {
706 rc->device_offset = rc->device_size;
707 rc->resume_bytes = 0;
710 rc->resume_bytes = rc->device_size - rc->device_offset;
711 *bytes = rc->resume_bytes;
714 if (write_log(rc) < 0)
717 while (!quit && rc->device_offset) {
718 if (rc->device_offset < block_size) {
720 working_block = rc->device_offset;
722 working_offset = rc->device_offset - block_size;
723 working_block = block_size;
726 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
727 lseek64(fd_new, working_offset, SEEK_SET) < 0) {
728 log_err(_("Cannot seek to device offset.\n"));
732 s1 = read(fd_old, buf, working_block);
733 if (s1 < 0 || (s1 != working_block)) {
734 log_dbg("Read error, expecting %d, got %d.",
735 (int)block_size, (int)s1);
739 s2 = write(fd_new, buf, working_block);
741 log_dbg("Write error, expecting %d, got %d.",
742 (int)block_size, (int)s2);
746 rc->device_offset -= s1;
747 if (opt_write_log && write_log(rc) < 0)
750 if (opt_fsync && fsync(fd_new) < 0) {
751 log_dbg("Write error, fsync.");
755 *bytes += (uint64_t)s2;
756 print_progress(rc, *bytes, 0);
759 return quit ? -EAGAIN : 0;
762 static int copy_data(struct reenc_ctx *rc)
764 size_t block_size = opt_bsize * 1024 * 1024;
765 int fd_old = -1, fd_new = -1;
770 log_dbg("Data copy preparation.");
772 fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
774 log_err(_("Cannot open temporary LUKS header file.\n"));
778 fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
780 log_err(_("Cannot open temporary LUKS header file.\n"));
785 if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_real) < 0) {
786 log_err(_("Cannot get device size.\n"));
790 rc->device_size = opt_device_size ?: rc->device_size_real;
792 if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
793 log_err(_("Allocation of aligned memory failed.\n"));
799 gettimeofday(&rc->start_time, NULL);
801 if (rc->reencrypt_direction == FORWARD)
802 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
804 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
807 print_progress(rc, bytes, 1);
810 log_err(_("Interrupted by a signal.\n"));
812 log_err(_("IO error during reencryption.\n"));
824 static int initialize_uuid(struct reenc_ctx *rc)
826 struct crypt_device *cd = NULL;
829 log_dbg("Initialising UUID.");
832 rc->device_uuid = strdup(NO_UUID);
836 /* Try to load LUKS from device */
837 if ((r = crypt_init(&cd, rc->device)))
839 crypt_set_log_callback(cd, _quiet_log, NULL);
840 r = crypt_load(cd, CRYPT_LUKS1, NULL);
842 rc->device_uuid = strdup(crypt_get_uuid(cd));
844 /* Reencryption already in progress - magic header? */
845 r = device_check(rc, CHECK_UNUSABLE);
851 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
852 const char *msg, int slot_to_check, int check)
854 int r = -EINVAL, slot, retry_count;
856 slot = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check;
858 retry_count = opt_tries ?: 1;
859 while (retry_count--) {
861 r = crypt_get_key(msg, &rc->p[slot].password,
862 &rc->p[slot].passwordLen,
863 0, 0, NULL /*opt_key_file*/,
870 /* library uses sigint internally, until it is fixed...*/
873 r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
874 rc->p[slot].password, rc->p[slot].passwordLen, 0);
879 crypt_safe_free(rc->p[slot].password);
880 rc->p[slot].password = NULL;
881 rc->p[slot].passwordLen = 0;
883 if (r < 0 && r != -EPERM)
889 log_err(_("No key available with this passphrase.\n"));
894 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
898 slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
899 r = crypt_get_key(NULL, &rc->p[slot].password, &rc->p[slot].passwordLen,
900 opt_keyfile_offset, opt_keyfile_size, opt_key_file, 0, 0, cd);
904 r = crypt_activate_by_passphrase(cd, NULL, slot_check,
905 rc->p[slot].password, rc->p[slot].passwordLen, 0);
908 * Allow keyslot only if it is last slot or if user explicitly
909 * specify whch slot to use (IOW others will be disabled).
911 if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
912 crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
913 log_err(_("Key file can be used only with --key-slot or with "
914 "exactly one key slot active.\n"));
919 crypt_safe_free(rc->p[slot].password);
920 rc->p[slot].password = NULL;
921 rc->p[slot].passwordLen = 0;
923 log_err(_("No key available with this passphrase.\n"));
931 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
933 struct crypt_device *cd = NULL;
934 crypt_keyslot_info ki;
938 log_dbg("Passhrases initialization.");
940 if (opt_new && !rc->in_progress) {
941 r = init_passphrase1(rc, cd, _("Enter new LUKS passphrase: "), 0, 0);
942 return r > 0 ? 0 : r;
945 if ((r = crypt_init(&cd, device)) ||
946 (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
947 (r = crypt_set_data_device(cd, rc->device))) {
953 r = init_keyfile(rc, cd, opt_key_slot);
954 } else if (rc->in_progress) {
955 r = init_passphrase1(rc, cd, _("Enter any LUKS passphrase: "),
957 } else for (i = 0; i < MAX_SLOT; i++) {
958 ki = crypt_keyslot_status(cd, i);
959 if (ki != CRYPT_SLOT_ACTIVE && ki != CRYPT_SLOT_ACTIVE_LAST)
962 snprintf(msg, sizeof(msg), _("Enter LUKS passphrase for key slot %u: "), i);
963 r = init_passphrase1(rc, cd, msg, i, 1);
969 return r > 0 ? 0 : r;
972 static int initialize_context(struct reenc_ctx *rc, const char *device)
974 log_dbg("Initialising reencryption context.");
978 if (!(rc->device = strndup(device, PATH_MAX)))
981 if (device_check(rc, CHECK_OPEN) < 0)
984 if (initialize_uuid(rc)) {
985 log_err(_("Device %s is not a valid LUKS device.\n"), device);
989 /* Prepare device names */
990 if (snprintf(rc->log_file, PATH_MAX,
991 "LUKS-%s.log", rc->device_uuid) < 0)
993 if (snprintf(rc->header_file_org, PATH_MAX,
994 "LUKS-%s.org", rc->device_uuid) < 0)
996 if (snprintf(rc->header_file_new, PATH_MAX,
997 "LUKS-%s.new", rc->device_uuid) < 0)
1000 /* Paths to encrypted devices */
1001 if (snprintf(rc->crypt_path_org, PATH_MAX,
1002 "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
1004 if (snprintf(rc->crypt_path_new, PATH_MAX,
1005 "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
1010 if (open_log(rc) < 0) {
1011 log_err(_("Cannot open reencryption log file.\n"));
1015 if (!rc->in_progress) {
1016 if (!opt_reduce_size)
1017 rc->reencrypt_direction = FORWARD;
1019 rc->reencrypt_direction = BACKWARD;
1020 rc->device_offset = (uint64_t)~0;
1027 static void destroy_context(struct reenc_ctx *rc)
1031 log_dbg("Destroying reencryption context.");
1036 if ((rc->reencrypt_direction == FORWARD &&
1037 rc->device_offset == rc->device_size) ||
1038 (rc->reencrypt_direction == BACKWARD &&
1039 (rc->device_offset == 0 || rc->device_offset == (uint64_t)~0))) {
1040 unlink(rc->log_file);
1041 unlink(rc->header_file_org);
1042 unlink(rc->header_file_new);
1045 for (i = 0; i < MAX_SLOT; i++)
1046 crypt_safe_free(rc->p[i].password);
1049 free(rc->device_uuid);
1052 static int run_reencrypt(const char *device)
1055 struct reenc_ctx rc = {};
1057 if (initialize_context(&rc, device))
1060 log_dbg("Running reencryption.");
1062 if (!rc.in_progress) {
1064 if ((r = initialize_passphrase(&rc, rc.device)) ||
1065 (r = backup_fake_header(&rc)))
1067 } else if ((r = initialize_passphrase(&rc, rc.device)) ||
1068 (r = backup_luks_headers(&rc)) ||
1069 (r = device_check(&rc, MAKE_UNUSABLE)))
1072 if ((r = initialize_passphrase(&rc, rc.header_file_new)))
1076 if ((r = activate_luks_headers(&rc)))
1079 if ((r = copy_data(&rc)))
1082 r = restore_luks_header(&rc);
1084 destroy_context(&rc);
1088 static void help(poptContext popt_context,
1089 enum poptCallbackReason reason __attribute__((unused)),
1090 struct poptOption *key,
1091 const char *arg __attribute__((unused)),
1092 void *data __attribute__((unused)))
1094 if (key->shortName == '?') {
1095 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1096 poptPrintHelp(popt_context, stdout, 0);
1099 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1102 int main(int argc, const char **argv)
1104 static struct poptOption popt_help_options[] = {
1105 { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL },
1106 { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL },
1107 { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL },
1110 static struct poptOption popt_options[] = {
1111 { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1112 { "version", '\0', POPT_ARG_NONE, &opt_version_mode, 0, N_("Print package version"), NULL },
1113 { "verbose", 'v', POPT_ARG_NONE, &opt_verbose, 0, N_("Shows more detailed error messages"), NULL },
1114 { "debug", '\0', POPT_ARG_NONE, &opt_debug, 0, N_("Show debug messages"), NULL },
1115 { "block-size", 'B', POPT_ARG_INT, &opt_bsize, 0, N_("Reencryption block size"), N_("MiB") },
1116 { "cipher", 'c', POPT_ARG_STRING, &opt_cipher, 0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1117 { "key-size", 's', POPT_ARG_INT, &opt_key_size, 0, N_("The size of the encryption key"), N_("BITS") },
1118 { "hash", 'h', POPT_ARG_STRING, &opt_hash, 0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1119 { "key-file", 'd', POPT_ARG_STRING, &opt_key_file, 0, N_("Read the key from a file."), NULL },
1120 { "iter-time", 'i', POPT_ARG_INT, &opt_iteration_time, 0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1121 { "batch-mode", 'q', POPT_ARG_NONE, &opt_batch_mode, 0, N_("Do not ask for confirmation"), NULL },
1122 { "tries", 'T', POPT_ARG_INT, &opt_tries, 0, N_("How often the input of the passphrase can be retried"), NULL },
1123 { "use-random", '\0', POPT_ARG_NONE, &opt_random, 0, N_("Use /dev/random for generating volume key."), NULL },
1124 { "use-urandom", '\0', POPT_ARG_NONE, &opt_urandom, 0, N_("Use /dev/urandom for generating volume key."), NULL },
1125 { "use-directio", '\0', POPT_ARG_NONE, &opt_directio, 0, N_("Use direct-io when accesing devices."), NULL },
1126 { "use-fsync", '\0', POPT_ARG_NONE, &opt_fsync, 0, N_("Use fsync after each block."), NULL },
1127 { "write-log", '\0', POPT_ARG_NONE, &opt_write_log, 0, N_("Update log file after every block."), NULL },
1128 { "key-slot", 'S', POPT_ARG_INT, &opt_key_slot, 0, N_("Use only this slot (others will be disabled)."), NULL },
1129 { "keyfile-offset", '\0', POPT_ARG_LONG, &opt_keyfile_offset, 0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1130 { "keyfile-size", 'l', POPT_ARG_LONG, &opt_keyfile_size, 0, N_("Limits the read from keyfile"), N_("bytes") },
1131 { "reduce-device-size",'\0', POPT_ARG_STRING, &opt_reduce_size_str, 0, N_("Reduce data device size (move data offset). DANGEROUS!"), N_("bytes") },
1132 { "device-size", '\0', POPT_ARG_STRING, &opt_device_size_str, 0, N_("Use only specified device size (ignore rest of device). DANGEROUS!"), N_("bytes") },
1133 { "new", 'N', POPT_ARG_NONE,&opt_new, 0, N_("Create new header on not encrypted device."), NULL },
1136 poptContext popt_context;
1139 crypt_set_log_callback(NULL, tool_log, NULL);
1143 setlocale(LC_ALL, "");
1144 bindtextdomain(PACKAGE, LOCALEDIR);
1145 textdomain(PACKAGE);
1147 popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1148 poptSetOtherOptionHelp(popt_context,
1149 _("[OPTION...] <device>"));
1151 while((r = poptGetNextOpt(popt_context)) > 0) ;
1153 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1154 poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1156 if (opt_version_mode) {
1157 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1158 poptFreeContext(popt_context);
1162 if (!opt_batch_mode) {
1163 log_std(_("WARNING: this is experimental code, it can completely break your data.\n"));
1164 log_verbose(_("Reencryption will change: volume key%s%s%s%s.\n"),
1165 opt_hash ? _(", set hash to ") : "", opt_hash ?: "",
1166 opt_cipher ? _(", set cipher to "): "", opt_cipher ?: "");
1169 action_argv = poptGetArgs(popt_context);
1171 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1172 poptGetInvocationName(popt_context));
1174 if (opt_random && opt_urandom)
1175 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1176 poptGetInvocationName(popt_context));
1178 if (opt_bsize < 0 || opt_key_size < 0 || opt_iteration_time < 0 ||
1179 opt_tries < 0 || opt_keyfile_offset < 0 || opt_key_size < 0) {
1180 usage(popt_context, EXIT_FAILURE,
1181 _("Negative number for option not permitted."),
1182 poptGetInvocationName(popt_context));
1185 if (opt_bsize < 1 || opt_bsize > 64)
1186 usage(popt_context, EXIT_FAILURE,
1187 _("Only values between 1 MiB and 64 MiB allowed for reencryption block size."),
1188 poptGetInvocationName(popt_context));
1190 if (opt_key_size % 8)
1191 usage(popt_context, EXIT_FAILURE,
1192 _("Key size must be a multiple of 8 bits"),
1193 poptGetInvocationName(popt_context));
1195 if (opt_key_slot != CRYPT_ANY_SLOT &&
1196 (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS1)))
1197 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1198 poptGetInvocationName(popt_context));
1200 if (opt_random && opt_urandom)
1201 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1202 poptGetInvocationName(popt_context));
1204 if (opt_device_size_str &&
1205 crypt_string_to_size(NULL, opt_device_size_str, &opt_device_size))
1206 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1207 poptGetInvocationName(popt_context));
1209 if (opt_reduce_size_str &&
1210 crypt_string_to_size(NULL, opt_reduce_size_str, &opt_reduce_size))
1211 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1212 poptGetInvocationName(popt_context));
1213 if (opt_reduce_size > 64 * 1024 * 1024)
1214 usage(popt_context, EXIT_FAILURE, _("Maximum device reduce size is 64 MiB."),
1215 poptGetInvocationName(popt_context));
1216 if (opt_reduce_size % SECTOR_SIZE)
1217 usage(popt_context, EXIT_FAILURE, _("Reduce size must be multiple of 512 bytes sector."),
1218 poptGetInvocationName(popt_context));
1220 if (opt_new && !opt_reduce_size)
1221 usage(popt_context, EXIT_FAILURE, _("Option --new must be used together with --reduce-device-size."),
1222 poptGetInvocationName(popt_context));
1226 crypt_set_debug_level(-1);
1227 dbg_version_and_cmd(argc, argv);
1230 r = run_reencrypt(action_argv[0]);
1232 poptFreeContext(popt_context);
1234 return translate_errno(r);