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