2 * cryptsetup-reencrypt - crypt utility for offline re-encryption
4 * Copyright (C) 2012, Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2012-2015, 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>
26 #include <arpa/inet.h>
28 #define PACKAGE_REENC "crypt_reencrypt"
30 #define NO_UUID "cafecafe-cafe-cafe-cafe-cafecafeeeee"
31 #define MAX_BCK_SECTORS 8192
33 static const char *opt_cipher = NULL;
34 static const char *opt_hash = NULL;
35 static const char *opt_key_file = NULL;
36 static long opt_keyfile_size = 0;
37 static long opt_keyfile_offset = 0;
38 static int opt_iteration_time = 1000;
39 static int opt_version_mode = 0;
40 static int opt_random = 0;
41 static int opt_urandom = 0;
42 static int opt_bsize = 4;
43 static int opt_directio = 0;
44 static int opt_fsync = 0;
45 static int opt_write_log = 0;
46 static int opt_tries = 3;
47 static int opt_key_slot = CRYPT_ANY_SLOT;
48 static int opt_key_size = 0;
49 static int opt_new = 0;
50 static int opt_keep_key = 0;
51 static int opt_decrypt = 0;
53 static const char *opt_reduce_size_str = NULL;
54 static uint64_t opt_reduce_size = 0;
56 static const char *opt_device_size_str = NULL;
57 static uint64_t opt_device_size = 0;
59 static const char **action_argv;
65 uint64_t device_size; /* overrided by parameter */
66 uint64_t device_size_new_real;
67 uint64_t device_size_org_real;
68 uint64_t device_offset;
69 uint64_t device_shift;
72 enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
73 enum { REENCRYPT = 0, ENCRYPT = 1, DECRYPT = 2 } reencrypt_mode;
75 char header_file_org[PATH_MAX];
76 char header_file_new[PATH_MAX];
77 char log_file[PATH_MAX];
79 char crypt_path_org[PATH_MAX];
80 char crypt_path_new[PATH_MAX];
82 char log_buf[SECTOR_SIZE];
90 struct timeval start_time, end_time;
91 uint64_t resume_bytes;
94 char MAGIC[] = {'L','U','K','S', 0xba, 0xbe};
95 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
105 static void _quiet_log(int level, const char *msg, void *usrptr)
109 tool_log(level, msg, usrptr);
112 /* The difference in seconds between two times in "timeval" format. */
113 static double time_diff(struct timeval start, struct timeval end)
115 return (end.tv_sec - start.tv_sec)
116 + (end.tv_usec - start.tv_usec) / 1E6;
119 static int alignment(int fd)
123 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
129 static size_t pagesize(void)
131 long r = sysconf(_SC_PAGESIZE);
132 return r < 0 ? 4096 : (size_t)r;
135 /* Depends on the first two fields of LUKS1 header format, magic and version */
136 static int device_check(struct reenc_ctx *rc, header_magic set_magic)
142 size_t buf_size = pagesize();
144 devfd = open(rc->device, O_RDWR | O_EXCL | O_DIRECT);
146 if (errno == EBUSY) {
147 log_err(_("Cannot exclusively open %s, device in use.\n"),
151 log_err(_("Cannot open device %s\n"), rc->device);
155 if (set_magic == CHECK_OPEN) {
160 if (posix_memalign((void *)&buf, alignment(devfd), buf_size)) {
161 log_err(_("Allocation of aligned memory failed.\n"));
166 s = read(devfd, buf, buf_size);
167 if (s < 0 || s != (ssize_t)buf_size) {
168 log_err(_("Cannot read device %s.\n"), rc->device);
173 /* Be sure that we do not process new version of header */
174 memcpy((void*)&version, &buf[MAGIC_L], sizeof(uint16_t));
175 version = ntohs(version);
177 if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L) &&
179 log_verbose(_("Marking LUKS device %s unusable.\n"), rc->device);
180 memcpy(buf, NOMAGIC, MAGIC_L);
182 } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L) &&
184 log_verbose(_("Marking LUKS device %s usable.\n"), rc->device);
185 memcpy(buf, MAGIC, MAGIC_L);
187 } else if (set_magic == CHECK_UNUSABLE && version == 1) {
188 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
190 rc->device_uuid = strndup(&buf[0xa8], 40);
196 if (lseek(devfd, 0, SEEK_SET) == -1)
198 s = write(devfd, buf, buf_size);
199 if (s < 0 || s != (ssize_t)buf_size) {
200 log_err(_("Cannot write device %s.\n"), rc->device);
204 log_dbg("LUKS signature check failed for %s.", rc->device);
207 memset(buf, 0, buf_size);
213 static int create_empty_header(const char *new_file, const char *old_file,
214 uint64_t data_sector)
221 /* Never create header > 4MiB */
222 if (data_sector > MAX_BCK_SECTORS)
223 data_sector = MAX_BCK_SECTORS;
225 /* new header file of the same size as old backup */
227 if (stat(old_file, &st) == -1 ||
228 (st.st_mode & S_IFMT) != S_IFREG ||
229 (st.st_size > 16 * 1024 * 1024))
235 * if requesting key size change, try to use offset
236 * here can be enough space to fit new key.
239 size = data_sector * SECTOR_SIZE;
241 /* if reducing size, be sure we have enough space */
243 size += opt_reduce_size;
245 log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
247 if (!size || !(buf = malloc(size)))
249 memset(buf, 0, size);
251 fd = creat(new_file, S_IRUSR|S_IWUSR);
257 if (write(fd, buf, size) < size)
265 static int write_log(struct reenc_ctx *rc)
269 memset(rc->log_buf, 0, SECTOR_SIZE);
270 snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
271 "version = %d\nUUID = %s\ndirection = %d\nmode = %d\n"
272 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
273 2, rc->device_uuid, rc->reencrypt_direction, rc->reencrypt_mode,
274 rc->device_offset, rc->device_shift);
276 if (lseek(rc->log_fd, 0, SEEK_SET) == -1)
279 r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
280 if (r < 0 || r != SECTOR_SIZE) {
281 log_err(_("Cannot write reencryption log file.\n"));
288 static int parse_line_log(struct reenc_ctx *rc, const char *line)
294 /* whole line is comment */
298 if (sscanf(line, "version = %d", &i) == 1) {
299 if (i < 1 || i > 2) {
300 log_dbg("Log: Unexpected version = %i", i);
303 } else if (sscanf(line, "UUID = %40s", s) == 1) {
304 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
305 log_dbg("Log: Unexpected UUID %s", s);
308 } else if (sscanf(line, "direction = %d", &i) == 1) {
309 log_dbg("Log: direction = %i", i);
310 rc->reencrypt_direction = i;
311 } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
312 log_dbg("Log: offset = %" PRIu64, u64);
313 rc->device_offset = u64;
314 } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
315 log_dbg("Log: shift = %" PRIu64, u64);
316 rc->device_shift = u64;
317 } else if (sscanf(line, "mode = %d", &i) == 1) { /* added in v2 */
318 log_dbg("Log: mode = %i", i);
319 rc->reencrypt_mode = i;
320 if (rc->reencrypt_mode != REENCRYPT &&
321 rc->reencrypt_mode != ENCRYPT &&
322 rc->reencrypt_mode != DECRYPT)
330 static int parse_log(struct reenc_ctx *rc)
335 s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
337 log_err(_("Cannot read reencryption log file.\n"));
341 rc->log_buf[SECTOR_SIZE - 1] = '\0';
344 end = strchr(start, '\n');
347 if (parse_line_log(rc, start)) {
348 log_err("Wrong log format.\n");
359 static void close_log(struct reenc_ctx *rc)
361 log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
362 if (rc->log_fd != -1)
366 static int open_log(struct reenc_ctx *rc)
368 int flags = opt_fsync ? O_SYNC : 0;
370 rc->log_fd = open(rc->log_file, O_RDWR|O_EXCL|O_CREAT|flags, S_IRUSR|S_IWUSR);
371 if (rc->log_fd != -1) {
372 log_dbg("Created LUKS reencryption log file %s.", rc->log_file);
373 } else if (errno == EEXIST) {
374 log_std(_("Log file %s exists, resuming reencryption.\n"), rc->log_file);
375 rc->log_fd = open(rc->log_file, O_RDWR|flags);
379 if (rc->log_fd == -1)
382 if (!rc->in_progress && 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 log_verbose(_("Activating temporary device using old LUKS header.\n"));
404 if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
405 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
406 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
409 if ((r = crypt_init(&cd_new, rc->header_file_new)) ||
410 (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)) ||
411 (r = crypt_set_data_device(cd_new, rc->device)))
414 log_verbose(_("Activating temporary device using new LUKS header.\n"));
415 if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
416 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
417 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
424 log_err(_("Activation of temporary devices failed.\n"));
428 static int create_new_header(struct reenc_ctx *rc, const char *cipher,
429 const char *cipher_mode, const char *uuid,
430 const char *key, int key_size,
431 struct crypt_params_luks1 *params)
433 struct crypt_device *cd_new = NULL;
436 if ((r = crypt_init(&cd_new, rc->header_file_new)))
440 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
441 else if (opt_urandom)
442 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
444 if (opt_iteration_time)
445 crypt_set_iteration_time(cd_new, opt_iteration_time);
447 if ((r = crypt_format(cd_new, CRYPT_LUKS1, cipher, cipher_mode,
448 uuid, key, key_size, params)))
450 log_verbose(_("New LUKS header for device %s created.\n"), rc->device);
452 for (i = 0; i < MAX_SLOT; i++) {
453 if (!rc->p[i].password)
455 if ((r = crypt_keyslot_add_by_volume_key(cd_new, i,
456 NULL, 0, rc->p[i].password, rc->p[i].passwordLen)) < 0)
458 log_verbose(_("Activated keyslot %i.\n"), r);
466 static int backup_luks_headers(struct reenc_ctx *rc)
468 struct crypt_device *cd = NULL;
469 struct crypt_params_luks1 params = {0};
470 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
471 char *old_key = NULL;
475 log_dbg("Creating LUKS header backup for device %s.", rc->device);
477 if ((r = crypt_init(&cd, rc->device)) ||
478 (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
481 crypt_set_confirm_callback(cd, NULL, NULL);
482 if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org)))
484 log_verbose(_("LUKS header backup of device %s created.\n"), rc->device);
486 /* For decrypt, new header will be fake one, so we are done here. */
487 if (rc->reencrypt_mode == DECRYPT)
490 if ((r = create_empty_header(rc->header_file_new, rc->header_file_org,
491 crypt_get_data_offset(cd))))
494 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
495 params.data_alignment = crypt_get_data_offset(cd);
496 params.data_alignment += ROUND_SECTOR(opt_reduce_size);
497 params.data_device = rc->device;
500 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
502 log_err(_("No known cipher specification pattern detected.\n"));
508 log_dbg("Keeping key from old header.");
509 old_key_size = crypt_get_volume_key_size(cd);
510 old_key = crypt_safe_alloc(old_key_size);
515 r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, old_key, &old_key_size,
516 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
521 r = create_new_header(rc,
522 opt_cipher ? cipher : crypt_get_cipher(cd),
523 opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
526 opt_key_size ? opt_key_size / 8 : crypt_get_volume_key_size(cd),
530 crypt_safe_free(old_key);
532 log_err(_("Creation of LUKS backup headers failed.\n"));
536 /* Create fake header for original device */
537 static int backup_fake_header(struct reenc_ctx *rc)
539 struct crypt_device *cd_new = NULL;
540 struct crypt_params_luks1 params = {0};
541 char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
542 const char *header_file_fake;
545 log_dbg("Creating fake (cipher_null) header for %s device.",
546 (rc->reencrypt_mode == DECRYPT) ? "new" : "original");
548 header_file_fake = (rc->reencrypt_mode == DECRYPT) ? rc->header_file_new : rc->header_file_org;
551 opt_key_size = DEFAULT_LUKS1_KEYBITS;
554 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
556 log_err(_("No known cipher specification pattern detected.\n"));
561 r = create_empty_header(header_file_fake, NULL, MAX_BCK_SECTORS);
565 params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
566 params.data_alignment = 0;
567 params.data_device = rc->device;
569 r = crypt_init(&cd_new, header_file_fake);
573 r = crypt_format(cd_new, CRYPT_LUKS1, "cipher_null", "ecb",
574 NO_UUID, NULL, opt_key_size / 8, ¶ms);
578 r = crypt_keyslot_add_by_volume_key(cd_new, rc->keyslot, NULL, 0,
579 rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen);
583 /* The real header is backup header created in backup_luks_headers() */
584 if (rc->reencrypt_mode == DECRYPT)
587 r = create_empty_header(rc->header_file_new, rc->header_file_org, 0);
591 params.data_alignment = ROUND_SECTOR(opt_reduce_size);
592 r = create_new_header(rc,
593 opt_cipher ? cipher : DEFAULT_LUKS1_CIPHER,
594 opt_cipher ? cipher_mode : DEFAULT_LUKS1_MODE,
596 (opt_key_size ? opt_key_size : DEFAULT_LUKS1_KEYBITS) / 8,
603 static void remove_headers(struct reenc_ctx *rc)
605 struct crypt_device *cd = NULL;
607 log_dbg("Removing headers.");
609 if (crypt_init(&cd, NULL))
611 crypt_set_log_callback(cd, _quiet_log, NULL);
612 if (*rc->header_file_org)
613 (void)crypt_deactivate(cd, rc->header_file_org);
614 if (*rc->header_file_new)
615 (void)crypt_deactivate(cd, rc->header_file_new);
619 static int restore_luks_header(struct reenc_ctx *rc)
621 struct crypt_device *cd = NULL;
624 log_dbg("Restoring header for %s from %s.", rc->device, rc->header_file_new);
626 r = crypt_init(&cd, rc->device);
628 crypt_set_confirm_callback(cd, NULL, NULL);
629 r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new);
634 log_err(_("Cannot restore LUKS header on device %s.\n"), rc->device);
636 log_verbose(_("LUKS header on device %s restored.\n"), rc->device);
640 static void print_progress(struct reenc_ctx *rc, uint64_t bytes, int final)
642 unsigned long long mbytes, eta;
643 struct timeval now_time;
646 gettimeofday(&now_time, NULL);
647 if (!final && time_diff(rc->end_time, now_time) < 0.5)
650 rc->end_time = now_time;
655 tdiff = time_diff(rc->start_time, rc->end_time);
659 mbytes = (bytes - rc->resume_bytes) / 1024 / 1024;
660 mib = (double)(mbytes) / tdiff;
664 /* FIXME: calculate this from last minute only and remaining space */
665 eta = (unsigned long long)(rc->device_size / 1024 / 1024 / mib - tdiff);
667 /* vt100 code clear line */
669 log_err(_("Progress: %5.1f%%, ETA %02llu:%02llu, "
670 "%4llu MiB written, speed %5.1f MiB/s%s"),
671 (double)bytes / rc->device_size * 100,
672 eta / 60, eta % 60, mbytes, mib,
676 static ssize_t read_buf(int fd, void *buf, size_t count)
678 size_t read_size = 0;
682 /* This expects that partial read is aligned in buffer */
683 s = read(fd, buf, count - read_size);
684 if (s == -1 && errno != EINTR)
687 return (ssize_t)read_size;
689 if (s != (ssize_t)count)
690 log_dbg("Partial read %zd / %zu.", s, count);
691 read_size += (size_t)s;
692 buf = (uint8_t*)buf + s;
694 } while (read_size != count);
696 return (ssize_t)count;
699 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
700 size_t block_size, void *buf, uint64_t *bytes)
704 log_dbg("Reencrypting in forward direction.");
706 if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
707 lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
708 log_err(_("Cannot seek to device offset.\n"));
712 rc->resume_bytes = *bytes = rc->device_offset;
714 if (write_log(rc) < 0)
717 while (!quit && rc->device_offset < rc->device_size) {
718 s1 = read_buf(fd_old, buf, block_size);
719 if (s1 < 0 || ((size_t)s1 != block_size &&
720 (rc->device_offset + s1) != rc->device_size)) {
721 log_dbg("Read error, expecting %zu, got %zd.",
726 /* If device_size is forced, never write more than limit */
727 if ((s1 + rc->device_offset) > rc->device_size)
728 s1 = rc->device_size - rc->device_offset;
730 s2 = write(fd_new, buf, s1);
732 log_dbg("Write error, expecting %zu, got %zd.",
737 rc->device_offset += s1;
738 if (opt_write_log && write_log(rc) < 0)
741 if (opt_fsync && fsync(fd_new) < 0) {
742 log_dbg("Write error, fsync.");
746 *bytes += (uint64_t)s2;
747 print_progress(rc, *bytes, 0);
750 return quit ? -EAGAIN : 0;
753 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
754 size_t block_size, void *buf, uint64_t *bytes)
756 ssize_t s1, s2, working_block;
757 off64_t working_offset;
759 log_dbg("Reencrypting in backward direction.");
761 if (!rc->in_progress) {
762 rc->device_offset = rc->device_size;
763 rc->resume_bytes = 0;
766 rc->resume_bytes = rc->device_size - rc->device_offset;
767 *bytes = rc->resume_bytes;
770 if (write_log(rc) < 0)
773 while (!quit && rc->device_offset) {
774 if (rc->device_offset < block_size) {
776 working_block = rc->device_offset;
778 working_offset = rc->device_offset - block_size;
779 working_block = block_size;
782 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
783 lseek64(fd_new, working_offset, SEEK_SET) < 0) {
784 log_err(_("Cannot seek to device offset.\n"));
788 s1 = read_buf(fd_old, buf, working_block);
789 if (s1 < 0 || (s1 != working_block)) {
790 log_dbg("Read error, expecting %zu, got %zd.",
795 s2 = write(fd_new, buf, working_block);
797 log_dbg("Write error, expecting %zu, got %zd.",
802 rc->device_offset -= s1;
803 if (opt_write_log && write_log(rc) < 0)
806 if (opt_fsync && fsync(fd_new) < 0) {
807 log_dbg("Write error, fsync.");
811 *bytes += (uint64_t)s2;
812 print_progress(rc, *bytes, 0);
815 return quit ? -EAGAIN : 0;
818 static void zero_rest_of_device(int fd, size_t block_size, void *buf,
819 uint64_t *bytes, uint64_t offset)
823 log_dbg("Zeroing rest of device.");
825 if (lseek64(fd, offset, SEEK_SET) < 0) {
826 log_dbg(_("Cannot seek to device offset.\n"));
830 memset(buf, 0, block_size);
833 while (!quit && *bytes) {
837 s2 = write(fd, buf, s1);
839 log_dbg("Write error, expecting %zu, got %zd.",
844 if (opt_fsync && fsync(fd) < 0) {
845 log_dbg("Write error, fsync.");
853 static int copy_data(struct reenc_ctx *rc)
855 size_t block_size = opt_bsize * 1024 * 1024;
856 int fd_old = -1, fd_new = -1;
861 log_dbg("Data copy preparation.");
863 fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
865 log_err(_("Cannot open temporary LUKS header file.\n"));
869 fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
871 log_err(_("Cannot open temporary LUKS header file.\n"));
875 if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size_org_real) < 0) {
876 log_err(_("Cannot get device size.\n"));
880 if (ioctl(fd_new, BLKGETSIZE64, &rc->device_size_new_real) < 0) {
881 log_err(_("Cannot get device size.\n"));
886 rc->device_size = opt_device_size;
887 else if (rc->reencrypt_mode == DECRYPT)
888 rc->device_size = rc->device_size_org_real;
890 rc->device_size = rc->device_size_new_real;
892 if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
893 log_err(_("Allocation of aligned memory failed.\n"));
899 gettimeofday(&rc->start_time, NULL);
901 if (rc->reencrypt_direction == FORWARD)
902 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
904 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
906 print_progress(rc, bytes, 1);
908 /* Zero (wipe) rest of now plain-only device when decrypting.
909 * (To not leave any sign of encryption here.) */
910 if (!r && rc->reencrypt_mode == DECRYPT &&
911 rc->device_size_new_real > rc->device_size_org_real) {
912 bytes = rc->device_size_new_real - rc->device_size_org_real;
913 zero_rest_of_device(fd_new, block_size, buf, &bytes, rc->device_size_org_real);
919 log_err(_("Interrupted by a signal.\n"));
921 log_err(_("IO error during reencryption.\n"));
933 static int initialize_uuid(struct reenc_ctx *rc)
935 struct crypt_device *cd = NULL;
938 log_dbg("Initialising UUID.");
941 rc->device_uuid = strdup(NO_UUID);
945 /* Try to load LUKS from device */
946 if ((r = crypt_init(&cd, rc->device)))
948 crypt_set_log_callback(cd, _quiet_log, NULL);
949 r = crypt_load(cd, CRYPT_LUKS1, NULL);
951 rc->device_uuid = strdup(crypt_get_uuid(cd));
953 /* Reencryption already in progress - magic header? */
954 r = device_check(rc, CHECK_UNUSABLE);
960 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
961 const char *msg, int slot_to_check, int check)
964 int r = -EINVAL, retry_count;
967 retry_count = opt_tries ?: 1;
968 while (retry_count--) {
970 r = crypt_get_key(msg, &password, &passwordLen,
971 0, 0, NULL /*opt_key_file*/,
978 /* library uses sigint internally, until it is fixed...*/
981 r = crypt_activate_by_passphrase(cd, NULL, slot_to_check,
982 password, passwordLen, 0);
984 r = (slot_to_check == CRYPT_ANY_SLOT) ? 0 : slot_to_check;
987 crypt_safe_free(password);
991 if (r < 0 && r != -EPERM)
995 rc->p[r].password = password;
996 rc->p[r].passwordLen = passwordLen;
999 log_err(_("No key available with this passphrase.\n"));
1008 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
1014 r = crypt_get_key(NULL, &password, &passwordLen, opt_keyfile_offset,
1015 opt_keyfile_size, opt_key_file, 0, 0, cd);
1019 r = crypt_activate_by_passphrase(cd, NULL, slot_check, password,
1023 * Allow keyslot only if it is last slot or if user explicitly
1024 * specify which slot to use (IOW others will be disabled).
1026 if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
1027 crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
1028 log_err(_("Key file can be used only with --key-slot or with "
1029 "exactly one key slot active.\n"));
1034 crypt_safe_free(password);
1036 log_err(_("No key available with this passphrase.\n"));
1039 rc->p[r].password = password;
1040 rc->p[r].passwordLen = passwordLen;
1049 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
1051 struct crypt_device *cd = NULL;
1052 crypt_keyslot_info ki;
1056 log_dbg("Passhrases initialization.");
1058 if (rc->reencrypt_mode == ENCRYPT && !rc->in_progress) {
1059 r = init_passphrase1(rc, cd, _("Enter new passphrase: "), opt_key_slot, 0);
1060 return r > 0 ? 0 : r;
1063 if ((r = crypt_init(&cd, device)) ||
1064 (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
1065 (r = crypt_set_data_device(cd, rc->device))) {
1070 if (opt_key_slot != CRYPT_ANY_SLOT)
1071 snprintf(msg, sizeof(msg),
1072 _("Enter passphrase for key slot %u: "), opt_key_slot);
1074 snprintf(msg, sizeof(msg), _("Enter any existing passphrase: "));
1077 r = init_keyfile(rc, cd, opt_key_slot);
1078 } else if (rc->in_progress ||
1079 opt_key_slot != CRYPT_ANY_SLOT ||
1080 rc->reencrypt_mode == DECRYPT) {
1081 r = init_passphrase1(rc, cd, msg, opt_key_slot, 1);
1082 } else for (i = 0; i < MAX_SLOT; i++) {
1083 ki = crypt_keyslot_status(cd, i);
1084 if (ki != CRYPT_SLOT_ACTIVE && ki != CRYPT_SLOT_ACTIVE_LAST)
1087 snprintf(msg, sizeof(msg), _("Enter passphrase for key slot %u: "), i);
1088 r = init_passphrase1(rc, cd, msg, i, 1);
1094 return r > 0 ? 0 : r;
1097 static int initialize_context(struct reenc_ctx *rc, const char *device)
1099 log_dbg("Initialising reencryption context.");
1103 if (!(rc->device = strndup(device, PATH_MAX)))
1106 if (device_check(rc, CHECK_OPEN) < 0)
1109 if (initialize_uuid(rc)) {
1110 log_err(_("Device %s is not a valid LUKS device.\n"), device);
1114 /* Prepare device names */
1115 if (snprintf(rc->log_file, PATH_MAX,
1116 "LUKS-%s.log", rc->device_uuid) < 0)
1118 if (snprintf(rc->header_file_org, PATH_MAX,
1119 "LUKS-%s.org", rc->device_uuid) < 0)
1121 if (snprintf(rc->header_file_new, PATH_MAX,
1122 "LUKS-%s.new", rc->device_uuid) < 0)
1125 /* Paths to encrypted devices */
1126 if (snprintf(rc->crypt_path_org, PATH_MAX,
1127 "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
1129 if (snprintf(rc->crypt_path_new, PATH_MAX,
1130 "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
1135 if (open_log(rc) < 0) {
1136 log_err(_("Cannot open reencryption log file.\n"));
1140 if (!rc->in_progress) {
1141 if (!opt_reduce_size)
1142 rc->reencrypt_direction = FORWARD;
1144 rc->reencrypt_direction = BACKWARD;
1145 rc->device_offset = (uint64_t)~0;
1149 rc->reencrypt_mode = ENCRYPT;
1150 else if (opt_decrypt)
1151 rc->reencrypt_mode = DECRYPT;
1153 rc->reencrypt_mode = REENCRYPT;
1159 static void destroy_context(struct reenc_ctx *rc)
1163 log_dbg("Destroying reencryption context.");
1168 if ((rc->reencrypt_direction == FORWARD &&
1169 rc->device_offset == rc->device_size) ||
1170 (rc->reencrypt_direction == BACKWARD &&
1171 (rc->device_offset == 0 || rc->device_offset == (uint64_t)~0))) {
1172 unlink(rc->log_file);
1173 unlink(rc->header_file_org);
1174 unlink(rc->header_file_new);
1177 for (i = 0; i < MAX_SLOT; i++)
1178 crypt_safe_free(rc->p[i].password);
1181 free(rc->device_uuid);
1184 static int run_reencrypt(const char *device)
1187 static struct reenc_ctx rc = {};
1189 if (initialize_context(&rc, device))
1192 log_dbg("Running reencryption.");
1194 if (!rc.in_progress) {
1195 if ((r = initialize_passphrase(&rc, rc.device)))
1198 if (rc.reencrypt_mode == ENCRYPT) {
1199 /* Create fake header for exising device */
1200 if ((r = backup_fake_header(&rc)))
1203 if ((r = backup_luks_headers(&rc)))
1205 /* Create fake header for decrypted device */
1206 if (rc.reencrypt_mode == DECRYPT &&
1207 (r = backup_fake_header(&rc)))
1209 if ((r = device_check(&rc, MAKE_UNUSABLE)))
1213 if ((r = initialize_passphrase(&rc, rc.header_file_new)))
1217 if (!opt_keep_key) {
1218 log_dbg("Running data area reencryption.");
1219 if ((r = activate_luks_headers(&rc)))
1222 if ((r = copy_data(&rc)))
1225 log_dbg("Keeping existing key, skipping data area reencryption.");
1227 // FIXME: fix error path above to not skip this
1228 if (rc.reencrypt_mode != DECRYPT)
1229 r = restore_luks_header(&rc);
1231 destroy_context(&rc);
1235 static void help(poptContext popt_context,
1236 enum poptCallbackReason reason __attribute__((unused)),
1237 struct poptOption *key,
1238 const char *arg __attribute__((unused)),
1239 void *data __attribute__((unused)))
1241 if (key->shortName == '?') {
1242 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1243 poptPrintHelp(popt_context, stdout, 0);
1246 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1249 int main(int argc, const char **argv)
1251 static struct poptOption popt_help_options[] = {
1252 { NULL, '\0', POPT_ARG_CALLBACK, help, 0, NULL, NULL },
1253 { "help", '?', POPT_ARG_NONE, NULL, 0, N_("Show this help message"), NULL },
1254 { "usage", '\0', POPT_ARG_NONE, NULL, 0, N_("Display brief usage"), NULL },
1257 static struct poptOption popt_options[] = {
1258 { NULL, '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1259 { "version", '\0', POPT_ARG_NONE, &opt_version_mode, 0, N_("Print package version"), NULL },
1260 { "verbose", 'v', POPT_ARG_NONE, &opt_verbose, 0, N_("Shows more detailed error messages"), NULL },
1261 { "debug", '\0', POPT_ARG_NONE, &opt_debug, 0, N_("Show debug messages"), NULL },
1262 { "block-size", 'B', POPT_ARG_INT, &opt_bsize, 0, N_("Reencryption block size"), N_("MiB") },
1263 { "cipher", 'c', POPT_ARG_STRING, &opt_cipher, 0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1264 { "key-size", 's', POPT_ARG_INT, &opt_key_size, 0, N_("The size of the encryption key"), N_("BITS") },
1265 { "hash", 'h', POPT_ARG_STRING, &opt_hash, 0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1266 { "keep-key", '\0', POPT_ARG_NONE, &opt_keep_key, 0, N_("Do not change key, no data area reencryption."), NULL },
1267 { "key-file", 'd', POPT_ARG_STRING, &opt_key_file, 0, N_("Read the key from a file."), NULL },
1268 { "iter-time", 'i', POPT_ARG_INT, &opt_iteration_time, 0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1269 { "batch-mode", 'q', POPT_ARG_NONE, &opt_batch_mode, 0, N_("Do not ask for confirmation"), NULL },
1270 { "tries", 'T', POPT_ARG_INT, &opt_tries, 0, N_("How often the input of the passphrase can be retried"), NULL },
1271 { "use-random", '\0', POPT_ARG_NONE, &opt_random, 0, N_("Use /dev/random for generating volume key."), NULL },
1272 { "use-urandom", '\0', POPT_ARG_NONE, &opt_urandom, 0, N_("Use /dev/urandom for generating volume key."), NULL },
1273 { "use-directio", '\0', POPT_ARG_NONE, &opt_directio, 0, N_("Use direct-io when accessing devices."), NULL },
1274 { "use-fsync", '\0', POPT_ARG_NONE, &opt_fsync, 0, N_("Use fsync after each block."), NULL },
1275 { "write-log", '\0', POPT_ARG_NONE, &opt_write_log, 0, N_("Update log file after every block."), NULL },
1276 { "key-slot", 'S', POPT_ARG_INT, &opt_key_slot, 0, N_("Use only this slot (others will be disabled)."), NULL },
1277 { "keyfile-offset", '\0', POPT_ARG_LONG, &opt_keyfile_offset, 0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1278 { "keyfile-size", 'l', POPT_ARG_LONG, &opt_keyfile_size, 0, N_("Limits the read from keyfile"), N_("bytes") },
1279 { "reduce-device-size",'\0', POPT_ARG_STRING, &opt_reduce_size_str, 0, N_("Reduce data device size (move data offset). DANGEROUS!"), N_("bytes") },
1280 { "device-size", '\0', POPT_ARG_STRING, &opt_device_size_str, 0, N_("Use only specified device size (ignore rest of device). DANGEROUS!"), N_("bytes") },
1281 { "new", 'N', POPT_ARG_NONE, &opt_new, 0, N_("Create new header on not encrypted device."), NULL },
1282 { "decrypt", '\0', POPT_ARG_NONE, &opt_decrypt, 0, N_("Permanently decrypt device (remove encryption)."), NULL },
1285 poptContext popt_context;
1288 crypt_set_log_callback(NULL, tool_log, NULL);
1292 setlocale(LC_ALL, "");
1293 bindtextdomain(PACKAGE, LOCALEDIR);
1294 textdomain(PACKAGE);
1296 popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1297 poptSetOtherOptionHelp(popt_context,
1298 _("[OPTION...] <device>"));
1300 while((r = poptGetNextOpt(popt_context)) > 0) ;
1302 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1303 poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1305 if (opt_version_mode) {
1306 log_std("%s %s\n", PACKAGE_REENC, PACKAGE_VERSION);
1307 poptFreeContext(popt_context);
1311 if (!opt_batch_mode) {
1312 log_std(_("WARNING: this is experimental code, it can completely break your data.\n"));
1313 log_verbose(_("Reencryption will change: volume key%s%s%s%s.\n"),
1314 opt_hash ? _(", set hash to ") : "", opt_hash ?: "",
1315 opt_cipher ? _(", set cipher to "): "", opt_cipher ?: "");
1318 action_argv = poptGetArgs(popt_context);
1320 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1321 poptGetInvocationName(popt_context));
1323 if (opt_random && opt_urandom)
1324 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1325 poptGetInvocationName(popt_context));
1327 if (opt_bsize < 0 || opt_key_size < 0 || opt_iteration_time < 0 ||
1328 opt_tries < 0 || opt_keyfile_offset < 0 || opt_key_size < 0) {
1329 usage(popt_context, EXIT_FAILURE,
1330 _("Negative number for option not permitted."),
1331 poptGetInvocationName(popt_context));
1334 if (opt_bsize < 1 || opt_bsize > 64)
1335 usage(popt_context, EXIT_FAILURE,
1336 _("Only values between 1 MiB and 64 MiB allowed for reencryption block size."),
1337 poptGetInvocationName(popt_context));
1339 if (opt_key_size % 8)
1340 usage(popt_context, EXIT_FAILURE,
1341 _("Key size must be a multiple of 8 bits"),
1342 poptGetInvocationName(popt_context));
1344 if (opt_key_slot != CRYPT_ANY_SLOT &&
1345 (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS1)))
1346 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1347 poptGetInvocationName(popt_context));
1349 if (opt_random && opt_urandom)
1350 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1351 poptGetInvocationName(popt_context));
1353 if (opt_device_size_str &&
1354 crypt_string_to_size(NULL, opt_device_size_str, &opt_device_size))
1355 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1356 poptGetInvocationName(popt_context));
1358 if (opt_reduce_size_str &&
1359 crypt_string_to_size(NULL, opt_reduce_size_str, &opt_reduce_size))
1360 usage(popt_context, EXIT_FAILURE, _("Invalid device size specification."),
1361 poptGetInvocationName(popt_context));
1362 if (opt_reduce_size > 64 * 1024 * 1024)
1363 usage(popt_context, EXIT_FAILURE, _("Maximum device reduce size is 64 MiB."),
1364 poptGetInvocationName(popt_context));
1365 if (opt_reduce_size % SECTOR_SIZE)
1366 usage(popt_context, EXIT_FAILURE, _("Reduce size must be multiple of 512 bytes sector."),
1367 poptGetInvocationName(popt_context));
1369 if (opt_new && !opt_reduce_size)
1370 usage(popt_context, EXIT_FAILURE, _("Option --new must be used together with --reduce-device-size."),
1371 poptGetInvocationName(popt_context));
1373 if (opt_keep_key && ((!opt_hash && !opt_iteration_time) || opt_cipher || opt_new))
1374 usage(popt_context, EXIT_FAILURE, _("Option --keep-key can be used only with --hash or --iter-time."),
1375 poptGetInvocationName(popt_context));
1377 if (opt_new && opt_decrypt)
1378 usage(popt_context, EXIT_FAILURE, _("Option --new cannot be used together with --decrypt."),
1379 poptGetInvocationName(popt_context));
1381 if (opt_decrypt && (opt_cipher || opt_hash || opt_reduce_size || opt_keep_key || opt_device_size))
1382 usage(popt_context, EXIT_FAILURE, _("Option --decrypt is incompatible with specified parameters."),
1383 poptGetInvocationName(popt_context));
1387 crypt_set_debug_level(-1);
1388 dbg_version_and_cmd(argc, argv);
1391 r = run_reencrypt(action_argv[0]);
1393 poptFreeContext(popt_context);
1395 return translate_errno(r);