7eaf4cff284a6563be499231d7b4adac57fd9702
[platform/upstream/cryptsetup.git] / src / crypt_reencrypt.c
1 /*
2  * crypt_reencrypt - crypt utility for offline reencryption
3  *
4  * Copyright (C) 2012 Milan Broz All rights reserved.
5  *
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.
9  *
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.
14  *
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.
18  */
19
20 #define _LARGEFILE64_SOURCE
21 #define _FILE_OFFSET_BITS 64
22 #define SECTOR_SIZE 512
23
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28 #include <stdarg.h>
29 #include <inttypes.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <sys/time.h>
35 #include <linux/fs.h>
36 #include <fcntl.h>
37 #include <limits.h>
38 #include <signal.h>
39 #include <libcryptsetup.h>
40 #include <popt.h>
41
42 #include "cryptsetup.h"
43
44 static int opt_verbose = 0;
45 static int opt_debug = 0;
46 static const char *opt_cipher = NULL;
47 static const char *opt_hash = NULL;
48 static const char *opt_key_file = NULL;
49 static long opt_keyfile_size = 0;
50 static long opt_keyfile_offset = 0;
51 static int opt_iteration_time = 1000;
52 static int opt_batch_mode = 0;
53 static int opt_version_mode = 0;
54 static int opt_random = 0;
55 static int opt_urandom = 0;
56 static int opt_bsize = 4;
57 static int opt_directio = 0;
58 static int opt_write_log = 0;
59 static int opt_tries = 3;
60 static int opt_key_slot = CRYPT_ANY_SLOT;
61
62 static const char **action_argv;
63
64 static volatile int quit = 0;
65
66 #define MAX_SLOT 8
67 struct {
68         char *device;
69         char *device_uuid;
70         uint64_t device_size;
71         uint64_t device_offset;
72         uint64_t device_shift;
73
74         int in_progress:1;
75         enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
76
77         char header_file_org[PATH_MAX];
78         char header_file_new[PATH_MAX];
79         char log_file[PATH_MAX];
80
81         char crypt_path_org[PATH_MAX];
82         char crypt_path_new[PATH_MAX];
83         int log_fd;
84
85         struct {
86                 char *password;
87                 size_t passwordLen;
88         } p[MAX_SLOT];
89         int keyslot;
90
91         struct timeval start_time, end_time;
92         uint64_t restart_bytes;
93 } rnc;
94
95 char MAGIC[]   = {'L','U','K','S', 0xba, 0xbe};
96 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
97 int  MAGIC_L = 6;
98
99 typedef enum {
100         MAKE_UNUSABLE,
101         MAKE_USABLE,
102         CHECK_UNUSABLE
103 } header_magic;
104
105 __attribute__((format(printf, 5, 6)))
106 static void clogger(struct crypt_device *cd, int level, const char *file,
107                    int line, const char *format, ...)
108 {
109         va_list argp;
110         char *target = NULL;
111
112         va_start(argp, format);
113
114         if (vasprintf(&target, format, argp) > 0) {
115                 if (level >= 0) {
116                         crypt_log(cd, level, target);
117                 } else if (opt_debug)
118                         printf("# %s\n", target);
119         }
120
121         va_end(argp);
122         free(target);
123 }
124
125 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
126 {
127         switch(level) {
128
129         case CRYPT_LOG_NORMAL:
130                 fputs(msg, stdout);
131                 break;
132         case CRYPT_LOG_VERBOSE:
133                 if (opt_verbose)
134                         fputs(msg, stdout);
135                 break;
136         case CRYPT_LOG_ERROR:
137                 fputs(msg, stderr);
138                 break;
139         case CRYPT_LOG_DEBUG:
140                 if (opt_debug)
141                         printf("# %s\n", msg);
142                 break;
143         default:
144                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
145                 break;
146         }
147 }
148
149 static void _quiet_log(int level, const char *msg, void *usrptr)
150 {
151         if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
152                 level = CRYPT_LOG_VERBOSE;
153         _log(level, msg, usrptr);
154 }
155
156 static void int_handler(int sig __attribute__((__unused__)))
157 {
158         quit++;
159 }
160
161 static void set_int_block(int block)
162 {
163         sigset_t signals_open;
164
165         sigemptyset(&signals_open);
166         sigaddset(&signals_open, SIGINT);
167         sigaddset(&signals_open, SIGTERM);
168         sigprocmask(block ? SIG_SETMASK : SIG_UNBLOCK, &signals_open, NULL);
169 }
170
171 static void set_int_handler(void)
172 {
173         struct sigaction sigaction_open;
174
175         memset(&sigaction_open, 0, sizeof(struct sigaction));
176         sigaction_open.sa_handler = int_handler;
177         sigaction(SIGINT, &sigaction_open, 0);
178         sigaction(SIGTERM, &sigaction_open, 0);
179         set_int_block(0);
180 }
181
182 /* The difference in seconds between two times in "timeval" format. */
183 double time_diff(struct timeval start, struct timeval end)
184 {
185         return (end.tv_sec - start.tv_sec)
186                 + (end.tv_usec - start.tv_usec) / 1E6;
187 }
188
189 static int alignment(int fd)
190 {
191         int alignment;
192
193         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
194         if (alignment < 0)
195                 alignment = 4096;
196         return alignment;
197 }
198
199 static int device_magic(header_magic set_magic)
200 {
201         char *buf = NULL;
202         int r, devfd;
203         ssize_t s;
204
205         devfd = open(rnc.device, O_RDWR | O_DIRECT);
206         if (devfd == -1)
207                 return errno == EBUSY ? -EBUSY : -EINVAL;
208
209         if (posix_memalign((void *)&buf, alignment(devfd), SECTOR_SIZE)) {
210                 log_err(_("Allocation of aligned memory failed.\n"));
211                 r = -ENOMEM;
212                 goto out;
213         }
214
215         s = read(devfd, buf, SECTOR_SIZE);
216         if (s < 0 || s != SECTOR_SIZE) {
217                 log_err(_("Cannot read device %s.\n"), rnc.device);
218                 close(devfd);
219                 return -EIO;
220         }
221
222         if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L)) {
223                 log_verbose(_("Marking LUKS device %s unusable.\n"), rnc.device);
224                 memcpy(buf, NOMAGIC, MAGIC_L);
225                 r = 0;
226
227         } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L)) {
228                 log_verbose(_("Marking LUKS device %s usable.\n"), rnc.device);
229                 memcpy(buf, MAGIC, MAGIC_L);
230                 r = 0;
231         } else if (set_magic == CHECK_UNUSABLE) {
232                 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
233                 if (!r)
234                         rnc.device_uuid = strndup(&buf[0xa8], 40);
235                 goto out;
236         } else
237                 r = -EINVAL;
238
239         if (!r) {
240                 if (lseek(devfd, 0, SEEK_SET) == -1)
241                         goto out;
242                 s = write(devfd, buf, SECTOR_SIZE);
243                 if (s < 0 || s != SECTOR_SIZE) {
244                         log_err(_("Cannot write device %s.\n"), rnc.device);
245                         r = -EIO;
246                 }
247         } else
248                 log_dbg("LUKS signature check failed for %s.", rnc.device);
249 out:
250         if (buf)
251                 memset(buf, 0, SECTOR_SIZE);
252         free(buf);
253         close(devfd);
254         return r;
255 }
256
257 static int create_empty_header(const char *new_file, const char *old_file)
258 {
259         struct stat st;
260         size_t size;
261         int fd, r = 0;
262         char *buf;
263
264         if (stat(old_file, &st) == -1 || (st.st_mode & S_IFMT) != S_IFREG)
265                 return -EINVAL;
266         size = st.st_size;
267
268         log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
269
270         if (!(buf = malloc(size)))
271                 return -ENOMEM;
272         memset(buf, 0, size);
273
274         fd = creat(new_file, S_IRUSR|S_IWUSR);
275         if(fd == -1) {
276                 free(buf);
277                 return -EINVAL;
278         }
279
280         if (write(fd, buf, size) < size)
281                 r = -EIO;
282
283         close(fd);
284         free(buf);
285         return r;
286 }
287
288 static int write_log(void)
289 {
290         static char buf[SECTOR_SIZE];
291         ssize_t r;
292
293         memset(buf, 0, SECTOR_SIZE);
294         snprintf(buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
295                 "version = %d\nUUID = %s\ndirection = %d\n"
296                 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
297                 1, rnc.device_uuid, rnc.reencrypt_direction,
298                 rnc.device_offset, rnc.device_shift);
299
300         lseek(rnc.log_fd, 0, SEEK_SET);
301         r = write(rnc.log_fd, buf, SECTOR_SIZE);
302         if (r < 0 || r != SECTOR_SIZE) {
303                 log_err(_("Cannot write reencryption log file.\n"));
304                 return -EIO;
305         }
306
307         return 0;
308 }
309
310 static int parse_line_log(const char *line)
311 {
312         uint64_t u64;
313         int i;
314         char s[64];
315
316         /* whole line is comment */
317         if (*line == '#')
318                 return 0;
319
320         if (sscanf(line, "version = %d", &i) == 1) {
321                 if (i != 1) {
322                         log_dbg("Log: Unexpected version = %i", i);
323                         return -EINVAL;
324                 }
325         } else if (sscanf(line, "UUID = %40s", s) == 1) {
326                 if (!rnc.device_uuid || strcmp(rnc.device_uuid, s)) {
327                         log_dbg("Log: Unexpected UUID %s", s);
328                         return -EINVAL;
329                 }
330         } else if (sscanf(line, "direction = %d", &i) == 1) {
331                 log_dbg("Log: direction = %i", i);
332                 rnc.reencrypt_direction = i;
333         } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
334                 log_dbg("Log: offset = %" PRIu64, u64);
335                 rnc.device_offset = u64;
336         } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
337                 log_dbg("Log: shift = %" PRIu64, u64);
338                 rnc.device_shift = u64;
339         } else
340                 return -EINVAL;
341
342         return 0;
343 }
344
345 static int parse_log(void)
346 {
347         static char buf[SECTOR_SIZE];
348         char *start, *end;
349         ssize_t s;
350
351         s = read(rnc.log_fd, buf, SECTOR_SIZE);
352         if (s == -1) {
353                 log_err(_("Cannot read reencryption log file.\n"));
354                 return -EIO;
355         }
356
357         buf[SECTOR_SIZE - 1] = '\0';
358         start = buf;
359         do {
360                 end = strchr(start, '\n');
361                 if (end) {
362                         *end++ = '\0';
363                         if (parse_line_log(start)) {
364                                 log_err("Wrong log format.\n");
365                                 return -EINVAL;
366                         }
367                 }
368
369                 start = end;
370         } while (start);
371
372         return 0;
373 }
374
375 static int open_log(void)
376 {
377         int flags;
378         struct stat st;
379
380         if(stat(rnc.log_file, &st) < 0) {
381                 log_dbg("Creating LUKS reencryption log file %s.", rnc.log_file);
382                 flags = opt_directio ? O_RDWR|O_CREAT|O_DIRECT : O_RDWR|O_CREAT;
383                 rnc.log_fd = open(rnc.log_file, flags, S_IRUSR|S_IWUSR);
384                 if (rnc.log_fd == -1)
385                         return -EINVAL;
386                 if (write_log() < 0)
387                         return -EIO;
388         } else {
389                 log_dbg("Log file %s exists, restarting.", rnc.log_file);
390                 flags = opt_directio ? O_RDWR|O_DIRECT : O_RDWR;
391                 rnc.log_fd = open(rnc.log_file, flags);
392                 if (rnc.log_fd == -1)
393                         return -EINVAL;
394                 rnc.in_progress = 1;
395         }
396
397         /* Be sure it is correct format */
398         return parse_log();
399 }
400
401 static void close_log(void)
402 {
403         log_dbg("Closing LUKS reencryption log file %s.", rnc.log_file);
404         if (rnc.log_fd != -1)
405                 close(rnc.log_fd);
406 }
407
408 static int activate_luks_headers(void)
409 {
410         struct crypt_device *cd = NULL, *cd_new = NULL;
411         int r;
412
413         log_dbg("Activating LUKS devices from headers.");
414
415         if ((r = crypt_init(&cd, rnc.header_file_org)) ||
416             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
417             (r = crypt_set_data_device(cd, rnc.device)))
418                 goto out;
419
420         if ((r = crypt_activate_by_passphrase(cd, rnc.header_file_org,
421                 opt_key_slot, rnc.p[rnc.keyslot].password, rnc.p[rnc.keyslot].passwordLen,
422                 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
423                 goto out;
424
425         if ((r = crypt_init(&cd_new, rnc.header_file_new)) ||
426             (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)) ||
427             (r = crypt_set_data_device(cd_new, rnc.device)))
428                 goto out;
429
430         if ((r = crypt_activate_by_passphrase(cd_new, rnc.header_file_new,
431                 opt_key_slot, rnc.p[rnc.keyslot].password, rnc.p[rnc.keyslot].passwordLen,
432                 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
433                 goto out;
434         r = 0;
435 out:
436         crypt_free(cd);
437         crypt_free(cd_new);
438         if (r < 0)
439                 log_err(_("Activation of temporary devices failed.\n"));
440         return r;
441 }
442
443 static int backup_luks_headers(void)
444 {
445         struct crypt_device *cd = NULL, *cd_new = NULL;
446         struct crypt_params_luks1 params = {0};
447         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
448         int i, r;
449
450         log_dbg("Creating LUKS header backup for device %s.", rnc.device);
451
452         if ((r = crypt_init(&cd, rnc.device)) ||
453             (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
454                 goto out;
455
456         crypt_set_confirm_callback(cd, NULL, NULL);
457         if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rnc.header_file_org)))
458                 goto out;
459         log_verbose(_("LUKS header backup of device %s created.\n"), rnc.device);
460
461         if ((r = create_empty_header(rnc.header_file_new, rnc.header_file_org)))
462                 goto out;
463
464         params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
465         params.data_alignment = crypt_get_data_offset(cd);
466         params.data_device = rnc.device;
467
468         if ((r = crypt_init(&cd_new, rnc.header_file_new)))
469                 goto out;
470
471         if (opt_random)
472                 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
473         else if (opt_urandom)
474                 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
475
476         if (opt_iteration_time)
477                 crypt_set_iteration_time(cd_new, opt_iteration_time);
478
479         if (opt_cipher) {
480                 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
481                 if (r < 0) {
482                         log_err(_("No known cipher specification pattern detected.\n"));
483                         goto out;
484                 }
485         }
486
487         if ((r = crypt_format(cd_new, CRYPT_LUKS1,
488                         opt_cipher ? cipher : crypt_get_cipher(cd),
489                         opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
490                         crypt_get_uuid(cd),
491                         NULL, crypt_get_volume_key_size(cd), &params)))
492                 goto out;
493         log_verbose(_("New LUKS header for device %s created.\n"), rnc.device);
494
495         for (i = 0; i < MAX_SLOT; i++) {
496                 if (!rnc.p[i].password)
497                         continue;
498                 if ((r = crypt_keyslot_add_by_volume_key(cd_new, i,
499                         NULL, 0, rnc.p[i].password, rnc.p[i].passwordLen)) < 0)
500                         goto out;
501                 log_verbose(_("Activated keyslot %i.\n"), r);
502                 r = 0;
503         }
504 out:
505         crypt_free(cd);
506         crypt_free(cd_new);
507         if (r)
508                 log_err(_("Creation of LUKS backup headers failed.\n"));
509         return r;
510 }
511
512 static void remove_headers(void)
513 {
514         struct crypt_device *cd = NULL;
515
516         log_dbg("Removing headers.");
517
518         if (crypt_init(&cd, NULL))
519                 return;
520         crypt_set_log_callback(cd, _quiet_log, NULL);
521         (void)crypt_deactivate(cd, rnc.header_file_org);
522         (void)crypt_deactivate(cd, rnc.header_file_new);
523         crypt_free(cd);
524 }
525
526 static int restore_luks_header(const char *backup)
527 {
528         struct crypt_device *cd = NULL;
529         int r;
530
531         log_dbg("Restoring header for %s from %s.", rnc.device, backup);
532
533         r = crypt_init(&cd, rnc.device);
534         if (r == 0) {
535                 crypt_set_confirm_callback(cd, NULL, NULL);
536                 r = crypt_header_restore(cd, CRYPT_LUKS1, backup);
537         }
538
539         crypt_free(cd);
540         if (r)
541                 log_err(_("Cannot restore LUKS header on device %s.\n"), rnc.device);
542         else
543                 log_verbose(_("LUKS header on device %s restored.\n"), rnc.device);
544         return r;
545 }
546
547 void print_progress(uint64_t bytes, int final)
548 {
549         uint64_t mbytes = (bytes - rnc.restart_bytes) / 1024 / 1024;
550         struct timeval now_time;
551         double tdiff;
552
553         gettimeofday(&now_time, NULL);
554         if (!final && time_diff(rnc.end_time, now_time) < 0.5)
555                 return;
556
557         rnc.end_time = now_time;
558
559         if (opt_batch_mode)
560                 return;
561
562         tdiff = time_diff(rnc.start_time, rnc.end_time);
563         if (!tdiff)
564                 return;
565
566         /* vt100 code clear line */
567         log_err("\33[2K\r");
568         log_err(_("Progress: %5.1f%%, time elapsed %3.1f seconds, "
569                 "%4llu MiB written, speed %5.1f MiB/s%s"),
570                 (double)bytes / rnc.device_size * 100,
571                 time_diff(rnc.start_time, rnc.end_time),
572                 (unsigned long long)mbytes, (double)(mbytes) / tdiff,
573                 final ? "\n" :"");
574 }
575
576 static int copy_data_forward(int fd_old, int fd_new, size_t block_size, void *buf, uint64_t *bytes)
577 {
578         ssize_t s1, s2;
579
580         log_dbg("Reencrypting in forward direction.");
581
582         if (lseek64(fd_old, rnc.device_offset, SEEK_SET) < 0 ||
583             lseek64(fd_new, rnc.device_offset, SEEK_SET) < 0) {
584                 log_err(_("Cannot seek to device offset.\n"));
585                 return -EIO;
586         }
587
588         rnc.restart_bytes = *bytes = rnc.device_offset;
589
590         if (write_log() < 0)
591                 return -EIO;
592
593         while (!quit && rnc.device_offset < rnc.device_size) {
594                 s1 = read(fd_old, buf, block_size);
595                 if (s1 < 0 || (s1 != block_size && (rnc.device_offset + s1) != rnc.device_size)) {
596                         log_dbg("Read error, expecting %d, got %d.", (int)block_size, (int)s1);
597                         return -EIO;
598                 }
599                 s2 = write(fd_new, buf, s1);
600                 if (s2 < 0) {
601                         log_dbg("Write error, expecting %d, got %d.", (int)block_size, (int)s2);
602                         return -EIO;
603                 }
604                 rnc.device_offset += s1;
605                 if (opt_write_log && write_log() < 0)
606                         return -EIO;
607
608                 *bytes += (uint64_t)s2;
609                 print_progress(*bytes, 0);
610         }
611
612         return quit ? -EAGAIN : 0;
613 }
614
615 static int copy_data_backward(int fd_old, int fd_new, size_t block_size, void *buf, uint64_t *bytes)
616 {
617         ssize_t s1, s2, working_block;
618         off64_t working_offset;
619
620         log_dbg("Reencrypting in backward direction.");
621
622         if (!rnc.in_progress) {
623                 rnc.device_offset = rnc.device_size;
624                 rnc.restart_bytes = 0;
625                 *bytes = 0;
626         } else {
627                 rnc.restart_bytes = rnc.device_size - rnc.device_offset;
628                 *bytes = rnc.restart_bytes;
629         }
630
631         if (write_log() < 0)
632                 return -EIO;
633
634         while (!quit && rnc.device_offset) {
635                 if (rnc.device_offset < block_size) {
636                         working_offset = 0;
637                         working_block = rnc.device_offset;
638                 } else {
639                         working_offset = rnc.device_offset - block_size;
640                         working_block = block_size;
641                 }
642
643                 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
644                     lseek64(fd_new, working_offset, SEEK_SET) < 0) {
645                         log_err(_("Cannot seek to device offset.\n"));
646                         return -EIO;
647                 }
648
649                 s1 = read(fd_old, buf, working_block);
650                 if (s1 < 0 || (s1 != working_block)) {
651                         log_dbg("Read error, expecting %d, got %d.", (int)block_size, (int)s1);
652                         return -EIO;
653                 }
654                 s2 = write(fd_new, buf, working_block);
655                 if (s2 < 0) {
656                         log_dbg("Write error, expecting %d, got %d.", (int)block_size, (int)s2);
657                         return -EIO;
658                 }
659                 rnc.device_offset -= s1;
660                 if (opt_write_log && write_log() < 0)
661                         return -EIO;
662
663                 *bytes += (uint64_t)s2;
664                 print_progress(*bytes, 0);
665         }
666
667         return quit ? -EAGAIN : 0;
668 }
669
670 static int copy_data(void)
671 {
672         size_t block_size = opt_bsize * 1024 * 1024;
673         int fd_old = -1, fd_new = -1;
674         int r = -EINVAL;
675         void *buf = NULL;
676         uint64_t bytes = 0;
677
678         log_dbg("Data copy preparation.");
679
680         fd_old = open(rnc.crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
681         if (fd_old == -1) {
682                 log_err(_("Cannot open temporary LUKS header file.\n"));
683                 goto out;
684         }
685
686         fd_new = open(rnc.crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
687         if (fd_new == -1) {
688                 log_err(_("Cannot open temporary LUKS header file.\n"));
689                 goto out;
690         }
691
692         /* Check size */
693         if (ioctl(fd_old, BLKGETSIZE64, &rnc.device_size) < 0) {
694                 log_err(_("Cannot get device size.\n"));
695                 goto out;
696         }
697
698         if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
699                 log_err(_("Allocation of aligned memory failed.\n"));
700                 r = -ENOMEM;
701                 goto out;
702         }
703
704         set_int_handler();
705         gettimeofday(&rnc.start_time, NULL);
706
707         if (rnc.reencrypt_direction == FORWARD)
708                 r = copy_data_forward(fd_old, fd_new, block_size, buf, &bytes);
709         else
710                 r = copy_data_backward(fd_old, fd_new, block_size, buf, &bytes);
711
712         set_int_block(1);
713         print_progress(bytes, 1);
714
715         if (r == -EAGAIN)
716                  log_err(_("Interrupted by a signal.\n"));
717         else if (r < 0)
718                 log_err(_("IO error during reencryption.\n"));
719
720         (void)write_log();
721 out:
722         if (fd_old != -1)
723                 close(fd_old);
724         if (fd_new != -1)
725                 close(fd_new);
726         free(buf);
727         return r;
728 }
729
730 static int initialize_uuid(void)
731 {
732         struct crypt_device *cd = NULL;
733         int r;
734
735         log_dbg("Initialising UUID.");
736
737         /* Try to load LUKS from device */
738         if ((r = crypt_init(&cd, rnc.device)))
739                 return r;
740         crypt_set_log_callback(cd, _quiet_log, NULL);
741         r = crypt_load(cd, CRYPT_LUKS1, NULL);
742         if (!r)
743                 rnc.device_uuid = strdup(crypt_get_uuid(cd));
744         else
745                 /* Reencryption already in progress - magic header? */
746                 r = device_magic(CHECK_UNUSABLE);
747
748         crypt_free(cd);
749         return r;
750 }
751
752 static int init_passphrase1(struct crypt_device *cd, const char *msg, int slot_check)
753 {
754         int r = -EINVAL, slot, retry_count;
755
756         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
757
758         retry_count = opt_tries ?: 1;
759         while (retry_count--) {
760                 r = crypt_get_key(msg, &rnc.p[slot].password,
761                         &rnc.p[slot].passwordLen,
762                         0, 0, NULL /*opt_key_file*/,
763                         0, 0, cd);
764                 if (r < 0)
765                         return r;
766
767                 r = crypt_activate_by_passphrase(cd, NULL, slot_check,
768                         rnc.p[slot].password, rnc.p[slot].passwordLen, 0);
769
770                 if (r < 0) {
771                         crypt_safe_free(rnc.p[slot].password);
772                         rnc.p[slot].password = NULL;
773                         rnc.p[slot].passwordLen = 0;
774                 }
775                 if (r < 0 && r != -EPERM)
776                         return r;
777                 if (r >= 0) {
778                         rnc.keyslot = slot;
779                         break;
780                 }
781                 log_err(_("No key available with this passphrase.\n"));
782         }
783         return r;
784 }
785
786 static int init_keyfile(struct crypt_device *cd, int slot_check)
787 {
788         int r, slot;
789
790         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
791         r = crypt_get_key(NULL, &rnc.p[slot].password, &rnc.p[slot].passwordLen,
792                 opt_keyfile_offset, opt_keyfile_size, opt_key_file, 0, 0, cd);
793         if (r < 0)
794                 return r;
795
796         r = crypt_activate_by_passphrase(cd, NULL, slot_check,
797                 rnc.p[slot].password, rnc.p[slot].passwordLen, 0);
798
799         /*
800          * Allow keyslot only if it is last slot or if user explicitly
801          * specify whch slot to use (IOW others will be disabled).
802          */
803         if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
804             crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
805                 log_err(_("Key file can be used only with --key-slot or with "
806                           "exactly one key slot active.\n"));
807                 r = -EINVAL;
808         }
809
810         if (r < 0) {
811                 crypt_safe_free(rnc.p[slot].password);
812                 rnc.p[slot].password = NULL;
813                 rnc.p[slot].passwordLen = 0;
814                 if (r == -EPERM)
815                         log_err(_("No key available with this passphrase.\n"));
816                 return r;
817         } else
818                 rnc.keyslot = slot;
819
820         return r;
821 }
822
823 static int initialize_passphrase(const char *device)
824 {
825         struct crypt_device *cd = NULL;
826         crypt_keyslot_info ki;
827         char msg[256];
828         int i, r;
829
830         log_dbg("Passhrases initialization.");
831
832         if ((r = crypt_init(&cd, device)) ||
833             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
834             (r = crypt_set_data_device(cd, rnc.device))) {
835                 crypt_free(cd);
836                 return r;
837         }
838
839         if (opt_key_file) {
840                 r = init_keyfile(cd, opt_key_slot);
841         } else if (rnc.in_progress) {
842                 r = init_passphrase1(cd, _("Enter any LUKS passphrase: "), CRYPT_ANY_SLOT);
843         } else for (i = 0; i < MAX_SLOT; i++) {
844                 ki = crypt_keyslot_status(cd, i);
845                 if (ki != CRYPT_SLOT_ACTIVE && ki != CRYPT_SLOT_ACTIVE_LAST)
846                         continue;
847
848                 snprintf(msg, sizeof(msg), _("Enter LUKS passphrase for key slot %u): "), i);
849                 r = init_passphrase1(cd, msg, i);
850                 if (r < 0)
851                         break;
852         }
853
854         crypt_free(cd);
855         return r > 0 ? 0 : r;
856 }
857
858 static int initialize_context(const char *device)
859 {
860         log_dbg("Initialising reencryption context.");
861
862         rnc.log_fd =-1;
863
864         if (!(rnc.device = strndup(device, PATH_MAX)))
865                 return -ENOMEM;
866
867         if (initialize_uuid()) {
868                 log_err(_("Device %s is not a valid LUKS device.\n"), device);
869                 return -EINVAL;
870         }
871
872         /* Prepare device names */
873         if (snprintf(rnc.log_file, PATH_MAX,
874                      "LUKS-%s.log", rnc.device_uuid) < 0)
875                 return -ENOMEM;
876         if (snprintf(rnc.header_file_org, PATH_MAX,
877                      "LUKS-%s.org", rnc.device_uuid) < 0)
878                 return -ENOMEM;
879         if (snprintf(rnc.header_file_new, PATH_MAX,
880                      "LUKS-%s.new", rnc.device_uuid) < 0)
881                 return -ENOMEM;
882
883         /* Paths to encrypted devices */
884         if (snprintf(rnc.crypt_path_org, PATH_MAX,
885                      "%s/%s", crypt_get_dir(), rnc.header_file_org) < 0)
886                 return -ENOMEM;
887         if (snprintf(rnc.crypt_path_new, PATH_MAX,
888                      "%s/%s", crypt_get_dir(), rnc.header_file_new) < 0)
889                 return -ENOMEM;
890
891         remove_headers();
892
893         if (open_log() < 0) {
894                 log_err(_("Cannot open reencryption log file.\n"));
895                 return -EINVAL;
896         }
897
898         if (!rnc.in_progress) {
899                 if (1 /*opt_new */)
900                         rnc.reencrypt_direction = FORWARD;
901                 else {
902                         rnc.reencrypt_direction = BACKWARD;
903                         rnc.device_offset = (uint64_t)~0;
904                 }
905         }
906
907         return 0;
908 }
909
910 static void destroy_context(void)
911 {
912         int i;
913
914         log_dbg("Destroying reencryption context.");
915
916         close_log();
917         remove_headers();
918
919         if ((rnc.reencrypt_direction == FORWARD &&
920              rnc.device_offset == rnc.device_size) ||
921              rnc.device_offset == 0) {
922                 unlink(rnc.log_file);
923                 unlink(rnc.header_file_org);
924                 unlink(rnc.header_file_new);
925         }
926
927         for (i = 0; i < MAX_SLOT; i++)
928                 crypt_safe_free(rnc.p[i].password);
929
930         free(rnc.device);
931         free(rnc.device_uuid);
932 }
933
934 int run_reencrypt(const char *device)
935 {
936         int r = -EINVAL;
937         if (initialize_context(device))
938                 goto out;
939
940         log_dbg("Running reencryption.");
941
942         if (!rnc.in_progress) {
943                 if ((r = initialize_passphrase(rnc.device)) ||
944                     (r = backup_luks_headers()) ||
945                     (r = device_magic(MAKE_UNUSABLE)))
946                         goto out;
947         } else {
948                 if ((r = initialize_passphrase(rnc.header_file_new)))
949                         goto out;
950         }
951
952         if ((r = activate_luks_headers()))
953                 goto out;
954
955         if ((r = copy_data()))
956                 goto out;
957
958         r = restore_luks_header(rnc.header_file_new);
959 out:
960         destroy_context();
961         return r;
962 }
963
964 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
965                                              int exitcode, const char *error,
966                                              const char *more)
967 {
968         poptPrintUsage(popt_context, stderr, 0);
969         if (error)
970                 log_err("%s: %s\n", more, error);
971         poptFreeContext(popt_context);
972         exit(exitcode);
973 }
974
975 static void help(poptContext popt_context,
976                  enum poptCallbackReason reason __attribute__((unused)),
977                  struct poptOption *key,
978                  const char *arg __attribute__((unused)),
979                  void *data __attribute__((unused)))
980 {
981         usage(popt_context, EXIT_SUCCESS, NULL, NULL);
982 }
983
984 static void _dbg_version_and_cmd(int argc, const char **argv)
985 {
986         int i;
987
988         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
989         for (i = 0; i < argc; i++) {
990                 if (i)
991                         log_std(" ");
992                 log_std("%s", argv[i]);
993         }
994         log_std("\"\n");
995 }
996
997 int main(int argc, const char **argv)
998 {
999         static struct poptOption popt_help_options[] = {
1000                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1001                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1002                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1003                 POPT_TABLEEND
1004         };
1005         static struct poptOption popt_options[] = {
1006                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1007                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
1008                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1009                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1010                 { "block-size",        'B',  POPT_ARG_INT, &opt_bsize,                  0, N_("Reencryption block size"), N_("MiB") },
1011                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1012                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1013                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
1014                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1015                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1016                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1017                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1018                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1019                 { "use-directio",      '\0', POPT_ARG_NONE, &opt_directio,              0, N_("Use direct-io when accesing devices."), NULL },
1020                 { "write-log",         '\0', POPT_ARG_NONE, &opt_write_log,             0, N_("Update log file after every block."), NULL },
1021                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Use only this slot (others will be disabled)."), NULL },
1022                 { "keyfile-offset",   '\0',  POPT_ARG_LONG, &opt_keyfile_offset,        0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1023                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1024                 POPT_TABLEEND
1025         };
1026         poptContext popt_context;
1027         int r;
1028
1029         crypt_set_log_callback(NULL, _log, NULL);
1030
1031         set_int_block(1);
1032
1033         setlocale(LC_ALL, "");
1034         bindtextdomain(PACKAGE, LOCALEDIR);
1035         textdomain(PACKAGE);
1036
1037         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1038         poptSetOtherOptionHelp(popt_context,
1039                                N_("[OPTION...] <device>]"));
1040
1041         while((r = poptGetNextOpt(popt_context)) > 0) {
1042                 if (r < 0)
1043                         break;
1044         }
1045
1046         if (r < -1)
1047                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1048                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1049         if (opt_version_mode) {
1050                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1051                 poptFreeContext(popt_context);
1052                 exit(EXIT_SUCCESS);
1053         }
1054
1055         if (!opt_batch_mode)
1056                 log_err(_("WARNING: this is experimental code, it can completely break your data.\n"));
1057
1058         action_argv = poptGetArgs(popt_context);
1059         if(!action_argv)
1060                 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1061                       poptGetInvocationName(popt_context));
1062
1063         if (opt_random && opt_urandom)
1064                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1065                       poptGetInvocationName(popt_context));
1066
1067         if (opt_bsize < 1 || opt_bsize > 64)
1068                 usage(popt_context, EXIT_FAILURE,
1069                       _("Only values between 1MiB and 64 MiB allowed for reencryption block size."),
1070                       poptGetInvocationName(popt_context));
1071
1072         if (opt_debug) {
1073                 opt_verbose = 1;
1074                 crypt_set_debug_level(-1);
1075                 _dbg_version_and_cmd(argc, argv);
1076         }
1077
1078         r = run_reencrypt(action_argv[0]);
1079
1080         poptFreeContext(popt_context);
1081
1082         /* Translate exit code to simple codes */
1083         switch (r) {
1084         case 0:         r = EXIT_SUCCESS; break;
1085         case -EEXIST:
1086         case -EBUSY:    r = 5; break;
1087         case -ENOTBLK:
1088         case -ENODEV:   r = 4; break;
1089         case -ENOMEM:   r = 3; break;
1090         case -EPERM:    r = 2; break;
1091         case -EAGAIN:
1092         case -EINVAL:
1093         case -ENOENT:
1094         case -ENOSYS:
1095         default:        r = EXIT_FAILURE;
1096         }
1097         return r;
1098 }