2 * crypt_reencrypt - crypt utility for offline reencryption
4 * Copyright (C) 2012 Milan Broz All rights reserved.
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * version 2 as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #define PACKAGE_REENC "crypt_reencrypt"
22 #define _LARGEFILE64_SOURCE
23 #define _FILE_OFFSET_BITS 64
24 #define SECTOR_SIZE 512
35 #include <sys/ioctl.h>
38 #include <arpa/inet.h>
43 #include "cryptsetup.h"
45 static int opt_verbose = 0;
46 static int opt_debug = 0;
47 static const char *opt_cipher = NULL;
48 static const char *opt_hash = NULL;
49 static const char *opt_key_file = NULL;
50 static long opt_keyfile_size = 0;
51 static long opt_keyfile_offset = 0;
52 static int opt_iteration_time = 1000;
53 static int opt_batch_mode = 0;
54 static int opt_version_mode = 0;
55 static int opt_random = 0;
56 static int opt_urandom = 0;
57 static int opt_bsize = 4;
58 static int opt_reduce_device_size = 0;
59 static int opt_directio = 0;
60 static int opt_fsync = 0;
61 static int opt_write_log = 0;
62 static int opt_tries = 3;
63 static int opt_key_slot = CRYPT_ANY_SLOT;
64 static int opt_key_size = 0;
66 static const char **action_argv;
68 static volatile int quit = 0;
75 uint64_t device_offset;
76 uint64_t device_shift;
79 enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
81 char header_file_org[PATH_MAX];
82 char header_file_new[PATH_MAX];
83 char log_file[PATH_MAX];
85 char crypt_path_org[PATH_MAX];
86 char crypt_path_new[PATH_MAX];
96 struct timeval start_time, end_time;
97 uint64_t restart_bytes;
100 char MAGIC[] = {'L','U','K','S', 0xba, 0xbe};
101 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
111 __attribute__((format(printf, 5, 6)))
112 static void clogger(struct crypt_device *cd, int level, const char *file,
113 int line, const char *format, ...)
118 va_start(argp, format);
120 if (vasprintf(&target, format, argp) > 0) {
122 crypt_log(cd, level, target);
123 } else if (opt_debug)
124 printf("# %s\n", target);
131 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
135 case CRYPT_LOG_NORMAL:
138 case CRYPT_LOG_VERBOSE:
142 case CRYPT_LOG_ERROR:
145 case CRYPT_LOG_DEBUG:
147 printf("# %s\n", msg);
150 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
155 static void _quiet_log(int level, const char *msg, void *usrptr)
159 _log(level, msg, usrptr);
162 static void int_handler(int sig __attribute__((__unused__)))
167 static void set_int_block(int block)
169 sigset_t signals_open;
171 sigemptyset(&signals_open);
172 sigaddset(&signals_open, SIGINT);
173 sigaddset(&signals_open, SIGTERM);
174 sigprocmask(block ? SIG_SETMASK : SIG_UNBLOCK, &signals_open, NULL);
177 static void set_int_handler(void)
179 struct sigaction sigaction_open;
181 memset(&sigaction_open, 0, sizeof(struct sigaction));
182 sigaction_open.sa_handler = int_handler;
183 sigaction(SIGINT, &sigaction_open, 0);
184 sigaction(SIGTERM, &sigaction_open, 0);
188 /* The difference in seconds between two times in "timeval" format. */
189 static double time_diff(struct timeval start, struct timeval end)
191 return (end.tv_sec - start.tv_sec)
192 + (end.tv_usec - start.tv_usec) / 1E6;
195 static int alignment(int fd)
199 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
205 /* Depends on the first two fields of LUKS1 header format, magic and version */
206 static int device_check(struct reenc_ctx *rc, header_magic set_magic)
213 devfd = open(rc->device, O_RDWR | O_EXCL | O_DIRECT);
215 if (errno == EBUSY) {
216 log_err(_("Cannot exclusively open %s, device in use.\n"),
220 log_err(_("Cannot open device %s\n"), rc->device);
224 if (set_magic == CHECK_OPEN) {
229 if (posix_memalign((void *)&buf, alignment(devfd), SECTOR_SIZE)) {
230 log_err(_("Allocation of aligned memory failed.\n"));
235 s = read(devfd, buf, SECTOR_SIZE);
236 if (s < 0 || s != SECTOR_SIZE) {
237 log_err(_("Cannot read device %s.\n"), rc->device);
242 /* Be sure that we do not process new version of header */
243 memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
244 version = ntohs(version);
246 if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
248 log_verbose(_("Marking LUKS device %s unusable.\n"), rc->device);
249 memcpy(buf, NOMAGIC, MAGIC_L);
251 } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L) &&
253 log_verbose(_("Marking LUKS device %s usable.\n"), rc->device);
254 memcpy(buf, MAGIC, MAGIC_L);
256 } else if (set_magic == CHECK_UNUSABLE && version == 1) {
257 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
259 rc->device_uuid = strndup(&buf[0xa8], 40);
265 if (lseek(devfd, 0, SEEK_SET) == -1)
267 s = write(devfd, buf, SECTOR_SIZE);
268 if (s < 0 || s != SECTOR_SIZE) {
269 log_err(_("Cannot write device %s.\n"), rc->device);
273 log_dbg("LUKS signature check failed for %s.", rc->device);
276 memset(buf, 0, SECTOR_SIZE);
282 static int create_empty_header(const char *new_file, const char *old_file,
283 uint64_t data_sector)
290 /* Never create header > 4MiB */
291 if (data_sector > 8192)
294 /* new header file of the same size as old backup */
295 if (stat(old_file, &st) == -1 ||
296 (st.st_mode & S_IFMT) != S_IFREG ||
297 (st.st_size > 16 * 1024 * 1024))
302 * if requesting key size change, try to use offset
303 * here can be enough space to fit new key.
306 size = data_sector * SECTOR_SIZE;
308 /* if reducing size, be sure we have enough space */
309 if (opt_reduce_device_size)
310 size += (opt_reduce_device_size * SECTOR_SIZE);
312 log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
314 if (!(buf = malloc(size)))
316 memset(buf, 0, size);
318 fd = creat(new_file, S_IRUSR|S_IWUSR);
324 if (write(fd, buf, size) < size)
332 static int write_log(struct reenc_ctx *rc)
336 memset(rc->log_buf, 0, SECTOR_SIZE);
337 snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
338 "version = %d\nUUID = %s\ndirection = %d\n"
339 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
340 1, rc->device_uuid, rc->reencrypt_direction,
341 rc->device_offset, rc->device_shift);
343 lseek(rc->log_fd, 0, SEEK_SET);
344 r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
345 if (r < 0 || r != SECTOR_SIZE) {
346 log_err(_("Cannot write reencryption log file.\n"));
353 static int parse_line_log(struct reenc_ctx *rc, const char *line)
359 /* whole line is comment */
363 if (sscanf(line, "version = %d", &i) == 1) {
365 log_dbg("Log: Unexpected version = %i", i);
368 } else if (sscanf(line, "UUID = %40s", s) == 1) {
369 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
370 log_dbg("Log: Unexpected UUID %s", s);
373 } else if (sscanf(line, "direction = %d", &i) == 1) {
374 log_dbg("Log: direction = %i", i);
375 rc->reencrypt_direction = i;
376 } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
377 log_dbg("Log: offset = %" PRIu64, u64);
378 rc->device_offset = u64;
379 } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
380 log_dbg("Log: shift = %" PRIu64, u64);
381 rc->device_shift = u64;
388 static int parse_log(struct reenc_ctx *rc)
393 s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
395 log_err(_("Cannot read reencryption log file.\n"));
399 rc->log_buf[SECTOR_SIZE - 1] = '\0';
402 end = strchr(start, '\n');
405 if (parse_line_log(rc, start)) {
406 log_err("Wrong log format.\n");
417 static void close_log(struct reenc_ctx *rc)
419 log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
420 if (rc->log_fd != -1)
426 static int open_log(struct reenc_ctx *rc)
428 int flags, create_new;
431 if (!stat(rc->log_file, &st))
433 else if (errno == ENOENT)
439 log_dbg("Creating LUKS reencryption log file %s.", rc->log_file);
440 flags = opt_directio ? O_RDWR|O_CREAT|O_DIRECT : O_RDWR|O_CREAT;
441 rc->log_fd = open(rc->log_file, flags, S_IRUSR|S_IWUSR);
442 if (rc->log_fd == -1)
445 log_dbg("Log file %s exists, restarting.", rc->log_file);
446 flags = opt_directio ? O_RDWR|O_DIRECT : O_RDWR;
447 rc->log_fd = open(rc->log_file, flags);
448 if (rc->log_fd == -1)
453 if (posix_memalign((void *)&rc->log_buf, alignment(rc->log_fd), SECTOR_SIZE)) {
454 log_err(_("Allocation of aligned memory failed.\n"));
459 if (create_new && write_log(rc) < 0) {
464 /* Be sure it is correct format */
465 return parse_log(rc);
468 static int activate_luks_headers(struct reenc_ctx *rc)
470 struct crypt_device *cd = NULL, *cd_new = NULL;
473 log_dbg("Activating LUKS devices from headers.");
475 if ((r = crypt_init(&cd, rc->header_file_org)) ||
476 (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
477 (r = crypt_set_data_device(cd, rc->device)))
480 if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
481 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
482 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
485 if ((r = crypt_init(&cd_new, rc->header_file_new)) ||
486 (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)) ||
487 (r = crypt_set_data_device(cd_new, rc->device)))
490 if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
491 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
492 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
499 log_err(_("Activation of temporary devices failed.\n"));
503 static int backup_luks_headers(struct reenc_ctx *rc)
505 struct crypt_device *cd = NULL, *cd_new = NULL;
506 struct crypt_params_luks1 params = {0};
507 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
510 log_dbg("Creating LUKS header backup for device %s.", rc->device);
512 if ((r = crypt_init(&cd, rc->device)) ||
513 (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
516 crypt_set_confirm_callback(cd, NULL, NULL);
517 if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org)))
519 log_verbose(_("LUKS header backup of device %s created.\n"), rc->device);
521 if ((r = create_empty_header(rc->header_file_new, rc->header_file_org,
522 crypt_get_data_offset(cd))))
525 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
526 params.data_alignment = crypt_get_data_offset(cd);
527 params.data_alignment += opt_reduce_device_size;
528 params.data_device = rc->device;
531 if ((r = crypt_init(&cd_new, rc->header_file_new)))
535 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
536 else if (opt_urandom)
537 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
539 if (opt_iteration_time)
540 crypt_set_iteration_time(cd_new, opt_iteration_time);
543 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
545 log_err(_("No known cipher specification pattern detected.\n"));
550 if ((r = crypt_format(cd_new, CRYPT_LUKS1,
551 opt_cipher ? cipher : crypt_get_cipher(cd),
552 opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
555 opt_key_size ? opt_key_size / 8 : crypt_get_volume_key_size(cd),
558 log_verbose(_("New LUKS header for device %s created.\n"), rc->device);
560 for (i = 0; i < MAX_SLOT; i++) {
561 if (!rc->p[i].password)
563 if ((r = crypt_keyslot_add_by_volume_key(cd_new, i,
564 NULL, 0, rc->p[i].password, rc->p[i].passwordLen)) < 0)
566 log_verbose(_("Activated keyslot %i.\n"), r);
573 log_err(_("Creation of LUKS backup headers failed.\n"));
577 static void remove_headers(struct reenc_ctx *rc)
579 struct crypt_device *cd = NULL;
581 log_dbg("Removing headers.");
583 if (crypt_init(&cd, NULL))
585 crypt_set_log_callback(cd, _quiet_log, NULL);
586 if (*rc->header_file_org)
587 (void)crypt_deactivate(cd, rc->header_file_org);
588 if (*rc->header_file_new)
589 (void)crypt_deactivate(cd, rc->header_file_new);
593 static int restore_luks_header(struct reenc_ctx *rc)
595 struct crypt_device *cd = NULL;
598 log_dbg("Restoring header for %s from %s.", rc->device, rc->header_file_new);
600 r = crypt_init(&cd, rc->device);
602 crypt_set_confirm_callback(cd, NULL, NULL);
603 r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new);
608 log_err(_("Cannot restore LUKS header on device %s.\n"), rc->device);
610 log_verbose(_("LUKS header on device %s restored.\n"), rc->device);
614 static void print_progress(struct reenc_ctx *rc, uint64_t bytes, int final)
616 unsigned long long mbytes, eta;
617 struct timeval now_time;
620 gettimeofday(&now_time, NULL);
621 if (!final && time_diff(rc->end_time, now_time) < 0.5)
624 rc->end_time = now_time;
629 tdiff = time_diff(rc->start_time, rc->end_time);
633 mbytes = (bytes - rc->restart_bytes) / 1024 / 1024;
634 mib = (double)(mbytes) / tdiff;
638 eta = (unsigned long long)(rc->device_size / 1024 / 1024 / mib - tdiff);
640 /* vt100 code clear line */
642 log_err(_("Progress: %5.1f%%, ETA %02llu:%02llu, "
643 "%4llu MiB written, speed %5.1f MiB/s%s"),
644 (double)bytes / rc->device_size * 100,
645 eta / 60, eta % 60, mbytes, mib,
649 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
650 size_t block_size, void *buf, uint64_t *bytes)
654 log_dbg("Reencrypting in forward direction.");
656 if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
657 lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
658 log_err(_("Cannot seek to device offset.\n"));
662 rc->restart_bytes = *bytes = rc->device_offset;
664 if (write_log(rc) < 0)
667 while (!quit && rc->device_offset < rc->device_size) {
668 s1 = read(fd_old, buf, block_size);
669 if (s1 < 0 || ((size_t)s1 != block_size &&
670 (rc->device_offset + s1) != rc->device_size)) {
671 log_dbg("Read error, expecting %d, got %d.",
672 (int)block_size, (int)s1);
676 s2 = write(fd_new, buf, s1);
678 log_dbg("Write error, expecting %d, got %d.",
679 (int)block_size, (int)s2);
683 rc->device_offset += s1;
684 if (opt_write_log && write_log(rc) < 0)
687 if (opt_fsync && fsync(fd_new) < 0) {
688 log_dbg("Write error, fsync.");
692 *bytes += (uint64_t)s2;
693 print_progress(rc, *bytes, 0);
696 return quit ? -EAGAIN : 0;
699 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
700 size_t block_size, void *buf, uint64_t *bytes)
702 ssize_t s1, s2, working_block;
703 off64_t working_offset;
705 log_dbg("Reencrypting in backward direction.");
707 if (!rc->in_progress) {
708 rc->device_offset = rc->device_size;
709 rc->restart_bytes = 0;
712 rc->restart_bytes = rc->device_size - rc->device_offset;
713 *bytes = rc->restart_bytes;
716 if (write_log(rc) < 0)
719 while (!quit && rc->device_offset) {
720 if (rc->device_offset < block_size) {
722 working_block = rc->device_offset;
724 working_offset = rc->device_offset - block_size;
725 working_block = block_size;
728 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
729 lseek64(fd_new, working_offset, SEEK_SET) < 0) {
730 log_err(_("Cannot seek to device offset.\n"));
734 s1 = read(fd_old, buf, working_block);
735 if (s1 < 0 || (s1 != working_block)) {
736 log_dbg("Read error, expecting %d, got %d.",
737 (int)block_size, (int)s1);
741 s2 = write(fd_new, buf, working_block);
743 log_dbg("Write error, expecting %d, got %d.",
744 (int)block_size, (int)s2);
748 rc->device_offset -= s1;
749 if (opt_write_log && write_log(rc) < 0)
752 if (opt_fsync && fsync(fd_new) < 0) {
753 log_dbg("Write error, fsync.");
757 *bytes += (uint64_t)s2;
758 print_progress(rc, *bytes, 0);
761 return quit ? -EAGAIN : 0;
764 static int copy_data(struct reenc_ctx *rc)
766 size_t block_size = opt_bsize * 1024 * 1024;
767 int fd_old = -1, fd_new = -1;
772 log_dbg("Data copy preparation.");
774 fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
776 log_err(_("Cannot open temporary LUKS header file.\n"));
780 fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
782 log_err(_("Cannot open temporary LUKS header file.\n"));
787 if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size) < 0) {
788 log_err(_("Cannot get device size.\n"));
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.");
831 /* Try to load LUKS from device */
832 if ((r = crypt_init(&cd, rc->device)))
834 crypt_set_log_callback(cd, _quiet_log, NULL);
835 r = crypt_load(cd, CRYPT_LUKS1, NULL);
837 rc->device_uuid = strdup(crypt_get_uuid(cd));
839 /* Reencryption already in progress - magic header? */
840 r = device_check(rc, CHECK_UNUSABLE);
846 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
847 const char *msg, int slot_check)
849 int r = -EINVAL, slot, retry_count;
851 slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
853 retry_count = opt_tries ?: 1;
854 while (retry_count--) {
856 r = crypt_get_key(msg, &rc->p[slot].password,
857 &rc->p[slot].passwordLen,
858 0, 0, NULL /*opt_key_file*/,
865 /* library uses sigint internally, until it is fixed...*/
867 r = crypt_activate_by_passphrase(cd, NULL, slot_check,
868 rc->p[slot].password, rc->p[slot].passwordLen, 0);
871 crypt_safe_free(rc->p[slot].password);
872 rc->p[slot].password = NULL;
873 rc->p[slot].passwordLen = 0;
875 if (r < 0 && r != -EPERM)
881 log_err(_("No key available with this passphrase.\n"));
886 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
890 slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
891 r = crypt_get_key(NULL, &rc->p[slot].password, &rc->p[slot].passwordLen,
892 opt_keyfile_offset, opt_keyfile_size, opt_key_file, 0, 0, cd);
896 r = crypt_activate_by_passphrase(cd, NULL, slot_check,
897 rc->p[slot].password, rc->p[slot].passwordLen, 0);
900 * Allow keyslot only if it is last slot or if user explicitly
901 * specify whch slot to use (IOW others will be disabled).
903 if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
904 crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
905 log_err(_("Key file can be used only with --key-slot or with "
906 "exactly one key slot active.\n"));
911 crypt_safe_free(rc->p[slot].password);
912 rc->p[slot].password = NULL;
913 rc->p[slot].passwordLen = 0;
915 log_err(_("No key available with this passphrase.\n"));
923 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
925 struct crypt_device *cd = NULL;
926 crypt_keyslot_info ki;
930 log_dbg("Passhrases initialization.");
932 if ((r = crypt_init(&cd, device)) ||
933 (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
934 (r = crypt_set_data_device(cd, rc->device))) {
940 r = init_keyfile(rc, cd, opt_key_slot);
941 } else if (rc->in_progress) {
942 r = init_passphrase1(rc, cd, _("Enter any LUKS passphrase: "), CRYPT_ANY_SLOT);
943 } else for (i = 0; i < MAX_SLOT; i++) {
944 ki = crypt_keyslot_status(cd, i);
945 if (ki != CRYPT_SLOT_ACTIVE && ki != CRYPT_SLOT_ACTIVE_LAST)
948 snprintf(msg, sizeof(msg), _("Enter LUKS passphrase for key slot %u: "), i);
949 r = init_passphrase1(rc, cd, msg, i);
955 return r > 0 ? 0 : r;
958 static int initialize_context(struct reenc_ctx *rc, const char *device)
960 log_dbg("Initialising reencryption context.");
964 if (!(rc->device = strndup(device, PATH_MAX)))
967 if (device_check(rc, CHECK_OPEN) < 0)
970 if (initialize_uuid(rc)) {
971 log_err(_("Device %s is not a valid LUKS device.\n"), device);
975 /* Prepare device names */
976 if (snprintf(rc->log_file, PATH_MAX,
977 "LUKS-%s.log", rc->device_uuid) < 0)
979 if (snprintf(rc->header_file_org, PATH_MAX,
980 "LUKS-%s.org", rc->device_uuid) < 0)
982 if (snprintf(rc->header_file_new, PATH_MAX,
983 "LUKS-%s.new", rc->device_uuid) < 0)
986 /* Paths to encrypted devices */
987 if (snprintf(rc->crypt_path_org, PATH_MAX,
988 "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
990 if (snprintf(rc->crypt_path_new, PATH_MAX,
991 "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
996 if (open_log(rc) < 0) {
997 log_err(_("Cannot open reencryption log file.\n"));
1001 if (!rc->in_progress) {
1002 if (!opt_reduce_device_size)
1003 rc->reencrypt_direction = FORWARD;
1005 rc->reencrypt_direction = BACKWARD;
1006 rc->device_offset = (uint64_t)~0;
1013 static void destroy_context(struct reenc_ctx *rc)
1017 log_dbg("Destroying reencryption context.");
1022 if ((rc->reencrypt_direction == FORWARD &&
1023 rc->device_offset == rc->device_size) ||
1024 (rc->reencrypt_direction == BACKWARD &&
1025 (rc->device_offset == 0 || rc->device_offset == (uint64_t)~0))) {
1026 unlink(rc->log_file);
1027 unlink(rc->header_file_org);
1028 unlink(rc->header_file_new);
1031 for (i = 0; i < MAX_SLOT; i++)
1032 crypt_safe_free(rc->p[i].password);
1035 free(rc->device_uuid);
1038 static int run_reencrypt(const char *device)
1041 struct reenc_ctx rc = {};
1043 if (initialize_context(&rc, device))
1046 log_dbg("Running reencryption.");
1048 if (!rc.in_progress) {
1049 if ((r = initialize_passphrase(&rc, rc.device)) ||
1050 (r = backup_luks_headers(&rc)) ||
1051 (r = device_check(&rc, MAKE_UNUSABLE)))
1054 if ((r = initialize_passphrase(&rc, rc.header_file_new)))
1058 if ((r = activate_luks_headers(&rc)))
1061 if ((r = copy_data(&rc)))
1064 r = restore_luks_header(&rc);
1066 destroy_context(&rc);
1070 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
1071 int exitcode, const char *error,
1074 poptPrintUsage(popt_context, stderr, 0);
1076 log_err("%s: %s\n", more, error);
1077 poptFreeContext(popt_context);
1081 static void help(poptContext popt_context,
1082 enum poptCallbackReason reason __attribute__((unused)),
1083 struct poptOption *key,
1084 const char *arg __attribute__((unused)),
1085 void *data __attribute__((unused)))
1087 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1090 static void _dbg_version_and_cmd(int argc, const char **argv)
1094 log_std("# %s %s processing \"", PACKAGE_REENC, PACKAGE_VERSION);
1095 for (i = 0; i < argc; i++) {
1098 log_std("%s", argv[i]);
1103 int main(int argc, const char **argv)
1105 static struct poptOption popt_help_options[] = {
1106 { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL },
1107 { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL },
1108 { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL },
1111 static struct poptOption popt_options[] = {
1112 { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1113 { "version", '\0', POPT_ARG_NONE, &opt_version_mode, 0, N_("Print package version"), NULL },
1114 { "verbose", 'v', POPT_ARG_NONE, &opt_verbose, 0, N_("Shows more detailed error messages"), NULL },
1115 { "debug", '\0', POPT_ARG_NONE, &opt_debug, 0, N_("Show debug messages"), NULL },
1116 { "block-size", 'B', POPT_ARG_INT, &opt_bsize, 0, N_("Reencryption block size"), N_("MiB") },
1117 { "cipher", 'c', POPT_ARG_STRING, &opt_cipher, 0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1118 { "key-size", 's', POPT_ARG_INT, &opt_key_size, 0, N_("The size of the encryption key"), N_("BITS") },
1119 { "hash", 'h', POPT_ARG_STRING, &opt_hash, 0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1120 { "key-file", 'd', POPT_ARG_STRING, &opt_key_file, 0, N_("Read the key from a file."), NULL },
1121 { "iter-time", 'i', POPT_ARG_INT, &opt_iteration_time, 0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1122 { "batch-mode", 'q', POPT_ARG_NONE, &opt_batch_mode, 0, N_("Do not ask for confirmation"), NULL },
1123 { "tries", 'T', POPT_ARG_INT, &opt_tries, 0, N_("How often the input of the passphrase can be retried"), NULL },
1124 { "use-random", '\0', POPT_ARG_NONE, &opt_random, 0, N_("Use /dev/random for generating volume key."), NULL },
1125 { "use-urandom", '\0', POPT_ARG_NONE, &opt_urandom, 0, N_("Use /dev/urandom for generating volume key."), NULL },
1126 { "use-directio", '\0', POPT_ARG_NONE, &opt_directio, 0, N_("Use direct-io when accesing devices."), NULL },
1127 { "use-fsync", '\0', POPT_ARG_NONE, &opt_fsync, 0, N_("Use fsync after each block."), NULL },
1128 { "write-log", '\0', POPT_ARG_NONE, &opt_write_log, 0, N_("Update log file after every block."), NULL },
1129 { "key-slot", 'S', POPT_ARG_INT, &opt_key_slot, 0, N_("Use only this slot (others will be disabled)."), NULL },
1130 { "keyfile-offset", '\0', POPT_ARG_LONG, &opt_keyfile_offset, 0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1131 { "keyfile-size", 'l', POPT_ARG_LONG, &opt_keyfile_size, 0, N_("Limits the read from keyfile"), N_("bytes") },
1132 { "reduce-device-size",'\0', POPT_ARG_INT, &opt_reduce_device_size, 0, N_("Reduce data device size (move data start). DANGEROUS!"), N_("SECTORS") },
1135 poptContext popt_context;
1138 crypt_set_log_callback(NULL, _log, NULL);
1142 setlocale(LC_ALL, "");
1143 bindtextdomain(PACKAGE, LOCALEDIR);
1144 textdomain(PACKAGE);
1146 popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1147 poptSetOtherOptionHelp(popt_context,
1148 N_("[OPTION...] <device>]"));
1150 while((r = poptGetNextOpt(popt_context)) > 0) ;
1152 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1153 poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1155 if (opt_version_mode) {
1156 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1157 poptFreeContext(popt_context);
1161 if (!opt_batch_mode) {
1162 log_std(_("WARNING: this is experimental code, it can completely break your data.\n"));
1163 log_verbose(_("Reencryption will change: volume key%s%s%s%s.\n"),
1164 opt_hash ? _(", set hash to ") : "", opt_hash ?: "",
1165 opt_cipher ? _(", set cipher to "): "", opt_cipher ?: "");
1168 action_argv = poptGetArgs(popt_context);
1170 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1171 poptGetInvocationName(popt_context));
1173 if (opt_random && opt_urandom)
1174 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1175 poptGetInvocationName(popt_context));
1177 if (opt_bsize < 1 || opt_bsize > 64)
1178 usage(popt_context, EXIT_FAILURE,
1179 _("Only values between 1MiB and 64 MiB allowed for reencryption block size."),
1180 poptGetInvocationName(popt_context));
1182 if (opt_reduce_device_size > 64 * 1024 * 1024 / SECTOR_SIZE)
1183 usage(popt_context, EXIT_FAILURE,
1184 _("Maximum device reduce size is 64 MiB."),
1185 poptGetInvocationName(popt_context));
1187 if (opt_key_size % 8)
1188 usage(popt_context, EXIT_FAILURE,
1189 _("Key size must be a multiple of 8 bits"),
1190 poptGetInvocationName(popt_context));
1194 crypt_set_debug_level(-1);
1195 _dbg_version_and_cmd(argc, argv);
1198 r = run_reencrypt(action_argv[0]);
1200 poptFreeContext(popt_context);
1202 /* Translate exit code to simple codes */
1204 case 0: r = EXIT_SUCCESS; break;
1206 case -EBUSY: r = 5; break;
1208 case -ENODEV: r = 4; break;
1209 case -ENOMEM: r = 3; break;
1210 case -EPERM: r = 2; break;
1211 default: r = EXIT_FAILURE;