Handle interrupts & restart.
[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 /* The code works as follows:
21  *  - create backup (detached) headers fo old and new device
22  *  - mark original device unusable
23  *  - maps two devices, one with old header one with new onto
24  *    the _same_ underlying device
25  *  - with direct-io reads old device and copy to new device in defined steps
26  *  - keps simple off in file (allows restart)
27  *  - there is several windows when corruption can happen
28  *
29  * null target
30  * dmsetup create x --table "0 $(blockdev --getsz DEV) crypt cipher_null-ecb-null - 0 DEV 0"
31  */
32 #define _LARGEFILE64_SOURCE
33 #define _FILE_OFFSET_BITS 64
34
35 #include <string.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <stdint.h>
39 #include <stdarg.h>
40 #include <inttypes.h>
41 #include <errno.h>
42 #include <unistd.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/time.h>
46 #include <linux/fs.h>
47 #include <fcntl.h>
48 #include <limits.h>
49 #include <signal.h>
50 #include <libcryptsetup.h>
51 #include <popt.h>
52
53 #include "cryptsetup.h"
54
55 static int opt_verbose = 0;
56 static int opt_debug = 0;
57 static const char *opt_cipher = NULL;
58 static const char *opt_hash = NULL;
59 static const char *opt_key_file = NULL;
60 static int opt_iteration_time = 1000;
61 static int opt_batch_mode = 0;
62 static int opt_version_mode = 0;
63 static int opt_random = 0;
64 static int opt_urandom = 0;
65 static int opt_bsize = 4;
66 static int opt_new = 0;
67 static int opt_directio = 0;
68 static int opt_write_log = 0;
69 static const char *opt_new_file = NULL;
70
71 static const char **action_argv;
72
73 static volatile int quit = 0;
74
75 struct {
76         char *device;
77         char *device_uuid;
78         uint64_t device_size;
79         uint64_t device_offset;
80         uint64_t device_shift;
81
82         int in_progress:1;
83         enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
84
85         char header_file_org[PATH_MAX];
86         char header_file_new[PATH_MAX];
87         char log_file[PATH_MAX];
88
89         char crypt_path_org[PATH_MAX];
90         char crypt_path_new[PATH_MAX];
91         int log_fd;
92
93         char *password;
94         size_t passwordLen;
95         int keyslot;
96
97         struct timeval start_time, end_time;
98 } rnc;
99
100 char MAGIC[]   = {'L','U','K','S', 0xba, 0xbe};
101 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
102 int  MAGIC_L = 6;
103
104 typedef enum {
105         MAKE_UNUSABLE,
106         MAKE_USABLE,
107         CHECK_UNUSABLE
108 } header_magic;
109
110 __attribute__((format(printf, 5, 6)))
111 static void clogger(struct crypt_device *cd, int level, const char *file,
112                    int line, const char *format, ...)
113 {
114         va_list argp;
115         char *target = NULL;
116
117         va_start(argp, format);
118
119         if (vasprintf(&target, format, argp) > 0) {
120                 if (level >= 0) {
121                         crypt_log(cd, level, target);
122                 } else if (opt_debug)
123                         printf("# %s\n", target);
124         }
125
126         va_end(argp);
127         free(target);
128 }
129
130 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
131 {
132         switch(level) {
133
134         case CRYPT_LOG_NORMAL:
135                 fputs(msg, stdout);
136                 break;
137         case CRYPT_LOG_VERBOSE:
138                 if (opt_verbose)
139                         fputs(msg, stdout);
140                 break;
141         case CRYPT_LOG_ERROR:
142                 fputs(msg, stderr);
143                 break;
144         case CRYPT_LOG_DEBUG:
145                 if (opt_debug)
146                         printf("# %s\n", msg);
147                 break;
148         default:
149                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
150                 break;
151         }
152 }
153
154 static void _quiet_log(int level, const char *msg, void *usrptr)
155 {
156         if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
157                 level = CRYPT_LOG_VERBOSE;
158         _log(level, msg, usrptr);
159 }
160
161 static void int_handler(int sig __attribute__((__unused__)))
162 {
163         quit++;
164 }
165
166 static void set_int_block(int block)
167 {
168         sigset_t signals_open;
169
170         sigemptyset(&signals_open);
171         sigaddset(&signals_open, SIGINT);
172         sigaddset(&signals_open, SIGTERM);
173         sigprocmask(block ? SIG_SETMASK : SIG_UNBLOCK, &signals_open, NULL);
174 }
175
176 static void set_int_handler(void)
177 {
178         struct sigaction sigaction_open;
179
180         memset(&sigaction_open, 0, sizeof(struct sigaction));
181         sigaction_open.sa_handler = int_handler;
182         sigaction(SIGINT, &sigaction_open, 0);
183         sigaction(SIGTERM, &sigaction_open, 0);
184         set_int_block(0);
185 }
186
187 /* The difference in seconds between two times in "timeval" format. */
188 double time_diff(struct timeval start, struct timeval end)
189 {
190         return (end.tv_sec - start.tv_sec)
191                 + (end.tv_usec - start.tv_usec) / 1E6;
192 }
193
194 static int alignment(int fd)
195 {
196         int alignment;
197
198         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
199         if (alignment < 0)
200                 alignment = 4096;
201         return alignment;
202 }
203
204 static int device_magic(header_magic set_magic)
205 {
206         char *buf = NULL;
207         size_t block_size = 512;
208         int r, devfd;
209         ssize_t s;
210
211         devfd = open(rnc.device, O_RDWR | O_DIRECT);
212         if (devfd == -1)
213                 return errno == EBUSY ? -EBUSY : -EINVAL;
214
215         if (posix_memalign((void *)&buf, alignment(devfd), block_size)) {
216                 r = -ENOMEM;
217                 goto out;
218         }
219
220         s = read(devfd, buf, block_size);
221         if (s < 0 || s != block_size) {
222                 log_verbose(_("Cannot read device %s.\n"), rnc.device);
223                 close(devfd);
224                 return -EIO;
225         }
226
227         if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L)) {
228                 log_dbg("Marking LUKS device %s unusable.", rnc.device);
229                 memcpy(buf, NOMAGIC, MAGIC_L);
230                 r = 0;
231
232         } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L)) {
233                 log_dbg("Marking LUKS device %s usable.", rnc.device);
234                 memcpy(buf, MAGIC, MAGIC_L);
235                 r = 0;
236         } else if (set_magic == CHECK_UNUSABLE) {
237                 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
238                 if (!r)
239                         rnc.device_uuid = strndup(&buf[0xa8], 40);
240                 goto out;
241         } else
242                 r = -EINVAL;
243
244         if (!r) {
245                 if (lseek(devfd, 0, SEEK_SET) == -1)
246                         goto out;
247                 s = write(devfd, buf, block_size);
248                 if (s < 0 || s != block_size) {
249                         log_verbose(_("Cannot write device %s.\n"), rnc.device);
250                         r = -EIO;
251                 }
252         } else
253                 log_dbg("LUKS signature check failed for %s.", rnc.device);
254 out:
255         if (buf)
256                 memset(buf, 0, block_size);
257         free(buf);
258         close(devfd);
259         return r;
260 }
261
262 static int create_empty_header(const char *new_file, uint64_t size)
263 {
264         int fd, r = 0;
265         char *buf;
266
267         log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
268
269         if (!(buf = malloc(size)))
270                 return -ENOMEM;
271         memset(buf, 0, size);
272
273         fd = creat(new_file, S_IRUSR|S_IWUSR);
274         if(fd == -1) {
275                 free(buf);
276                 return -EINVAL;
277         }
278
279         if (write(fd, buf, size) < size)
280                 r = -EIO;
281
282         close(fd);
283         free(buf);
284         return r;
285 }
286
287 static int write_log(void)
288 {
289         static char buf[512];
290         ssize_t r;
291
292         //log_dbg("Updating LUKS reencryption log offset %" PRIu64 ".", offset);
293         memset(buf, 0, sizeof(buf));
294         snprintf(buf, sizeof(buf), "# 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, sizeof(buf));
302         if (r < 0 || r != sizeof(buf))
303                 return -EIO;
304
305         return 0;
306 }
307
308 static int parse_line_log(const char *line)
309 {
310         uint64_t u64;
311         int i;
312         char s[64];
313
314         /* comment */
315         if (*line == '#')
316                 return 0;
317
318         if (sscanf(line, "version = %d", &i) == 1) {
319                 if (i != 1) {
320                         log_dbg("Log: Unexpected version = %i", i);
321                         return -EINVAL;
322                 }
323         } else if (sscanf(line, "UUID = %40s", s) == 1) {
324                 if (!rnc.device_uuid || strcmp(rnc.device_uuid, s)) {
325                         log_dbg("Log: Unexpected UUID %s", s);
326                         return -EINVAL;
327                 }
328         } else if (sscanf(line, "direction = %d", &i) == 1) {
329                 log_dbg("Log: direction = %i", i);
330                 rnc.reencrypt_direction = i;
331         } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
332                 log_dbg("Log: offset = %" PRIu64, u64);
333                 rnc.device_offset = u64;
334         } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
335                 log_dbg("Log: shift = %" PRIu64, u64);
336                 rnc.device_shift = u64;
337         } else
338                 return -EINVAL;
339
340         return 0;
341 }
342
343 static int parse_log(void)
344 {
345         static char buf[512];
346         char *start, *end;
347         ssize_t s;
348
349         s = read(rnc.log_fd, buf, sizeof(buf));
350         if (s == -1)
351                 return -EIO;
352
353         buf[511] = '\0';
354         start = buf;
355         do {
356                 end = strchr(start, '\n');
357                 if (end) {
358                         *end++ = '\0';
359                         if (parse_line_log(start)) {
360                                 log_err("Wrong log format.\n");
361                                 return -EINVAL;
362                         }
363                 }
364
365                 start = end;
366         } while (start);
367
368         return 0;
369 }
370
371 static int open_log(void)
372 {
373         int flags;
374         struct stat st;
375
376         if(stat(rnc.log_file, &st) < 0) {
377                 log_dbg("Creating LUKS reencryption log file %s.", rnc.log_file);
378
379                 // FIXME: move that somewhere else
380                 rnc.reencrypt_direction = BACKWARD;
381
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                 CRYPT_ANY_SLOT, rnc.password, rnc.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                 CRYPT_ANY_SLOT, rnc.password, rnc.passwordLen,
432                 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
433                 goto out;
434 out:
435         crypt_free(cd);
436         crypt_free(cd_new);
437         return r;
438 }
439
440 static int backup_luks_headers(void)
441 {
442         struct crypt_device *cd = NULL, *cd_new = NULL;
443         struct crypt_params_luks1 params = {0};
444         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
445         int r;
446
447         log_dbg("Creating LUKS header backup for device %s.", rnc.device);
448         if ((r = crypt_init(&cd, rnc.device)) ||
449             (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
450                 goto out;
451
452         crypt_set_confirm_callback(cd, NULL, NULL);
453         if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rnc.header_file_org)))
454                 goto out;
455
456         if ((r = create_empty_header(rnc.header_file_new,
457                                      crypt_get_data_offset(cd) * 512)))
458                 goto out;
459
460         params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
461         params.data_alignment = crypt_get_data_offset(cd);
462         params.data_device = rnc.device;
463
464         if ((r = crypt_init(&cd_new, rnc.header_file_new)))
465                 goto out;
466
467         if (opt_random)
468                 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
469         else if (opt_urandom)
470                 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
471
472         if (opt_iteration_time)
473                 crypt_set_iteration_time(cd_new, opt_iteration_time);
474
475         if (opt_cipher) {
476                 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
477                 if (r < 0) {
478                         log_err(_("No known cipher specification pattern detected.\n"));
479                         goto out;
480                 }
481         }
482
483         if ((r = crypt_format(cd_new, CRYPT_LUKS1,
484                         opt_cipher ? cipher : crypt_get_cipher(cd),
485                         opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
486                         crypt_get_uuid(cd),
487                         NULL, crypt_get_volume_key_size(cd), &params)))
488                 goto out;
489
490         if ((r = crypt_keyslot_add_by_volume_key(cd_new, rnc.keyslot,
491                                 NULL, 0, rnc.password, rnc.passwordLen)) < 0)
492                 goto out;
493
494 out:
495         crypt_free(cd);
496         crypt_free(cd_new);
497         return r;
498 }
499
500 static void remove_headers(void)
501 {
502         struct crypt_device *cd = NULL;
503
504         if (crypt_init(&cd, NULL))
505                 return;
506         crypt_set_log_callback(cd, _quiet_log, NULL);
507         (void)crypt_deactivate(cd, rnc.header_file_org);
508         (void)crypt_deactivate(cd, rnc.header_file_new);
509         crypt_free(cd);
510 }
511
512 static int restore_luks_header(const char *backup)
513 {
514         struct crypt_device *cd = NULL;
515         int r;
516
517         r = crypt_init(&cd, rnc.device);
518
519         if (r == 0) {
520                 crypt_set_confirm_callback(cd, NULL, NULL);
521                 r = crypt_header_restore(cd, CRYPT_LUKS1, backup);
522         }
523
524         crypt_free(cd);
525         return r;
526 }
527
528 void print_progress(uint64_t bytes, int final)
529 {
530         uint64_t mbytes = bytes / 1024 / 1024;
531         struct timeval now_time;
532         double tdiff;
533
534         gettimeofday(&now_time, NULL);
535         if (!final && time_diff(rnc.end_time, now_time) < 0.5)
536                 return;
537
538         rnc.end_time = now_time;
539
540         if (opt_batch_mode)
541                 return;
542
543         tdiff = time_diff(rnc.start_time, rnc.end_time);
544         if (!tdiff)
545                 return;
546
547         log_err("\33[2K\rProgress: %5.1f%%, time elapsed %3.1f seconds, %4"
548                 PRIu64 " MB written, speed %5.2f MB/s%s",
549                 (double)bytes / rnc.device_size * 100,
550                 time_diff(rnc.start_time, rnc.end_time),
551                 mbytes, (double)(mbytes) / tdiff,
552                 final ? "\n" :"");
553 }
554
555 static int copy_data_forward(int fd_old, int fd_new, size_t block_size, void *buf, uint64_t *bytes)
556 {
557         ssize_t s1, s2;
558
559         *bytes = rnc.device_offset;
560         while (!quit && rnc.device_offset < rnc.device_size) {
561                 s1 = read(fd_old, buf, block_size);
562                 if (s1 < 0 || (s1 != block_size && (rnc.device_offset + s1) != rnc.device_size)) {
563                         log_err("Read error, expecting %d, got %d.\n", (int)block_size, (int)s1);
564                         return -EIO;
565                 }
566                 s2 = write(fd_new, buf, s1);
567                 if (s2 < 0) {
568                         log_err("Write error, expecting %d, got %d.\n", (int)block_size, (int)s2);
569                         return -EIO;
570                 }
571                 rnc.device_offset += s1;
572                 if (opt_write_log && write_log() < 0) {
573                         log_err("Log write error, some data are perhaps lost.\n");
574                         return -EIO;
575                 }
576
577                 *bytes += (uint64_t)s2;
578                 print_progress(*bytes, 0);
579         }
580
581         return quit ? -EAGAIN : 0;
582 }
583
584 static int copy_data_backward(int fd_old, int fd_new, size_t block_size, void *buf, uint64_t *bytes)
585 {
586         ssize_t s1, s2, working_block;
587         off64_t working_offset;
588
589         *bytes = rnc.device_size - rnc.device_offset;
590         while (!quit && rnc.device_offset) {
591                 if (rnc.device_offset < block_size) {
592                         working_offset = 0;
593                         working_block = rnc.device_offset;
594                 } else {
595                         working_offset = rnc.device_offset - block_size;
596                         working_block = block_size;
597                 }
598
599                 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
600                     lseek64(fd_new, working_offset, SEEK_SET) < 0) {
601                         log_err("Cannot seek to device offset.\n");
602                         return -EIO;
603                 }
604
605                 s1 = read(fd_old, buf, working_block);
606                 if (s1 < 0 || (s1 != working_block)) {
607                         log_err("Read error, expecting %d, got %d.\n", (int)block_size, (int)s1);
608                         return -EIO;
609                 }
610                 s2 = write(fd_new, buf, working_block);
611                 if (s2 < 0) {
612                         log_err("Write error, expecting %d, got %d.\n", (int)block_size, (int)s2);
613                         return -EIO;
614                 }
615                 rnc.device_offset -= s1;
616                 if (opt_write_log && write_log() < 0) {
617                         log_err("Log write error, some data are perhaps lost.\n");
618                         return -EIO;
619                 }
620
621                 *bytes += (uint64_t)s2;
622                 print_progress(*bytes, 0);
623         }
624
625         return quit ? -EAGAIN : 0;
626 }
627
628 static int copy_data(void)
629 {
630         size_t block_size = opt_bsize * 1024 * 1024;
631         int fd_old = -1, fd_new = -1;
632         int r = -EINVAL;
633         void *buf = NULL;
634         uint64_t bytes = 0;
635
636         fd_old = open(rnc.crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
637         if (fd_old == -1)
638                 goto out;
639
640         fd_new = open(rnc.crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
641         if (fd_new == -1)
642                 goto out;
643
644         if (lseek(fd_old, rnc.device_offset, SEEK_SET) == -1)
645                 goto out;
646
647         if (lseek(fd_new, rnc.device_offset, SEEK_SET) == -1)
648                 goto out;
649
650         /* Check size */
651         if (ioctl(fd_old, BLKGETSIZE64, &rnc.device_size) < 0)
652                 goto out;
653
654         if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
655                 r = -ENOMEM;
656                 goto out;
657         }
658
659         set_int_handler();
660         // FIXME: all this should be in init
661         if (!rnc.in_progress && rnc.reencrypt_direction == BACKWARD)
662                 rnc.device_offset = rnc.device_size;
663
664         gettimeofday(&rnc.start_time, NULL);
665
666         if (rnc.reencrypt_direction == FORWARD)
667                 r = copy_data_forward(fd_old, fd_new, block_size, buf, &bytes);
668         else
669                 r = copy_data_backward(fd_old, fd_new, block_size, buf, &bytes);
670
671         set_int_block(1);
672         print_progress(bytes, 1);
673
674         if (r < 0)
675                 log_err("ERROR during reencryption.\n");
676
677         if (write_log() < 0)
678                 log_err("Log write error, ignored.\n");
679
680 out:
681         if (fd_old != -1)
682                 close(fd_old);
683         if (fd_new != -1)
684                 close(fd_new);
685         free(buf);
686         return r;
687 }
688
689 static int initialize_uuid(void)
690 {
691         struct crypt_device *cd = NULL;
692         int r;
693
694         /* Try to load LUKS from device */
695         if ((r = crypt_init(&cd, rnc.device)))
696                 return r;
697         crypt_set_log_callback(cd, _quiet_log, NULL);
698         r = crypt_load(cd, CRYPT_LUKS1, NULL);
699         if (!r)
700                 rnc.device_uuid = strdup(crypt_get_uuid(cd));
701         else
702                 /* Reencryption already in progress - magic header? */
703                 r = device_magic(CHECK_UNUSABLE);
704
705         crypt_free(cd);
706         return r;
707 }
708
709 static int initialize_passphrase(const char *device)
710 {
711         struct crypt_device *cd = NULL;
712         int r;
713
714         if ((r = crypt_init(&cd, device)) ||
715             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
716             (r = crypt_set_data_device(cd, rnc.device)))
717                 goto out;
718
719         if ((r = crypt_get_key(_("Enter LUKS passphrase: "),
720                           &rnc.password, &rnc.passwordLen,
721                           0, 0, opt_key_file,
722                           0, 0, cd)) <0)
723                 goto out;
724
725         if ((r = crypt_activate_by_passphrase(cd, NULL,
726                 CRYPT_ANY_SLOT, rnc.password, rnc.passwordLen, 0) < 0))
727                 goto out;
728
729         if (r >= 0) {
730                 rnc.keyslot = r;
731                 r = 0;
732         }
733 out:
734         crypt_free(cd);
735         return r;
736 }
737
738 static int initialize_context(const char *device)
739 {
740         log_dbg("Initialising reencryption context.");
741
742         rnc.log_fd =-1;
743
744         if (!(rnc.device = strndup(device, PATH_MAX)))
745                 return -ENOMEM;
746 /*
747         if (opt_new_file && !create_uuid()) {
748                 log_err("Cannot create fake header.\n");
749                 return -EINVAL;
750         }
751 */
752         if (initialize_uuid()) {
753                 log_err("No header found on device.\n");
754                 return -EINVAL;
755         }
756
757         /* Prepare device names */
758         if (snprintf(rnc.log_file, PATH_MAX,
759                      "LUKS-%s.log", rnc.device_uuid) < 0)
760                 return -ENOMEM;
761         if (snprintf(rnc.header_file_org, PATH_MAX,
762                      "LUKS-%s.org", rnc.device_uuid) < 0)
763                 return -ENOMEM;
764         if (snprintf(rnc.header_file_new, PATH_MAX,
765                      "LUKS-%s.new", rnc.device_uuid) < 0)
766                 return -ENOMEM;
767
768         /* Paths to encrypted devices */
769         if (snprintf(rnc.crypt_path_org, PATH_MAX,
770                      "%s/%s", crypt_get_dir(), rnc.header_file_org) < 0)
771                 return -ENOMEM;
772         if (snprintf(rnc.crypt_path_new, PATH_MAX,
773                      "%s/%s", crypt_get_dir(), rnc.header_file_new) < 0)
774                 return -ENOMEM;
775
776         remove_headers();
777
778         return open_log();
779 }
780
781 static void destroy_context(void)
782 {
783         log_dbg("Destroying reencryption context.");
784
785         close_log();
786         remove_headers();
787
788         if ((rnc.reencrypt_direction == FORWARD &&
789              rnc.device_offset == rnc.device_size) ||
790              rnc.device_offset == 0) {
791                 unlink(rnc.log_file);
792                 unlink(rnc.header_file_org);
793                 unlink(rnc.header_file_new);
794         }
795
796         crypt_safe_free(rnc.password);
797
798         free(rnc.device);
799         free(rnc.device_uuid);
800 }
801
802 int run_reencrypt(const char *device)
803 {
804         int r = -EINVAL;
805         if (initialize_context(device))
806                 goto out;
807
808         log_dbg("Running reencryption.");
809
810         if (!rnc.in_progress) {
811                 if ((r = initialize_passphrase(rnc.device)) ||
812                     (r = backup_luks_headers()) ||
813                     (r = device_magic(MAKE_UNUSABLE)))
814                         goto out;
815         } else {
816                 if ((r = initialize_passphrase(rnc.header_file_org)))
817                         goto out;
818         }
819
820         if ((r = activate_luks_headers()))
821                 goto out;
822
823         if ((r = copy_data()))
824                 goto out;
825
826         r = restore_luks_header(rnc.header_file_new);
827 out:
828         destroy_context();
829         return r;
830 }
831
832 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
833                                              int exitcode, const char *error,
834                                              const char *more)
835 {
836         poptPrintUsage(popt_context, stderr, 0);
837         if (error)
838                 log_err("%s: %s\n", more, error);
839         poptFreeContext(popt_context);
840         exit(exitcode);
841 }
842
843 static void help(poptContext popt_context,
844                  enum poptCallbackReason reason __attribute__((unused)),
845                  struct poptOption *key,
846                  const char *arg __attribute__((unused)),
847                  void *data __attribute__((unused)))
848 {
849         usage(popt_context, EXIT_SUCCESS, NULL, NULL);
850 }
851
852 static void _dbg_version_and_cmd(int argc, const char **argv)
853 {
854         int i;
855
856         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
857         for (i = 0; i < argc; i++) {
858                 if (i)
859                         log_std(" ");
860                 log_std("%s", argv[i]);
861         }
862         log_std("\"\n");
863 }
864
865 int main(int argc, const char **argv)
866 {
867         static struct poptOption popt_help_options[] = {
868                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
869                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
870                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
871                 POPT_TABLEEND
872         };
873         static struct poptOption popt_options[] = {
874                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
875                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
876                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
877                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
878                 { "block-size",        'B',  POPT_ARG_INT, &opt_bsize,                  0, N_("Reencryption block size"), N_("MB") },
879                 { "new-header",        'N',  POPT_ARG_INT, &opt_new,                    0, N_("Create new header, need size on the end of device"), N_("MB") },
880                 { "new-crypt",         'f',  POPT_ARG_STRING, &opt_new_file,            0, N_("Log suffix for new reencryption file."), NULL },
881                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
882                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
883                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
884                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
885                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
886                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
887                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
888                 { "use-directio",      '\0', POPT_ARG_NONE, &opt_directio,              0, N_("Use direct-io when accesing devices."), NULL },
889                 { "write-log",         '\0', POPT_ARG_NONE, &opt_write_log,             0, N_("Update log file after every block."), NULL },
890                 POPT_TABLEEND
891         };
892         poptContext popt_context;
893         int r;
894
895         crypt_set_log_callback(NULL, _log, NULL);
896         log_err("WARNING: this is experimental code, it can completely break your data.\n");
897
898         set_int_block(1);
899
900         setlocale(LC_ALL, "");
901         bindtextdomain(PACKAGE, LOCALEDIR);
902         textdomain(PACKAGE);
903
904         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
905         poptSetOtherOptionHelp(popt_context,
906                                N_("[OPTION...] <device>]"));
907
908         while((r = poptGetNextOpt(popt_context)) > 0) {
909                 if (r < 0)
910                         break;
911         }
912
913         if (r < -1)
914                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
915                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
916         if (opt_version_mode) {
917                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
918                 poptFreeContext(popt_context);
919                 exit(EXIT_SUCCESS);
920         }
921
922         action_argv = poptGetArgs(popt_context);
923         if(!action_argv)
924                 usage(popt_context, EXIT_FAILURE, _("Argument required."),
925                       poptGetInvocationName(popt_context));
926
927         if (opt_random && opt_urandom)
928                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
929                       poptGetInvocationName(popt_context));
930
931         if (opt_new && !opt_new_file)
932                 usage(popt_context, EXIT_FAILURE, _("You have to use -f with -N."),
933                       poptGetInvocationName(popt_context));
934
935         if (opt_debug) {
936                 opt_verbose = 1;
937                 crypt_set_debug_level(-1);
938                 _dbg_version_and_cmd(argc, argv);
939         }
940
941         r = run_reencrypt(action_argv[0]);
942
943         poptFreeContext(popt_context);
944
945         /* Translate exit code to simple codes */
946         switch (r) {
947         case 0:         r = EXIT_SUCCESS; break;
948         case -EEXIST:
949         case -EBUSY:    r = 5; break;
950         case -ENOTBLK:
951         case -ENODEV:   r = 4; break;
952         case -ENOMEM:   r = 3; break;
953         case -EPERM:    r = 2; break;
954         case -EAGAIN: log_err(_("Interrupted by a signal.\n"));
955         case -EINVAL:
956         case -ENOENT:
957         case -ENOSYS:
958         default:        r = EXIT_FAILURE;
959         }
960         return r;
961 }